-
Notifications
You must be signed in to change notification settings - Fork 1
/
dmn_bwm.py
4361 lines (3277 loc) · 143 KB
/
dmn_bwm.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from one.api import ONE
from brainbox.singlecell import bin_spikes2D
from brainwidemap import (bwm_query, load_good_units,
load_trials_and_mask, bwm_units)
from iblatlas.atlas import AllenAtlas
from iblatlas.regions import BrainRegions
import iblatlas
from iblatlas.plots import plot_swanson_vector
from brainbox.io.one import SessionLoader
import ephys_atlas.data
#from reproducible_ephys_functions import figure_style, labs
import sys
sys.path.append('Dropbox/scripts/IBL/')
from granger import get_volume, get_centroids, get_res, get_structural, get_ari
from state_space_bwm import get_cmap_bwm, pre_post
from bwm_figs import variverb
from scipy import signal
import pandas as pd
import numpy as np
from collections import Counter
from sklearn.decomposition import PCA, FastICA
from sklearn.cluster import KMeans, SpectralClustering, SpectralCoclustering
from sklearn.manifold import TSNE
from scipy.cluster.hierarchy import linkage, fcluster, dendrogram
from statsmodels.stats.multitest import multipletests
from numpy.linalg import norm
from scipy.stats import (gaussian_kde, f_oneway,
pearsonr, spearmanr, kruskal, rankdata, linregress)
from scipy.spatial import distance
from scipy.cluster import hierarchy
from scipy.spatial.distance import squareform, cdist
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import StandardScaler
from random import shuffle
from sklearn.linear_model import LogisticRegression
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import StratifiedKFold
from joblib import Parallel, delayed
from sklearn.utils import parallel_backend
import gc
from pathlib import Path
import random
from copy import deepcopy
import time, sys, math, string, os
from scipy.stats import spearmanr, zscore
import umap.umap_ as umap
from rastermap import Rastermap
from scipy.stats import wasserstein_distance
from itertools import combinations, chain
from datetime import datetime
import scipy.ndimage as ndi
import hdbscan
from matplotlib.axis import Axis
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from matplotlib.gridspec import GridSpec
import mpldatacursor
from matplotlib.lines import Line2D
from matplotlib.colors import to_rgba
from matplotlib.patches import Rectangle
from matplotlib.ticker import ScalarFormatter
from matplotlib.ticker import MaxNLocator
from matplotlib.pyplot import cm
from venny4py.venny4py import *
import warnings
warnings.filterwarnings("ignore")
#mpl.use('QtAgg')
plt.ion()
np.set_printoptions(threshold=sys.maxsize)
plt.rcParams.update(plt.rcParamsDefault)
plt.ion()
f_size = 15 # font size
# canonical colors for left and right trial types
blue_left = [0.13850039, 0.41331206, 0.74052025]
red_right = [0.66080672, 0.21526712, 0.23069468]
T_BIN = 0.0125 # bin size [sec] for neural binning
sts = 0.002 # stride size in [sec] for overlapping bins
ntravis = 30 # #trajectories for vis, first 2 real, rest pseudo
# conversion divident to get bins in seconds
# (taking strinding into account)
c_sec = int(T_BIN // sts) / T_BIN
one = ONE()
#base_url='https://openalyx.internationalbrainlab.org',
# password='international', silent=True
br = BrainRegions()
#units_df = bwm_units(one) # canonical set of cells
# save results here
pth_dmn = Path(one.cache_dir, 'dmn', 'res')
pth_dmn.mkdir(parents=True, exist_ok=True)
sigl = 0.05 # significance level (for stacking, plotting, fdr)
# order sensitive: must be tts__ = concat_PETHs(pid, get_tts=True).keys()
tts__ = ['inter_trial', 'blockL', 'blockR', 'block50',
'quiescence', 'stimLbLcL', 'stimLbRcL', 'stimLbRcR',
'stimLbLcR', 'stimRbLcL', 'stimRbRcL', 'stimRbRcR',
'stimRbLcR', 'motor_init', 'sLbLchoiceL', 'sLbRchoiceL',
'sLbRchoiceR', 'sLbLchoiceR', 'sRbLchoiceL', 'sRbRchoiceL',
'sRbRchoiceR', 'sRbLchoiceR', 'choiceL', 'choiceR',
'fback1', 'fback0']
PETH_types_dict = {
'concat': [item for item in tts__],
'resting': ['inter_trial'],
'quiescence': ['quiescence'],
'pre-stim-prior': ['blockL', 'blockR'],
'block50': ['block50'],
'stim_surp_incon': ['stimLbRcL','stimRbLcR'],
'stim_surp_con': ['stimLbLcL', 'stimRbRcR'],
'stim_all': ['stimLbRcL','stimRbLcR','stimLbLcL', 'stimRbRcR'],
'motor_init': ['motor_init'],
'fback1': ['fback1'],
'fback0': ['fback0']}
# https://github.com/XY-DIng/mouse_dist_wm/blob/main/results/area_list.csv
harris_hierarchy = [
"VISp", "AUDp", "SSp-ll", "AUDd", "SSp-n", "SSp-ul", "AIp", "SSp-m",
"SSp-un", "SSp-bfd", "VISl", "AUDv", "SSs", "VISC", "SSp-tr", "VISli",
"MOp", "VISrl", "VISpl", "RSPv", "RSPd", "GU", "RSPagl", "PERI", "ECT",
"VISal", "ILA", "ORBl", "AId", "VISpm", "ORBm", "PL", "VISpor", "FRP",
"AUDpo", "TEa", "VISa", "VISam"
]
def put_panel_label(ax, k):
ax.annotate(string.ascii_lowercase[k], (-0.05, 1.15),
xycoords='axes fraction',
fontsize=f_size * 1.5, va='top',
ha='right', weight='bold')
def grad(c, nobs, fr=1):
'''
color gradient for plotting trajectories
c: color map type
nobs: number of observations
'''
cmap = mpl.cm.get_cmap(c)
return [cmap(fr * (nobs - p) / nobs) for p in range(nobs)]
def eid_probe2pid(eid, probe_name):
df = bwm_query(one)
return df[np.bitwise_and(df['eid'] == eid,
df['probe_name'] == probe_name
)]['pid'].values[0]
def cosine_sim(v0, v1):
# cosine similarity
return np.inner(v0,v1)/ (norm(v0) * norm(v1))
def fn2_eid_probe_pid(u):
'''
file name u to eid, probe, pid
'''
return [u.split('_')[0], u.split('_')[1].split('.')[0],
eid_probe2pid(u.split('_')[0],
u.split('_')[1].split('.')[0])]
def get_name(brainregion):
'''
get verbose name for brain region acronym
'''
regid = br.id[np.argwhere(br.acronym == brainregion)][0, 0]
return br.name[np.argwhere(br.id == regid)[0, 0]]
def get_eid_info(eid):
'''
return counter of regions for a given session
'''
units_df = bwm_units(one)
return Counter(units_df[units_df['eid']==eid]['Beryl'])
def get_sess_per(reg, t='pid'):
'''
return bwm insertions that have this region
'''
units_df = bwm_units(one)
print(f'listing {t} per region')
return Counter(units_df[units_df['Beryl'] == reg][t])
def eid2pids(eid):
'''
return pids for a given eid
'''
units_df = bwm_units(one)
return Counter(units_df[units_df['eid'] == eid]['pid'])
def deep_in_block(trials, pleft, depth=10):
'''
get mask for trials object of pleft trials that are
"depth" trials into the block
'''
# pleft trial indices
ar = np.arange(len(trials))[trials['probabilityLeft'] == pleft]
# pleft trial indices shifted by depth earlier
ar_shift = ar - depth
# trial indices where shifted ones are in block
ar_ = ar[trials['probabilityLeft'][ar_shift] == pleft]
# transform into mask for all trials
bool_array = np.full(len(trials), False, dtype=bool)
bool_array[ar_] = True
return bool_array
def concat_PETHs(pid, get_tts=False, vers='concat'):
'''
for each cell concat all possible PETHs
vers: different PETH set
vers == 'contrast': extra analyiss for BWM reviewer;
check for zero contrast effects
have PETHs aligned to main events; irrespective of type
'''
eid, probe = one.pid2eid(pid)
# Load in trials data and mask bad trials (False if bad)
trials, mask = load_trials_and_mask(one, eid,
saturation_intervals=['saturation_stim_plus04',
'saturation_feedback_plus04',
'saturation_move_minus02',
'saturation_stim_minus04_minus01',
'saturation_stim_plus06',
'saturation_stim_minus06_plus06'])
if vers == 'concat':
# define align, trial type, window length
# For the 'inter_trial' mask trials with too short iti
idcs = [0]+ list(np.where((trials['stimOn_times'].values[1:]
- trials['intervals_1'].values[:-1])>1.15)[0]+1)
mask_iti = [True if i in idcs else False
for i in range(len(trials['stimOn_times']))]
# all sorts of PETHs, some for the surprise conditions
# need to be 10 trials into a block, see - 10
tts = {
'inter_trial': ['stimOn_times',
np.bitwise_and.reduce([mask, mask_iti]),
[1.15, -1]],
'blockL': ['stimOn_times',
np.bitwise_and.reduce([mask,
trials['probabilityLeft'] == 0.8]),
[0.4, -0.1]],
'blockR': ['stimOn_times',
np.bitwise_and.reduce([mask,
trials['probabilityLeft'] == 0.2]),
[0.4, -0.1]],
'block50': ['stimOn_times',
np.bitwise_and.reduce([mask,
trials['probabilityLeft'] == 0.5]),
[0.4, -0.1]],
'quiescence': ['stimOn_times', mask,
[0.4, -0.1]],
'stimLbLcL': ['stimOn_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastLeft']),
trials['probabilityLeft'] == 0.8,
deep_in_block(trials, 0.8),
trials['choice'] == 1]),
[0, 0.2]],
'stimLbRcL': ['stimOn_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastLeft']),
trials['probabilityLeft'] == 0.2,
deep_in_block(trials, 0.2),
trials['choice'] == 1]), [0, 0.2]],
'stimLbRcR': ['stimOn_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastLeft']),
trials['probabilityLeft'] == 0.2,
deep_in_block(trials, 0.2),
trials['choice'] == -1]),
[0, 0.2]],
'stimLbLcR': ['stimOn_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastLeft']),
trials['probabilityLeft'] == 0.8,
deep_in_block(trials, 0.8),
trials['choice'] == -1]),
[0, 0.2]],
'stimRbLcL': ['stimOn_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastRight']),
trials['probabilityLeft'] == 0.8,
deep_in_block(trials, 0.8),
trials['choice'] == 1]),
[0, 0.2]],
'stimRbRcL': ['stimOn_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastRight']),
trials['probabilityLeft'] == 0.2,
deep_in_block(trials, 0.2),
trials['choice'] == 1]),
[0, 0.2]],
'stimRbRcR': ['stimOn_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastRight']),
trials['probabilityLeft'] == 0.2,
deep_in_block(trials, 0.2),
trials['choice'] == -1]),
[0, 0.2]],
'stimRbLcR': ['stimOn_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastRight']),
trials['probabilityLeft'] == 0.8,
deep_in_block(trials, 0.8),
trials['choice'] == -1]),
[0, 0.2]],
'motor_init': ['firstMovement_times', mask,
[0.15, 0]],
'sLbLchoiceL': ['firstMovement_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastLeft']),
trials['probabilityLeft'] == 0.8,
trials['choice'] == 1]),
[0.15, 0]],
'sLbRchoiceL': ['firstMovement_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastLeft']),
trials['probabilityLeft'] == 0.2,
trials['choice'] == 1]),
[0.15, 0]],
'sLbRchoiceR': ['firstMovement_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastLeft']),
trials['probabilityLeft'] == 0.2,
trials['choice'] == -1]),
[0.15, 0]],
'sLbLchoiceR': ['firstMovement_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastLeft']),
trials['probabilityLeft'] == 0.8,
trials['choice'] == -1]),
[0.15, 0]],
'sRbLchoiceL': ['firstMovement_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastRight']),
trials['probabilityLeft'] == 0.8,
trials['choice'] == 1]),
[0.15, 0]],
'sRbRchoiceL': ['firstMovement_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastRight']),
trials['probabilityLeft'] == 0.2,
trials['choice'] == 1]),
[0.15, 0]],
'sRbRchoiceR': ['firstMovement_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastRight']),
trials['probabilityLeft'] == 0.2,
trials['choice'] == -1]),
[0.15, 0]],
'sRbLchoiceR': ['firstMovement_times',
np.bitwise_and.reduce([mask,
~np.isnan(trials[f'contrastRight']),
trials['probabilityLeft'] == 0.8,
trials['choice'] == -1]),
[0.15, 0]],
'choiceL': ['firstMovement_times',
np.bitwise_and.reduce([mask,
trials['choice'] == 1]),
[0, 0.15]],
'choiceR': ['firstMovement_times',
np.bitwise_and.reduce([mask,
trials['choice'] == -1]),
[0, 0.15]],
'fback1': ['feedback_times',
np.bitwise_and.reduce([mask,
trials['feedbackType'] == 1]),
[0, 0.3]],
'fback0': ['feedback_times',
np.bitwise_and.reduce([mask,
trials['feedbackType'] == -1]),
[0, 0.3]]}
elif vers == 'contrast':
# for latency plot based on coarse PETHs
# and extra control for auditory signal
tts = {'stim': ['stimOn_times', mask, [0, .15]],
'choice': ['firstMovement_times', mask, [0, 0.15]],
'fback': ['feedback_times', mask, [0, 0.15]],
'stim0': ['stimOn_times', np.bitwise_and(mask,
np.bitwise_or(trials[f'contrastRight'] == 0,
trials[f'contrastLeft'] == 0)),
[0, .15]]}
else:
print('what set of PETHs??')
return
if get_tts:
return tts
# load in spikes
spikes, clusters = load_good_units(one, pid)
assert len(
spikes['times']) == len(
spikes['clusters']), 'spikes != clusters'
D = {}
D['ids'] = np.array(clusters['atlas_id'])
D['xyz'] = np.array(clusters[['x','y','z']])
D['channels'] = np.array(clusters['channels'])
D['axial_um'] = np.array(clusters['axial_um'])
D['lateral_um'] = np.array(clusters['lateral_um'])
D['uuids'] = np.array(clusters['uuids'])
tls = {} # trial numbers for each type
ws = [] # list of binned data
for tt in tts:
event = trials[tts[tt][0]][np.bitwise_and.reduce([mask, tts[tt][1]])]
tls[tt] = len(event)
# bin and cut into trials
# overlapping time bins, bin size = T_BIN, stride = sts
# tts[key][-1][pre-event time, post-event time]
bis = []
st = int(T_BIN // sts)
for ts in range(st):
bi, _ = bin_spikes2D(
spikes['times'],
clusters['cluster_id'][spikes['clusters']],
clusters['cluster_id'],
np.array(event) + ts * sts,
tts[tt][-1][0], tts[tt][-1][1],
T_BIN)
bis.append(bi)
ntr, nn, nbin = bi.shape
ar = np.zeros((ntr, nn, st * nbin))
for ts in range(st):
ar[:, :, ts::st] = bis[ts]
# average squared firing rates across trials
ws.append(np.mean(ar**2, axis=0))
D['tls'] = tls
D['trial_names'] = list(tts.keys())
D['ws'] = ws
return D
def load_atlas_data():
LOCAL_DATA_PATH = Path(one.cache_dir, 'ephys_atlas_data')
D = {}
(D['df_raw_features'],
D['df_clusters'],
D['df_channels'],
D['df_probes']) = ephys_atlas.data.download_tables(
label='latest',
local_path=LOCAL_DATA_PATH,
one=one)
merged_df0 = D['df_raw_features'].merge(D['df_channels'],
on=['pid','channel'])
merged_df0.reset_index(inplace=True)
merged_df = merged_df0.merge(
D['df_clusters'],
on=['pid', 'axial_um', 'lateral_um'])
return merged_df
def get_allen_info(rerun=False):
'''
Function to load Allen atlas info, like region colors
'''
pth_dmna = Path(one.cache_dir, 'dmn', 'alleninfo.npy')
if (not pth_dmna.is_file() or rerun):
p = (Path(iblatlas.__file__).parent /
'allen_structure_tree.csv')
dfa = pd.read_csv(p)
# replace yellow by brown #767a3a
cosmos = []
cht = []
for i in range(len(dfa)):
try:
ind = dfa.iloc[i]['structure_id_path'].split('/')[4]
cr = br.id2acronym(ind, mapping='Cosmos')[0]
cosmos.append(cr)
if cr == 'CB':
cht.append('767A3A')
else:
cht.append(dfa.iloc[i]['color_hex_triplet'])
except:
cosmos.append('void')
cht.append('FFFFFF')
dfa['Cosmos'] = cosmos
dfa['color_hex_triplet2'] = cht
# get colors per acronym and transfomr into RGB
dfa['color_hex_triplet2'] = dfa['color_hex_triplet2'].fillna('FFFFFF')
dfa['color_hex_triplet2'] = dfa['color_hex_triplet2'
].replace('19399', '19399a')
dfa['color_hex_triplet2'] = dfa['color_hex_triplet2'].replace(
'0', 'FFFFFF')
dfa['color_hex_triplet2'] = '#' + dfa['color_hex_triplet2'].astype(str)
dfa['color_hex_triplet2'] = dfa['color_hex_triplet2'
].apply(lambda x:
mpl.colors.to_rgba(x))
palette = dict(zip(dfa.acronym, dfa.color_hex_triplet2))
palette['CB'] = (0.4627450980392157, 0.47843137254901963,
0.22745098039215686, 1.0)
palette['void'] = (0, 0, 0, 1)
palette['root'] = (0, 0, 0, 1)
#add layer colors
bc = ['b', 'g', 'r', 'c', 'm', 'y', 'brown', 'pink']
for i in range(7):
palette[str(i)] = bc[i]
palette['thal'] = 'k'
r = {}
r['dfa'] = dfa
r['palette'] = palette
np.save(pth_dmna, r, allow_pickle=True)
r = np.load(pth_dmna, allow_pickle=True).flat[0]
return r['dfa'], r['palette']
_,pal = get_allen_info()
def regional_group(mapping, vers='concat', ephys=True,
nclus = 13, rerun=False):
'''
mapping: how to color 2d points, say Beryl, layers, kmeans
find group labels for all cells
mapping: [Allen, Beryl, Cosmos, layers, clusters, clusters_xyz, 'in tts__']
'''
if mapping == 'kmeans':
pth__ = Path(one.cache_dir, 'dmn', 'kmeans_group.npy')
if ((pth__.is_file()) and (not rerun)):
return np.load(pth__,allow_pickle=True).flat[0]
r = np.load(Path(pth_dmn, f'{vers}_ephys{ephys}.npy'),
allow_pickle=True).flat[0]
# add point names to dict
r['nums'] = range(len(r['xyz'][:,0]))
if mapping == 'kmeans':
feat = 'concat_z'
nclus = nclus
kmeans = KMeans(n_clusters=nclus, random_state=3)
kmeans.fit(r[feat]) # kmeans in feature space
clusters = kmeans.labels_
cmap = mpl.cm.get_cmap('Spectral')
cols = cmap(clusters/nclus)
acs = clusters
regs = np.unique(clusters)
color_map = dict(zip(list(acs), list(cols)))
r['els'] = [Line2D([0], [0], color=color_map[reg],
lw=4, label=f'{reg + 1}')
for reg in regs]
av = None
elif mapping == 'cocluster':
feat = 'concat_z'
clusterer = SpectralCoclustering(n_clusters=nclus, random_state=0)
clusterer.fit(r[feat])
labels = clusterer.row_labels_
unique_labels = np.unique(labels)
mapping = {old_label: new_label
for new_label, old_label in
enumerate(unique_labels)}
clusters = np.array([mapping[label] for label in labels])
cmap = mpl.cm.get_cmap('Spectral')
cols = cmap(clusters/len(unique_labels))
acs = clusters
elif mapping == 'layers':
acs = np.array(br.id2acronym(r['ids'],
mapping='Allen'))
regs0 = Counter(acs)
# get regs with number at and of acronym
regs = [reg for reg in regs0
if reg[-1].isdigit()]
for reg in regs:
acs[acs == reg] = reg[-1]
# extra class of thalamic (and hypothalamic) regions
names = dict(zip(regs0,[get_name(reg) for reg in regs0]))
thal = {x:names[x] for x in names if 'thala' in names[x]}
for reg in thal:
acs[acs == reg] = 'thal'
mask = np.array([(x.isdigit() or x == 'thal') for x in acs])
acs[~mask] = '0'
remove_0 = True
if remove_0:
# also remove layer 6, as there are only 20 neurons
zeros = np.arange(len(acs))[
np.bitwise_or(acs == '0', acs == '6')]
for key in r:
if len(r[key]) == len(acs):
r[key] = np.delete(r[key], zeros, axis=0)
acs = np.delete(acs, zeros)
_,pa = get_allen_info()
cols = np.array([pa[reg] for reg in acs])
regs = Counter(acs)
r['els'] = [Line2D([0], [0], color=pa[reg],
lw=4, label=f'{reg} {regs[reg]}')
for reg in regs]
elif mapping == 'clusters_xyz':
# use clusters from hierarchical clustering to color
nclus = 1000
clusters = fcluster(r['linked_xyz'], t=nclus,
criterion='maxclust')
cmap = mpl.cm.get_cmap('Spectral')
cols = cmap(clusters/nclus)
acs = clusters
elif mapping in PETH_types_dict:
# For a group of PETH types defined in PETH_types_dict,
# concatenate the defined PETH segments and rank cells by mean score
feat = 'concat_z' # was _bd
assert vers == 'concat', 'vers needs to be concat for this'
assert feat == 'concat_z'
# Retrieve the list of PETH types to concatenate from PETH_types_dict
peth_types_to_concat = PETH_types_dict[mapping]
# Initialize a list to store the concatenated segments
concatenated_data = []
# Iterate through each PETH type in the list and concatenate the data
for peth_type in peth_types_to_concat:
# Extract relevant information from the data
# Get the start and end indices of the PETH segment
segment_names = list(r['len'].keys())
segment_lengths = list(r['len'].values())
start_idx = sum(segment_lengths[:segment_names.index(peth_type)])
end_idx = start_idx + r['len'][peth_type]
# Extract the segment of interest and append to concatenated_data
segment_data = r[feat][:, start_idx:end_idx]
concatenated_data.append(segment_data)
# Concatenate all the segments along the column axis
concatenated_data = np.concatenate(concatenated_data, axis=1)
# Compute the mean (max) for each neuron across the concatenated segment
means = np.mean(abs(concatenated_data), axis=1)
# Rank neurons based on their mean values
df = pd.DataFrame({'means': means})
df['rankings'] = df['means'].rank(method='min', ascending=False).astype(int)
r['rankings'] = df['rankings'].values
# Map neuron IDs to brain region acronyms (if needed)
acs = np.array(br.id2acronym(r['ids'], mapping='Beryl'))
# Apply a color map based on the rankings
cmap = mpl.cm.get_cmap('Spectral')
cols = cmap(r['rankings'] / max(r['rankings']))
# Count the occurrence of each brain region acronym
regs = Counter(acs)
elif mapping in tts__:
# for a specific PETH type,
# rank cells by mean score
feat = 'concat_z' # was _bd
assert vers == 'concat', 'vers needs to be concat for this'
assert feat == 'concat_z'
# Extract relevant information from the data
# Get the start and end indices of the PETH segment
segment_names = list(r['len'].keys())
segment_lengths = list(r['len'].values())
start_idx = sum(segment_lengths[:segment_names.index(mapping)])
end_idx = start_idx + r['len'][mapping]
# Extract the segment of interest
segment_data = r[feat][:, start_idx:end_idx]
# Compute the mean for each neuron across the segment
means = np.mean(abs(segment_data), axis=1)
# Get the ranking of neurons based on their mean values
df = pd.DataFrame({'means': means})
df['rankings'] = df['means'].rank(method='min',
ascending=False).astype(int)
r['rankings'] = df['rankings'].values
acs = np.array(br.id2acronym(r['ids'],
mapping='Beryl'))
cmap = mpl.cm.get_cmap('Spectral')
cols = cmap(r['rankings']/max(r['rankings']))
regs = Counter(acs)
elif mapping == 'functional':
funct = {
"FRP": "Prefrontal", "ACAd": "Prefrontal", "ACAv": "Prefrontal", "PL": "Prefrontal", "ILA": "Prefrontal",
"ORBl": "Prefrontal", "ORBm": "Prefrontal", "ORBvl": "Prefrontal",
"AId": "Lateral", "AIv": "Lateral", "AIp": "Lateral", "GU": "Lateral", "VISc": "Lateral",
"TEa": "Lateral", "PERI": "Lateral", "ECT": "Lateral",
"SSs": "Somatomotor", "SSp-bfd": "Somatomotor", "SSp-tr": "Somatomotor", "SSp-ll": "Somatomotor",
"SSp-ul": "Somatomotor", "SSp-un": "Somatomotor", "SSp-n": "Somatomotor", "SSp-m": "Somatomotor",
"MOp": "Somatomotor", "MOs": "Somatomotor",
"VISal": "Visual", "VISl": "Visual", "VISp": "Visual", "VISpl": "Visual",
"VISli": "Visual", "VISpor": "Visual", "VISrl": "Visual",
"VISa": "Medial", "VISam": "Medial", "VISpm": "Medial",
"RSPagl": "Medial", "RSPd": "Medial", "RSPv": "Medial",
"AUDd": "Auditory", "AUDp": "Auditory", "AUDpo": "Auditory", "AUDv": "Auditory"
}
cols0 = {
"Prefrontal": (0.78, 0.16, 0.16, 1.0), # Deep Red
"Lateral": (0.83, 0.79, 0.36, 1.0), # Yellow-green
"Somatomotor": (0.89, 0.63, 0.33, 1.0), # Light Orange
"Visual": (0.49, 0.73, 0.50, 1.0), # Light Green
"Medial": (0.53, 0.63, 0.83, 1.0), # Light Blue
"Auditory": (0.65, 0.51, 0.84, 1.0), # Purple
"Other": (0.,0.,0.,1.) # Black
}
acs0 = np.array(br.id2acronym(r['ids'],
mapping='Beryl'))
acs = [funct[reg] if (reg in funct) else 'Other' for reg in acs0]
cols = np.array([cols0[reg] for reg in acs])
# get average points and color per region
regs = Counter(acs)
else:
acs = np.array(br.id2acronym(r['ids'],
mapping=mapping))
_,pa = get_allen_info()
cols = np.array([pa[reg] for reg in acs])
# get average points and color per region
regs = Counter(acs)
rmv_void_rt = True
if 'end' in r['len']:
del r['len']['end']
r['acs'] = np.array(acs)
r['cols'] = np.array(cols)
if mapping == 'kmeans':
pth__ = Path(one.cache_dir, 'dmn', 'kmeans_group.npy')
np.save(pth__, r, allow_pickle=True)
return r
def get_umap_dist(rerun=False, algo='umap_z',
mapping='Beryl', vers='concat'):
pth_ = Path(one.cache_dir, 'dmn',
f'{algo}_{mapping}_{vers}_smooth.npy')
if (not pth_.is_file() or rerun):
res, regs = smooth_dist(algo=algo, mapping=mapping, vers=vers)
d = {'res': res, 'regs' : regs}
np.save(pth_, d, allow_pickle=True)
else:
d = np.load(pth_, allow_pickle=True).flat[0]
return d
def get_pw_dist(rerun=False, mapping='Beryl', vers='concat',
nclus=7, norm_=False, zscore_=True, nmin=20):
'''
get distance for all region pairs by computing
the Euclidean distance of the feature vectors
for all pairs of neurons in the two regions and then
average that score
'''
pth_ = Path(one.cache_dir, 'dmn',
f'{mapping}_{vers}_zscore_{zscore_}_pw.npy')
if (not pth_.is_file() or rerun):
r = np.load(Path(pth_dmn, f'{vers}_norm{norm_}.npy'),
allow_pickle=True).flat[0]
vecs = 'concat_z' if zscore_ else 'concat'
if mapping == 'kmeans':
# use kmeans to cluster high-dim points
nclus = nclus
kmeans = KMeans(n_clusters=nclus, random_state=0)
kmeans.fit(r[vecs])
acs = kmeans.labels_
print('kmeans done')
else:
acs = np.array(br.id2acronym(r['ids'],
mapping=mapping))
assert len(r[vecs]) == len(acs), 'mismatch, data != acs'
regs0 = Counter(acs)
regs = [x for x in regs0 if regs0[x] > nmin]
res = np.zeros((len(regs),len(regs)))
print(len(regs), 'regions')
k = 0
for i in range(len(regs)):
for j in range(i, len(regs)):
# group of cells a and b
g_a = r[vecs][acs == regs[i]]
g_b = r[vecs][acs == regs[j]]
# compute pairwise distance
M = cdist(g_a, g_b)
rows, cols = M.shape
# remove duplicate counts
mask = np.ones_like(M, dtype=bool)
min_dim = min(rows, cols)
mask[:min_dim, :min_dim] = np.triu(
np.ones((min_dim, min_dim), dtype=bool), k=1)
# average across all pairwise scores
res[i,j] = np.mean(M[mask])
res[j,i] = res[i,j]
if np.isnan(res[i,j]):
print(regs[i], regs[j], len(g_a), len(g_b))
return
#res[i,j] = np.mean(M)
k += 1
print(k, 'of', 0.5*(len(regs)**2), 'done')
d = {'res': res, 'regs' : regs}
np.save(pth_, d, allow_pickle=True)
else:
d = np.load(pth_, allow_pickle=True).flat[0]
return d
def NN(x, y, decoder='LDA', CC=1.0, confusion=False,
return_weights=False, shuf=False, verb=True):
'''
Decode region label y from activity x with parallelized cross-validation.
'''
nclasses = len(Counter(y))
startTime = datetime.now()
if shuf:
np.random.shuffle(y)
if len(x.shape) == 1:
x = x.reshape(-1, 1)
acs = []
# predicted labels for train/test
yp_train = []
yp_test = []
# true labels for train/test
yt_train = []
yt_test = []
folds = 5
kf = StratifiedKFold(n_splits=folds, shuffle=True)
if verb:
print('input dimension:', np.shape(x))
print(f'# classes = {nclasses}')
print('x.shape:', x.shape, 'y.shape:', y.shape)
print(f'{folds}-fold cross validation')
if shuf:
print('labels are SHUFFLED')
def process_fold(train_index, test_index):
"""
Process a single fold of cross-validation.
"""
sc = StandardScaler()
train_X = sc.fit_transform(x[train_index])
test_X = sc.fit_transform(x[test_index])
train_X = x[train_index]
test_X = x[test_index]
train_y = y[train_index]
test_y = y[test_index]
if decoder == 'LR':
clf = LogisticRegression(C=CC, random_state=0, n_jobs=-1,
max_iter=1000)