-
Notifications
You must be signed in to change notification settings - Fork 1
/
granger.py
2156 lines (1583 loc) · 69.7 KB
/
granger.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
#import os
#os.environ["SPECTRAL_CONNECTIVITY_ENABLE_GPU"] = "true"
import numpy as np
from collections import Counter
from pathlib import Path
from spectral_connectivity import Multitaper, Connectivity
import time
import timeit
from itertools import combinations
from scipy.stats import norm
import pandas as pd
import umap, os
from copy import copy
#from sklearn.manifold import MDS
from scipy.stats import pearsonr, spearmanr, norm, chi2, zscore
from statsmodels.stats.multitest import multipletests
import networkx as nx
from scipy.sparse.csgraph import shortest_path, csgraph_from_dense
from scipy.sparse import csr_matrix
from brainwidemap import (load_good_units, bwm_query,
download_aggregate_tables, load_trials_and_mask)
from iblutil.numerical import bincount2D
from one.api import ONE
from iblatlas.regions import BrainRegions
from iblatlas.atlas import AllenAtlas
import iblatlas
import sys
sys.path.append('Dropbox/scripts/IBL/')
import logging
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import gc as garbage
import matplotlib
#matplotlib.use('QtAgg')
#matplotlib.use('tkagg')
sns.reset_defaults()
plt.ion()
one = ONE()
#base_url='https://openalyx.internationalbrainlab.org',
# password='international', silent=True
bad_eids = ['4e560423-5caf-4cda-8511-d1ab4cd2bf7d',
'3a3ea015-b5f4-4e8b-b189-9364d1fc7435',
'd85c454e-8737-4cba-b6ad-b2339429d99b',
'de905562-31c6-4c31-9ece-3ee87b97eab4',
'2d9bfc10-59fb-424a-b699-7c42f86c7871',
'7cc74598-9c1b-436b-84fa-0bf89f31adf6',
'642c97ea-fe89-4ec9-8629-5e492ea4019d',
'a2ec6341-c55f-48a0-a23b-0ef2f5b1d71e', # clear saturation
'195443eb-08e9-4a18-a7e1-d105b2ce1429',
'549caacc-3bd7-40f1-913d-e94141816547',
'90c61c38-b9fd-4cc3-9795-29160d2f8e55',
'ebe090af-5922-4fcd-8fc6-17b8ba7bad6d',
'a9138924-4395-4981-83d1-530f6ff7c8fc',
'8c025071-c4f3-426c-9aed-f149e8f75b7b',
'29a6def1-fc5c-4eea-ac48-47e9b053dcb5',
'0cc486c3-8c7b-494d-aa04-b70e2690bcba']
# window names: [alignment times, segment length, gap, side]
wins = {'whole_session': ['no_events', 10, 0, 'plus'],
'feedback_plus1': ['feedback_times',1, 0, 'plus'],
'stim_plus01': ['stimOn_times', 0.1, 0, 'plus'],
'stim_minus06_minus02': ['stimOn_times', 0.4, 0.2, 'minus'],
'move_minus01': ['firstMovement_times', 0.1, 0, 'minus']}
ba = AllenAtlas()
br = BrainRegions()
T_BIN = 0.0125 # 0.005
sigl=0.05 # alpha throughout
#df = bwm_query(one)
#align = {'stim': 'stim on',
# 'choice': 'motion on',
# 'fback': 'feedback'}
# save results here
pth_res = Path(one.cache_dir, 'granger') #, 'res_feedback_times')
pth_res.mkdir(parents=True, exist_ok=True)
def get_allen_info():
r = np.load(Path(one.cache_dir, 'dmn', 'alleninfo.npy'),
allow_pickle=True).flat[0]
return r['dfa'], r['palette']
def p_fisher(p_values):
# combine p-values via Fisher's method
if len(p_values) == 0:
raise ValueError("Input list of p-values is empty.")
if len(p_values) == 1:
return p_values[0]
z_scores = norm.ppf(1 - np.array(p_values) / 2)
X_squared = np.sum(z_scores**2)
p_combined = chi2.sf(X_squared, 2 * len(p_values))
return p_combined
def get_nregs(win='whole_session'):
'''
get a dict with regs per eid
'''
pthh = pth_res / win
p = pthh.glob('**/*')
files = [x for x in p if x.is_file()]
d = {}
for sess in files:
D = np.load(sess, allow_pickle=True).flat[0]
eid = str(sess).split('/')[-1].split('.')[0]
d[eid] = D['regsd']
return d
def get_structural(rerun=False, shortestp=False, fign=4):
'''
load structural connectivity matrix
https://www.nature.com/articles/nature13186
fig3
https://static-content.springer.com
/esm/art%3A10.1038%2Fnature13186/MediaObjects/
41586_2014_BFnature13186_MOESM70_ESM.xlsx
fig4 '/home/mic/41586_2014_BFnature13186_MOESM72_ESM.xlsx'
'''
pth_ = Path(one.cache_dir, 'granger', f'structural{fign}.npy')
if (not pth_.is_file() or rerun):
if fign == 3:
s=pd.read_excel('/home/mic'
'/41586_2014_BFnature13186_MOESM70_ESM.xlsx')
cols = list(s.keys())[1:297]
rows = s['Unnamed: 0'].array
M = np.zeros((len(cols), len(rows)))
for i in range(len(cols)):
M[i] = s[cols[i]].array
M = M.T
cols1 = np.array([reg.strip().replace(",", "") for reg in cols])
rows1 = np.array([reg.strip().replace(",", "") for reg in rows])
# average across injections
regsr = list(Counter(rows1))
M2 = []
for reg in regsr:
M2.append(np.mean(M[rows1 == reg], axis=0))
# # thresholding as in the paper
# M[M > 10**(-0.5)] = 1
# M[M < 10**(-3.5)] = 0
M2 = np.array(M2)
regs_source = regsr
regs_target = cols1
# turn into dict
d = {}
for i in range(len(regs_source)):
for j in range(len(regs_target)):
if M2[i,j] < 0:
continue
d[' --> '.join([regs_source[i],
regs_target[j]])] = M2[i,j]
np.save(pth_, d,
allow_pickle=True)
elif fign == 4:
s=pd.read_excel(
'/home/mic/41586_2014_BFnature13186_MOESM71_ESM.xlsx',
sheet_name='W_ipsi')
cols = list(s.keys())[1:]
rows = s['Unnamed: 0'].array
M = np.zeros((len(cols), len(rows)))
for i in range(len(cols)):
M[i] = s[cols[i]].array
M = M.T
# load p-values
s=pd.read_excel(
'/home/mic/41586_2014_BFnature13186_MOESM71_ESM.xlsx',
sheet_name='PValue_ipsi')
colsp = list(s.keys())[1:]
rowsp = s['Unnamed: 0'].array
P = np.zeros((len(colsp), len(rowsp)))
for i in range(len(colsp)):
P[i] = s[colsp[i]].array
P = P.T
# turn into dict
d = {}
for i in range(len(rows)):
for j in range(len(cols)):
if np.isnan(P[i,j]):
continue
if P[i,j] > 0.05:
continue
# d[' --> '.join([rows[i],
# cols[j]])] = 0
else:
d[' --> '.join([rows[i],
cols[j]])] = M[i,j]
np.save(pth_, d,
allow_pickle=True)
else:
d = np.load(pth_, allow_pickle=True).flat[0]
if shortestp:
# create adjacency matrix, setting absent connections to zero
# Unnamed: 1 is injection volume; discard
regs = Counter(np.array([x.split(' --> ')
for x in list(d.keys())
if 'Unnamed: 1' not in x]).flatten())
regs = list(regs)
A = np.zeros((len(regs), len(regs)))
for i in range(len(regs)):
for j in range(len(regs)):
if f'{regs[i]} --> {regs[j]}' in d:
A[i,j] = d[f'{regs[i]} --> {regs[j]}']
adjacency_matrix = A
# Convert the adjacency matrix to a sparse matrix (CSR format)
sparse_matrix = csr_matrix(adjacency_matrix)
# Find the shortest path lengths using the Floyd-Warshall algorithm
distances, predecessors = shortest_path(
csgraph=sparse_matrix, directed = False,
method='FW', return_predecessors=True,unweighted=False)
d0 = {}
res = distances
for i in range(len(regs)):
for j in range(len(regs)):
if i == j:
continue
d0[f'{regs[i]} --> {regs[j]}'] = res[i,j]
return d0
return d
def get_centroids(rerun=False, dist_=False):
'''
Beryl region centroids xyz
'''
pth_ = Path(one.cache_dir, 'granger', 'beryl_centroid.npy')
if (not pth_.is_file() or rerun):
beryl_vol = ba.regions.mappings['Beryl-lr'][ba.label]
beryl_idx = np.unique(ba.regions.mappings['Beryl-lr'])
d = {}
k = 0
for ridx in beryl_idx:
idx = np.where(beryl_vol == ridx)
ixiyiz = np.c_[idx[1], idx[0], idx[2]]
xyz = ba.bc.i2xyz(ixiyiz)
d[br.index2acronym(ridx,
mapping='Beryl')] = np.mean(xyz, axis=0)
print(br.index2acronym(ridx,mapping='Beryl'),k, 'of',
len(beryl_idx))
k+=1
np.save(pth_, d,
allow_pickle=True)
else:
d = np.load(pth_, allow_pickle=True).flat[0]
if dist_:
print('note this is the inverse of the centroid euc dist')
regs = list(d.keys())
res = np.zeros((len(regs), len(regs)))
for i in range(len(regs)):
for j in range(len(regs)):
res[i,j] = np.sum((d[regs[i]] - d[regs[j]])**2)**0.5
# invert and normalize, so that 1 is maximally similar
# and 0 is maximally distant
max_val = np.max(res)
min_val = np.min(res)
# Perform linear transformation
res = 1 - ((res - min_val) / (max_val - min_val))
D = {'res': res, 'regs': regs}
return D
return d
def get_volume(rerun=False):
'''
Beryl region volumina in mm^3
'''
pth_ = Path(one.cache_dir, 'granger', 'beryl_volumina.npy')
if (not pth_.is_file() or rerun):
ba.compute_regions_volume()
acs = np.unique(br.id2acronym(
ba.regions.id, mapping='Beryl'))
d2 = {}
for ac in acs:
d2[ac] = ba.regions.volume[
ba.regions.acronym2index(
ac, mapping='Beryl')[1]].sum()
np.save(pth_, d2,
allow_pickle=True)
else:
d2 = np.load(pth_, allow_pickle=True).flat[0]
return d2
def make_data(T=300000, vers='oscil', peak_freq_factor0=0.55,
peak_freq_factor1=0.2, phase_lag_factor=0.2):
'''
auto-regressive data creation
x2 dependend on x1, not vice versa
'''
x1 = np.random.normal(0, 1,T+3)
x2 = np.random.normal(0, 1,T+3)
if vers == 'dc':
x1 = x2[30:]
x2 = x2[0:-30]
regsd = {'x2[30:]':1, 'x2[0:-30]':1}
return np.array([x1,x2]), regsd
elif vers == 'oscil':
for t in range(2,T+2):
x2[t] = (peak_freq_factor1*x2[t-1] - 0.8*x2[t-2] +
x2[t+1])
x1[t] = (peak_freq_factor0*x1[t-1] - 0.8*x1[t-2] +
phase_lag_factor * x2[t-1] + x1[t+1])
elif vers == 'loopy':
for t in range(2,T+2):
x2[t] = (peak_freq_factor1 * x2[t - 1] - 0.8 * x2[t - 2]
+ phase_lag_factor * x1[t - 1] + x2[t + 1])
x1[t] = (peak_freq_factor0 * x1[t - 1] - 0.8 * x1[t - 2]
+ phase_lag_factor * x2[t - 1] + x1[t + 1])
regsd = {'dep':1, 'indep':1}
return np.array([x1[2:-1],x2[2:-1]]), regsd
def bin_average_neural(eid, mapping='Beryl', nmin=1):
'''
bin neural activity; bin, then average firing rates per region
from both probes if available
used to get session-wide time series, not cut into trials
nmin:
minumum number of neurons per brain region to consider it
returns:
R2: binned firing rate per region per time bin
times: time stamps for all time bins
redg: dict of neurons per region acronym
'''
pids0, probes = one.eid2pid(eid)
pids = []
for pid in pids0:
if pid in df['pid'].values:
pids.append(pid)
if len(pids) == 1:
spikes, clusters = load_good_units(one, pids[0])
R, times, _ = bincount2D(spikes['times'],
spikes['clusters'], T_BIN)
acs = br.id2acronym(clusters['atlas_id'], mapping=mapping)
regs = Counter(acs)
regs2 = {x: regs[x] for x in regs if
((regs[x] >= nmin) and (x not in ['root','void']))}
R2 = np.array([np.mean(R[acs == reg],axis=0) for reg in regs2])
return R2, times, regs2
else:
sks = []
clus = []
for pid in pids:
spikes, clusters = load_good_units(one, pid)
sks.append(spikes)
clus.append(clusters)
# add max cluster of p0 to p1, then concat, sort
max_cl0 = max(sks[0]['clusters'])
sks[1]['clusters'] = sks[1]['clusters'] + max_cl0 + 1
times_both = np.concatenate([sks[0]['times'],
sks[1]['times']])
clusters_both = np.concatenate([sks[0]['clusters'],
sks[1]['clusters']])
acs_both = np.concatenate([
br.id2acronym(clus[0]['atlas_id'],
mapping=mapping),
br.id2acronym(clus[1]['atlas_id'],
mapping=mapping)])
t_sorted = np.sort(times_both)
c_ordered = clusters_both[np.argsort(times_both)]
R, times, clus = bincount2D(t_sorted, c_ordered, T_BIN)
regs = Counter(acs_both)
regs2 = {x: regs[x] for x in regs if
((regs[x] >= nmin) and (x not in ['root','void']))}
R2 = np.array([np.mean(R[acs_both == reg],axis=0)
for reg in regs2])
return R2, times, regs2
def gc(r, segl=10, shuf=False, shuf_type = 'reg_shuffle'):
'''
chop up times series into segments of length segl [sec]
Independent of trial-structure, then compute metrics
'''
nchans, nobs = r.shape
segment_length = int(segl / T_BIN)
num_segments = nobs // segment_length
# reshape into: n_signals x n_segments x n_time_samples
r_segments = r[:, :num_segments * segment_length
].reshape((nchans, num_segments,
segment_length))
if shuf:
if shuf_type == 'reg_shuffle':
# shuffle region order per trial
indices = np.arange(r_segments.shape[0])
rs = np.zeros(r_segments.shape)
for trial in range(r_segments.shape[1]):
np.random.shuffle(indices)
rs[:,trial,:] = r_segments[indices, trial, :]
r_segments = np.array(rs)
else:
# shuffle segment order
indices = np.arange(r_segments.shape[1])
rs = np.zeros(r_segments.shape)
for chan in range(r_segments.shape[0]):
np.random.shuffle(indices)
rs[chan] = r_segments[chan, indices]
r_segments = np.array(rs)
#print('segments channel-independently shuffled')
# reshape into: n_time_samples x n_segments x n_signals
r_segments_reshaped = r_segments.transpose((2, 1, 0))
m = Multitaper(
r_segments_reshaped,
sampling_frequency=1/T_BIN,
time_halfbandwidth_product=2,
start_time=0)
c = Connectivity(
fourier_coefficients=m.fft(),
frequencies=m.frequencies,
time=m.time)
return c
def fr_performance(eid, nmin=1, nts = 20):
'''
for a given session get fr per region in inter trial interval
(-0.4 t0 -0.1 relative to stim onset)
and return with performance average
return:
ftp: performance per trial (0 incorrect, 1 correct)
frs: firing rate per inter trial interval per region
'''
# combine probes, bin fr per region
r, ts, regd = bin_average_neural(eid, nmin=nmin)
# cut out inter-trial fr
trials, mask = load_trials_and_mask(one, eid)
iti = np.array([trials['stimOn_times'][mask] - 0.4,
trials['stimOn_times'][mask] - 0.1])
ftp = trials['feedbackType'][mask]
ftp.replace(-1, 0, inplace=True)
fp = np.array(ftp)
cis = []
for i in range(2):
indices = np.searchsorted(ts, iti[i])
adjusted_indices = np.clip(indices - 1, 0, len(ts) - 1)
closest_indices = np.where(np.abs(iti[i] - ts[adjusted_indices]) <
np.abs(iti[i] - ts[adjusted_indices + 1]),
adjusted_indices, adjusted_indices + 1)
cis.append(closest_indices)
cis = np.array(cis).T
frs = []
for tr in cis:
frs.append(r[:,tr[0] : tr[1] +1])
fr = np.mean(np.array(frs),axis=-1).T
fp_m = []
fr_m = []
for chunk in range(len(fp)//nts):
fp_m.append(np.mean(fp[chunk * nts: (chunk+1) * nts]))
fr_m.append(np.mean(fr[:, chunk * nts: (chunk+1) * nts], axis=-1))
fp_m = np.array(fp_m)
fr_m = np.array(fr_m).T
corrd = {}
for i in range(len(fr_m)):
reg = list(regd)[i]
corrd[reg] = [list(pearsonr(fr_m[i], fp_m)),
list(spearmanr(fr_m[i], fp_m))]
D = {}
D['fp_m'] = fp_m
D['fr_m'] = fr_m
D['regd'] = regd
D['corrd'] = corrd
return D
def cut_segments(r, ts, te, segment_length=100, side='plus', gap_length=0):
'''
r:
binned activity time series
ts:
time stamps per bin
te:
event times where segments start
segment_length:
seg length in bins
side: ['plus', 'minus']
if segments start or end at alignement time
gap_length:
gap between segment and alignement event in bins
Returns:
A 3D array of segments with shape (n_regions, n_events, segment_length)
'''
r = np.array(r)
ts = np.array(ts)
te = np.array(te)
# Ensure r is 2D, even if it's a single region
if r.ndim == 1:
r = r[np.newaxis, :]
# Find indices of the nearest time stamps to event times
event_indices = np.searchsorted(ts, te)
# Adjust start indices based on 'side' and gap_length
if side == 'plus':
# Start segment after the event time plus the gap
start_indices = event_indices + gap_length
elif side == 'minus':
# End segment at event time minus the gap, so start earlier
start_indices = event_indices - segment_length - gap_length
else:
raise ValueError("Invalid value for 'side'. Choose 'plus' or 'minus'.")
# Create an array of indices for each segment
indices = start_indices[:, np.newaxis] + np.arange(segment_length)
# Clip indices to ensure they're within bounds
indices = np.clip(indices, 0, r.shape[1] - 1)
# Extract segments
segments = r[:, indices]
# Rearrange dimensions to (n_regions, n_events, segment_length)
segments = np.transpose(segments, (0, 1, 2))
# If original input was 1D, remove the singleton dimension
if r.shape[0] == 1:
segments = segments.squeeze(axis=1)
return segments
'''
####################
bulk processing
####################
'''
def get_all_granger(eids='all', nshufs = 100, nmin=10, wins=wins):
'''
get spectral directed granger for all bwm sessions
segl:
segment length in seconds (unless wins are given)
wins:
Window of interest and seg length, if None, the whole session
is binned and cut into segments; else segments
of length segl are cut after win times
eid, probe = one.pid2eid(pid)
'''
if isinstance(eids, str):
df = bwm_query(one)
eids = np.unique(df[['eid']].values)
Fs = []
k = 0
print(f'Processing {len(eids)} sessions')
time0 = time.perf_counter()
for eid in eids:
print('eid:', eid)
# remove lick artefact eid and late fire only
if eid in bad_eids:
print('exclude', eid)
continue
try:
time00 = time.perf_counter()
r, ts, regsd = bin_average_neural(eid, nmin=nmin)
if not bool(regsd):
print(f'no data for {eid}')
continue
nchans, nobs = r.shape
for win in wins:
if win == 'whole_session':
print('chop up whole session into segments')
print(win, 'align|segl|gap|side', wins[win])
segl = wins[win][1] # in sec
segment_length = int(segl / T_BIN) # in bins
# chop up whole session into segments
num_segments = nobs // segment_length
# reshape into: n_signals x n_segments x n_time_samples
r_segments = r[:, :num_segments * segment_length
].reshape((nchans, num_segments,
segment_length))
# reshape to n_time_samples x n_segments x n_signals
r_segments_reshaped = r_segments.transpose((2, 1, 0))
else:
print(win, 'align|segl|gap|side', wins[win])
segl = wins[win][1] # in sec
segment_length = int(segl / T_BIN) # in bins
gap = wins[win][2] # in sec
gap_length = int(gap / T_BIN) # in bins
side = wins[win][3]
# only pick segments starting at "win" times
# 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'])
te = trials[mask][wins[win][0]].values
# n_regions x n_segments x n_time_samples
r_segments = cut_segments(r, ts, te, gap_length=gap_length,
side=side, segment_length=segment_length)
# reshape to n_time_samples x n_segments x n_signals
r_segments_reshaped = r_segments.transpose((2, 1, 0))
m = Multitaper(
r_segments_reshaped,
sampling_frequency=1/T_BIN,
time_halfbandwidth_product=2,
start_time=0)
c = Connectivity(
fourier_coefficients=m.fft(),
frequencies=m.frequencies,
time=m.time)
psg = c.pairwise_spectral_granger_prediction()[0]
coh = c.coherence_magnitude()[0]
score_g = np.mean(psg,axis=0)
score_c = np.mean(coh,axis=0)
# get scores after shuffling segments
shuf_g = []
shuf_c = []
# shuffle pairs of regions separately
pairs = np.array(list(combinations(range(nchans),2)))
print('data binned', regsd, f'{len(pairs)} pairs')
for i in range(nshufs):
if i%10 == 0:
print('shuf', i, f'({nshufs})')
mg = np.zeros([nchans,nchans])
mc = np.zeros([nchans,nchans])
for pair in pairs:
rs = np.zeros([2, r_segments.shape[1],
r_segments.shape[2]])
for trial in range(r_segments.shape[1]):
np.random.shuffle(pair)
rs[:,trial,:] = r_segments[pair, trial, :]
r_segments0 = np.array(rs)
#into n_time_samples x n_segments x n_signals
r_segments_reshaped0 = r_segments0.transpose((2, 1, 0))
m = Multitaper(
r_segments_reshaped0,
sampling_frequency=1/T_BIN,
time_halfbandwidth_product=2,
start_time=0)
c0 = Connectivity(
fourier_coefficients=m.fft(),
frequencies=m.frequencies,
time=m.time)
mmg = np.mean(
c0.pairwise_spectral_granger_prediction()[0],
axis=0)
mmc = np.mean(
c0.coherence_magnitude()[0],
axis=0)
mg[pair[0], pair[1]] = mmg[0,1]
mg[pair[1], pair[0]] = mmg[1,0]
mc[pair[0], pair[1]] = mmc[0,1]
mc[pair[1], pair[0]] = mmc[1,0]
shuf_g.append(mg)
shuf_c.append(mc)
shuf_g.append(score_g)
shuf_c.append(score_c)
shuf_g = np.array(shuf_g)
shuf_c = np.array(shuf_c)
p_g = np.mean(shuf_g >= score_g, axis=0)
p_c = np.mean(shuf_c >= score_c, axis=0)
D = {'regsd': regsd,
'freqs': c.frequencies,
'p_granger': p_g,
'p_coherence': p_c,
'coherence': score_c,
'granger': score_g,
'coherence_pks': c.frequencies[np.argmax(coh,axis=0)],
'granger_pks': c.frequencies[np.argmax(psg,axis=0)]}
pthh = Path(pth_res, win)
pthh.mkdir(parents=True, exist_ok=True)
np.save(pthh / f'{eid}.npy', D, allow_pickle=True)
garbage.collect()
print(k + 1, 'of', len(eids), 'ok')
time11 = time.perf_counter()
print('runtime [sec]: ', time11 - time00)
except BaseException:
Fs.append(eid)
garbage.collect()
print(k + 1, 'of', len(eids), 'fail', eid)
k += 1
time1 = time.perf_counter()
print(time1 - time0, f'sec for {len(eids)} sessions')
print(len(Fs), 'failures')
return Fs
def get_res(nmin=10, metric='granger', combine_=True, c_mc =False,
rerun=False, sig_only=False, sessmin=2, win='whole_session'):
'''
Group results
nmin: minimum number of neurons per region to be included
sessmin: min number of sessions with region combi
metric in ['coherence', 'granger']
c_ms: correction for multiple comparisons (fdr_bh)
'''
pth_ = Path(pth_res, f'{metric}_{win}.npy')
if (not pth_.is_file() or rerun):
pthh = pth_res / win
p = pthh.glob('**/*')
files = [x for x in p if x.is_file()]
d = {}
ps = []
for sess in files:
# remove lick artefact eid and late fire only
eid = str(sess).split('/')[-1].split('.')[0]
if eid in bad_eids:
print('exclude', sess)
continue
D = np.load(sess, allow_pickle=True).flat[0]
m = D[metric]
regs = list(D['regsd'])
p_c = D[f'p_{metric}']
if not isinstance(D['regsd'], dict):
nd.append(sess)
continue
for i in range(len(regs)):
for j in range(len(regs)):
if i == j:
continue
if ((D['regsd'][regs[i]] <= nmin) or
(D['regsd'][regs[j]] <= nmin)):
continue
if f'{regs[i]} --> {regs[j]}' in d:
d[f'{regs[i]} --> {regs[j]}'].append(
[m[j, i], p_c[i,j],
D['regsd'][regs[i]], D['regsd'][regs[j]], eid])
else:
d[f'{regs[i]} --> {regs[j]}'] = []
d[f'{regs[i]} --> {regs[j]}'].append(
[m[j, i], p_c[i,j],
D['regsd'][regs[i]], D['regsd'][regs[j]], eid])
ps.append(p_c[i,j])
if c_mc:
_, corrected_ps, _, _ = multipletests(ps, sigl,
method='fdr_bh')
else:
corrected_ps = np.array(ps)
kp = 0
d2 = {}
for pair in d:
scores = []
for score in d[pair]:
scores.append([score[0],corrected_ps[kp],
score[2], score[3], score[4]])
kp+=1
if scores == []:
continue
else:
d2[pair] = scores
print(f'{metric} measurements in total: {len(ps)} ')
print(f'Uncorrected significant: {np.sum(np.array(ps)<sigl)}')
print(f'Corrected significant: {np.sum(corrected_ps<sigl)}')
np.save(Path(one.cache_dir, 'granger', f'{metric}_{win}.npy'),
d2, allow_pickle=True)
d = d2
else:
d = np.load(pth_, allow_pickle=True).flat[0]
if combine_:
# take mean score across measurements
dd = {k: [np.mean(np.array(d[k])[:,0], dtype=float),
p_fisher(np.array(np.array(d[k])[:,1], dtype=float))]
for k in d if (len(d[k]) >= sessmin)}
if sig_only:
ddd = {}
for pair in dd:
if dd[pair][1] < sigl:
ddd[pair] = dd[pair][0]
dd = ddd
else:
if sig_only:
dd = {}
for pair in d:
l = [x[0] for x in d[pair] if x[1] < sigl]
if l == []:
continue
else:
dd[pair] = l
else:
dd = d
return dd
def get_meta_info(rerun=False, win='whole_session'):
'''
get neuron number and peak freq_s per region???
'''
pth_ = Path(pth_res, f'all_regs.npy')
if (not pth_.is_file() or rerun):
pthh = pth_res / win
p = pthh.glob('**/*')
files = [x for x in p if x.is_file()]