-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcell_tracking.py
145 lines (118 loc) · 5.54 KB
/
cell_tracking.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 11:59:20 2019
@author: Nat Kinsky
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mp
import scipy.io as sio
import scipy.ndimage as sim
from os import path
import session_directory as sd
from session_directory import load_session_list
import er_plot_functions as er
from mouse_sessions import make_session_list
from plot_helper import ScrollPlot
from er_gen_functions import plot_tmap_us, plot_tmap_sm, plot_events_over_pos
# from progressbar import ProgressBar # NK need a better version of this
from tqdm import tqdm
from pickle import dump, load
# Make text save as whole words
plt.rcParams['pdf.fonttype'] = 42
def get_num_neurons(mouse, date, session, er_arena=None, er_day=None):
"""Gets number of neurons in a given session.
:param mouse:
:param arena:
:param day:
:param list_dir:
:return: nneurons: # neurons in a session
"""
if er_arena is None:
dir_use = sd.find_session_directory(mouse, date, session)
else:
dir_use = sd.find_eraser_directory(mouse, er_arena, er_day)
im_data_file = path.join(dir_use, 'FinalOutput.mat')
im_data = sio.loadmat(im_data_file, variable_names='NumNeurons')
# PSAbool = im_data['PSAbool']
nneurons = im_data['NumNeurons'][0][0]
return nneurons
def get_group_num_neurons(mice, days=[-2, -1, 4, 1, 2, 7], arenas=['Shock', 'Open']):
"""Gets # neurons for all mice/days/arenas specified
:param mice: list
:param days: list
:param arenas: list
:return: nneurons_all: nmice x ndays x narenas ndarray
"""
nneurons = np.ones((len(mice), len(arenas), len(days))) * np.nan
for idm, mouse in enumerate(mice):
for ida, arena in enumerate(arenas):
for idd, day in enumerate(days):
try:
nneurons[idm, ida, idd] = get_num_neurons(mouse, '', '',
er_arena=arena, er_day=day)
except TypeError:
print('Missing neural data file for ' + mouse + ' Day ' + str(day) + ' ' + arena)
return nneurons
def plot_num_neurons(nneurons, arena1='Shock', arena2='Open', day_labels=('-2', '-1', '4hr', '1', '2', '7'),
normalize=False, offset=(-0.05, 0.05), jitter=0.05, colors = ('b', 'r'), ax=None, **kwargs):
"""
Plots # neurons active in each arena on a given day. For eraser but could be used elsewhere
:param nneurons: nmice x ndays x narenas array. arena1/2 = shock/open by default
:param arena1/2: arena labels default1/2 = 'Shock'/'Open'.
:param normalize: boolean False(default) = do not normalize, otherwise takes a
string = day to normalize to, e.g. '-1' or '7'
:param kwargs: inputs to matplotlib.pyplot.plot
:return: fig, ax
"""
nmice, narenas, ndays = nneurons.shape
offset = (offset,) if isinstance(offset, float) else offset
assert len(offset) == narenas, 'Must enter offset amount for each arena'
if ax is None:
fig, ax = plt.subplots()
else:
fig = ax.figure
# normalize nneurons to day indicated
assert isinstance(normalize, (str, list, bool))
if normalize is not False:
normalize = [normalize] if isinstance(normalize, str) else normalize
norm_sesh_ind = [day_labels.index(i) for i in day_labels if i in normalize]
nneurons = norm_num_neurons(nneurons, norm_sesh_ind)
ax.plot(np.matlib.repmat(np.arange(0, ndays), nmice, 1) + offset[0] + np.random.uniform(-jitter, jitter, (nmice, ndays)),
nneurons[:, 0, :], color=colors[0], marker='o', linestyle='None', **kwargs)
lineshock, = ax.plot(np.arange(0, ndays) + offset[0], np.nanmean(nneurons[:, 0, :], axis=0),
color=colors[0], marker=None, linestyle='-', **kwargs)
if narenas == 2:
ax.plot(np.matlib.repmat(np.arange(0, ndays), nmice, 1) + offset[1] + np.random.uniform(-jitter, jitter, (nmice, ndays)),
nneurons[:, 1, :], color=colors[1], marker='o', linestyle='None', **kwargs)
lineopen, = ax.plot(np.arange(0, ndays) + offset[1], np.nanmean(nneurons[:, 1, :], axis=0),
color=colors[1], marker=None, linestyle='-', **kwargs)
plt.legend((lineshock, lineopen), (arena1, arena2))
if normalize is False:
ax.set_ylabel('# Neurons')
else:
ax.set_ylabel(f'Norm. # Neurons {norm_sesh_ind}=ref')
ax.set_xlabel('Day')
ax.set_xticks(np.arange(0, ndays))
ax.set_xticklabels(day_labels)
return fig, ax
def norm_num_neurons(nneurons, norm_sesh_ind: list or float):
"""Normalize nneurons to a particular session
:param nneurons: nmice x narenas x ndays array of active neurons
:param norm_sesh_ind: index in dimension 1 (days) to normalize to. Default = 0.
:return: nnorm:
"""
nmice, narenas, ndays = nneurons.shape
assert isinstance(norm_sesh_ind, (int, list))
norm_sesh_ind = norm_sesh_ind if isinstance(norm_sesh_ind, list) else [norm_sesh_ind]
nnorm = nneurons.reshape(narenas * nmice, ndays) / \
np.mean(nneurons[:, :, norm_sesh_ind], axis=2).reshape(narenas * nmice, -1)
nnorm = nnorm.reshape((nmice, narenas, ndays))
### Old code here where I had ndays in dim 1. above should be better.
# nnorm = nneurons.swapaxes(1, 2).reshape(narenas * nmice, ndays) / \
# nneurons[:, norm_sesh_ind, :].reshape(narenas * nmice, -1).copy()
# nnorm = nnorm.reshape((nmice, narenas, ndays)).swapaxes(2, 1)
return nnorm
if __name__ == '__main__':
get_num_neurons('Marble12', 'Open', -2)
pass