-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlibrary.py
More file actions
2246 lines (2149 loc) · 122 KB
/
library.py
File metadata and controls
2246 lines (2149 loc) · 122 KB
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 numpy as np
import pandas as pd
import os
import itertools
from scipy.stats import shapiro
from scipy.stats import ttest_ind
from scipy.stats import ranksums
from tqdm import tqdm
import pickle
import time
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from matplotlib.patches import Rectangle #, PathPatch
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import colors
import matplotlib.gridspec as gridspec
from statsmodels.stats.weightstats import ztest as ztest
import networkx as nx
import networkx.algorithms.isomorphism as iso
import community
from netgraph import Graph
import seaborn as sns
from scipy import signal
from scipy import stats
from collections import defaultdict
from sklearn.metrics.cluster import adjusted_rand_score
from upsetplot import from_contents, plot, UpSet
from bisect import bisect
np.seterr(divide='ignore', invalid='ignore')
plt.rcParams['font.family'] = 'serif'
plt.rcParams["font.serif"] = ["Times New Roman"]
session_ids = ['719161530','750749662','754312389','755434585','756029989','791319847','797828357']
stimulus_names = ['spontaneous', 'flash_dark', 'flash_light',
'drifting_gratings', 'static_gratings',
'natural_scenes', 'natural_movie_one', 'natural_movie_three']
visual_regions = ['VISam', 'VISpm', 'VISal', 'VISrl', 'VISl', 'VISp']
# region_colors = ['tab:green', 'lightcoral', 'steelblue', 'tab:orange', 'tab:purple', 'grey']
region_labels = ['AM', 'PM', 'AL', 'RL', 'LM', 'V1']
region_colors = ['#d9e9b5', '#c0d8e9', '#fed3a1', '#c3c3c3', '#fad3e4', '#cec5f2']
combined_stimuli = [['spontaneous'], ['flash_dark', 'flash_light'], ['drifting_gratings'], ['static_gratings'], ['natural_scenes'], ['natural_movie_one', 'natural_movie_three']]
combined_stimulus_names = ['Resting\nstate', 'Flashes', 'Drifting\ngratings', 'Static\ngratings', 'Natural\nscenes', 'Natural\nmovies']
combined_stimulus_colors = ['#8dd3c7', '#fee391', '#bebada', '#bebada', '#fb8072', '#fb8072']
stimulus2marker = {'Resting\nstate':'s', 'Flashes':'*', 'Drifting\ngratings':'X', 'Static\ngratings':'P', 'Natural\nscenes':r'$\clubsuit$', 'Natural\nmovies':'>'}
marker_size_dict = {'v':10, '*':22, 'P':13, 'X':13, 'o':11, 's':9.5, 'D':9, 'p':12, '>':10, r'$\clubsuit$':20}
scatter_size_dict = {'v':10, '*':17, 'P':13, 'X':13, 'o':11, 's':10, 'D':9, 'p':13, '>':12, r'$\clubsuit$':16}
error_size_dict = {'v':10, '*':24, 'P':16, 'X':16, 'o':11, 's':9., 'D':9, 'p':12, '>':13, r'$\clubsuit$':22}
TRIAD_NAMES = ('003', '012', '102', '021D', '021U', '021C', '111D', '111U', '030T', '030C', '201', '120D', '120U', '120C', '210', '300')
model_names = [u'Erdős-Rényi model', 'Degree-preserving model', 'Pair-preserving model', 'Signed-pair-preserving model']
def combine_stimulus(stimulus):
t_ind = [i for i in range(len(combined_stimuli)) if stimulus in combined_stimuli[i]][0]
return t_ind, combined_stimulus_names[t_ind]
def load_npz_3d(filename):
"""
load npz files with sparse matrix and dimension
output dense matrix with the correct dim
"""
npzfile = np.load(filename, allow_pickle=True)
sparse_matrix = npzfile['arr_0'][0]
ndim=npzfile['arr_0'][1]
new_matrix_2d = np.array(sparse_matrix.todense())
new_matrix = new_matrix_2d.reshape(ndim)
return new_matrix
def load_sparse_npz(filename):
with open(filename, 'rb') as infile:
[sparse_matrix, shape] = pickle.load(infile)
matrix_2d = sparse_matrix.toarray()
return matrix_2d.reshape(shape)
############# load area_dicts
def load_area_dicts(session_ids):
a_file = open('./files/area_dict.pkl', 'rb')
area_dict = pickle.load(a_file)
int_2_str = dict((session_id, str(session_id)) for session_id in session_ids)
area_dict = dict((int_2_str[key], value) for (key, value) in area_dict.items())
a_file.close()
a_file = open('./files/active_area_dict.pkl', 'rb')
active_area_dict = pickle.load(a_file)
a_file.close()
return area_dict, active_area_dict
# build a graph from an adjacency matrix
def mat2graph(adj_mat, confidence_level, active_area, cc=False, weight=False):
if not weight:
adj_mat[adj_mat.nonzero()] = 1
G = nx.from_numpy_array(adj_mat, create_using=nx.DiGraph) # same as from_numpy_matrix
node_idx = sorted(active_area.keys())
mapping = {i:node_idx[i] for i in range(len(node_idx))}
G = nx.relabel_nodes(G, mapping)
assert set(G.nodes())==set(node_idx), '{}, {}'.format(len(G.nodes()), len(node_idx))
nodes = sorted(G.nodes())
cl = {(nodes[i],nodes[j]):confidence_level[i,j] for i,j in zip(*np.where(~np.isnan(confidence_level)))}
nx.set_edge_attributes(G, cl, 'confidence')
if cc: # extract the largest (strongly) connected components
if np.allclose(adj_mat, adj_mat.T, rtol=1e-05, atol=1e-08): # if the matrix is symmetric, which means undirected graph
largest_cc = max(nx.connected_components(G), key=len)
else:
largest_cc = max(nx.strongly_connected_components(G), key=len)
G = nx.subgraph(G, largest_cc)
return G
# load all graphs into a dictionary
def load_graphs(directory, active_area_dict, weight):
G_dict, offset_dict, duration_dict = {}, {}, {}
files = os.listdir(directory)
files.sort(key=lambda x:int(x[:9]))
for file in files:
if ('_offset' not in file) and ('_duration' not in file) and ('confidence' not in file):
print(file)
adj_mat = load_npz_3d(os.path.join(directory, file))
confidence_level = load_npz_3d(os.path.join(directory, file.replace('.npz', '_confidence.npz')))
session = file.split('_')[0]
stimulus = file.replace('.npz', '').replace(session + '_', '')
if not session in G_dict:
G_dict[session], offset_dict[session], duration_dict[session] = {}, {}, {}
G_dict[session][stimulus] = mat2graph(adj_mat=np.nan_to_num(adj_mat), confidence_level=confidence_level, active_area=active_area_dict[session], cc=False, weight=weight)
offset_dict[session][stimulus] = load_npz_3d(os.path.join(directory, file.replace('.npz', '_offset.npz')))
duration_dict[session][stimulus] = load_npz_3d(os.path.join(directory, file.replace('.npz', '_duration.npz')))
return G_dict, offset_dict, duration_dict
# get sorted sessions and stimuli
def get_session_stimulus(G_dict):
sessions = list(G_dict.keys())
stimuli = []
for session in sessions:
stimuli += list(G_dict[session].keys())
stimuli = list(set(stimuli))
if 'drifting_gratings_contrast' in stimuli:
stimuli.remove('drifting_gratings_contrast')
# sort stimulus
stimulus_rank = ['spontaneous', 'flash_dark', 'flash_light',
'drifting_gratings', 'static_gratings',
'natural_scenes', 'natural_movie_one', 'natural_movie_three']
if set(stimuli).issubset(set(stimulus_rank)):
stimulus_rank_dict = {i:stimulus_rank.index(i) for i in stimuli}
stimulus_rank_dict = dict(sorted(stimulus_rank_dict.items(), key=lambda item: item[1]))
stimuli = list(stimulus_rank_dict.keys())
else:
stimuli = sorted(stimuli)
return sessions, stimuli
def add_sign(G_dict):
sessions, stimuli = get_session_stimulus(G_dict)
S_dict = {}
for session in sessions:
S_dict[session] = {}
for stimulus in stimuli:
G = G_dict[session][stimulus]
weights = nx.get_edge_attributes(G,'weight')
A = nx.to_numpy_array(G, nodelist=sorted(G.nodes()))
A[A.nonzero()] = 1
S = nx.from_numpy_array(A, create_using=nx.DiGraph)
node_idx = sorted(G.nodes())
mapping = {i:node_idx[i] for i in range(len(node_idx))}
S = nx.relabel_nodes(S, mapping)
for (n1, n2, d) in S.edges(data=True):
d.clear()
signs = {}
for e, w in weights.items():
signs[e] = np.sign(w)
nx.set_edge_attributes(S, signs, 'sign')
S_dict[session][stimulus] = S
return S_dict
def add_offset(G_dict, offset_dict):
sessions, stimuli = get_session_stimulus(G_dict)
S_dict = {}
for session in sessions:
S_dict[session] = {}
for stimulus in stimuli:
offset_mat = offset_dict[session][stimulus]
G = G_dict[session][stimulus]
nodes = sorted(list(G.nodes()))
offset = {}
for edge in G.edges():
offset[edge] = offset_mat[nodes.index(edge[0]), nodes.index(edge[1])]
S = G.copy()
nx.set_edge_attributes(S, offset, 'offset')
S_dict[session][stimulus] = S
return S_dict
def add_duration(G_dict, duration_dict):
sessions, stimuli = get_session_stimulus(G_dict)
S_dict = {}
for session in sessions:
S_dict[session] = {}
for stimulus in stimuli:
duration_mat = duration_dict[session][stimulus]
G = G_dict[session][stimulus]
nodes = sorted(list(G.nodes()))
duration = {}
for edge in G.edges():
duration[edge] = duration_mat[nodes.index(edge[0]), nodes.index(edge[1])]
S = G.copy()
nx.set_edge_attributes(S, duration, 'duration')
S_dict[session][stimulus] = S
return S_dict
def add_delay(G_dict):
sessions, stimuli = get_session_stimulus(G_dict)
S_dict = {}
for session in sessions:
S_dict[session] = {}
for stimulus in stimuli:
G = G_dict[session][stimulus]
delay = {}
for edge in G.edges():
delay[edge] = G.get_edge_data(*edge)['offset'] + G.get_edge_data(*edge)['duration']
S = G.copy()
nx.set_edge_attributes(S, delay, 'delay')
S_dict[session][stimulus] = S
return S_dict
################### Figure 1B ###################
def get_raster_data(area_dict, session_index, s_lengths, blank_width=50):
directory = './files/spike_trains/'
total_sequence = np.zeros((len(area_dict[session_ids[session_index]]), 0))
stimulus2plot = [stimulus_names[i] for i in [0, 1, 3, 4, 5, 6]]
for s_ind, stimulus in enumerate(stimulus2plot):
print(stimulus)
sequences = load_npz_3d(os.path.join(directory, str(session_ids[session_index]) + '_' + stimulus + '.npz'))
assert sequences.shape[0] == len(area_dict[str(session_ids[session_index])])
total_sequence = np.concatenate((total_sequence, sequences[:, 0, :s_lengths[s_ind]]), 1)
if s_ind < len(stimulus2plot) - 1:
total_sequence = np.concatenate((total_sequence, np.zeros((total_sequence.shape[0], blank_width))), 1)
node_area = area_dict[str(session_ids[session_index])]
nodes, areas = list(node_area.keys()), list(node_area.values())
areas_num = [(np.array(areas)==a).sum() for a in visual_regions]
areas_start_pos = list(np.insert(np.cumsum(areas_num)[:-1], 0, 0))
sequence_by_area = {area:[nodes.index(ind) for ind, a in node_area.items() if a == area] for area in visual_regions}
return total_sequence, areas_num, areas_start_pos, sequence_by_area
def plot_raster(total_sequence, areas_num, areas_start_pos, sequence_by_area, s_lengths, blank_width):
sorted_sample_seq = np.vstack([total_sequence[sequence_by_area[area], :] for area in visual_regions])
spike_pos = [np.nonzero(t)[0] / 1000 for t in sorted_sample_seq[:, :]] # divided by 1000 cuz bin size is 1 ms
colors1 = [region_colors[i] for i in sum([[visual_regions.index(a)] * areas_num[visual_regions.index(a)] for a in visual_regions], [])]
text_pos = [s + (areas_num[areas_start_pos.index(s)] - 1) / 2 for s in areas_start_pos]
lineoffsets2 = 1
linelengths2 = 2.
# create a horizontal plot
fig = plt.figure(figsize=(16.5, 6))
plt.eventplot(spike_pos, colors='k', lineoffsets=lineoffsets2,
linelengths=linelengths2) # colors=colors1
for ind, t_pos in enumerate(text_pos):
plt.text(-.1, t_pos, region_labels[ind], size=20, color='k', va='center', ha='center') #, color=region_colors[ind]
plt.axis('off')
plt.gca().invert_yaxis()
s_loc1 = np.concatenate(([0],(np.cumsum(s_lengths)+np.arange(1,len(s_lengths)+1)*blank_width)))[:-1]
s_loc2 = s_loc1 + np.array(s_lengths)
stext_pos = (s_loc1 + s_loc2) / 2000
loc_max = max(s_loc1.max(), s_loc2.max())
s_loc_frac1, s_loc_frac2 = [loc/loc_max for loc in s_loc1], [loc/loc_max for loc in s_loc2]
for ind, t_pos in enumerate(stext_pos):
plt.text(t_pos, -60, combined_stimulus_names[ind], size=20, color='k', va='center',ha='center')
#### add horizontal band
band_pos = areas_start_pos + [areas_start_pos[-1]+areas_num[-1]]
xgmin, xgmax=.045, .955
alpha_list = [.4, .4, .4, .6, .5, .5]
for loc1, loc2 in zip(band_pos[:-1], band_pos[1:]):
for scale1, scale2 in zip(s_loc_frac1, s_loc_frac2):
xmin, xmax = scale1 * (xgmax-xgmin) + xgmin, scale2 * (xgmax-xgmin) + xgmin
plt.gca().axhspan(loc1, loc2, xmin=xmin, xmax=xmax, facecolor=region_colors[areas_start_pos.index(loc1)], alpha=alpha_list[areas_start_pos.index(loc1)])
plt.savefig('./figures/figure1B.pdf', transparent=True)
################### Figure 1D ###################
def find_peak_zscore(corr,duration=6,maxlag=12):
filter = np.array([[[1]]]).repeat(duration+1, axis=2) # sum instead of mean
corr_integral = signal.convolve(corr, filter, mode='valid', method='fft')
mu, sigma = np.nanmean(corr_integral, -1), np.nanstd(corr_integral, -1)
abs_deviation = np.abs(corr_integral[:, :, :maxlag-duration+1] - mu[:,:,None])
extreme_offset = np.argmax(abs_deviation, -1)
ccg_mat_extreme = np.choose(extreme_offset, np.moveaxis(corr_integral[:, :, :maxlag-duration+1], -1, 0))
zscore = (ccg_mat_extreme - mu) / sigma
return zscore, ccg_mat_extreme
def ccg2zscore(ccg_corrected, max_duration=6, maxlag=12):
all_zscore, all_ccg = np.zeros(ccg_corrected.shape[:2]), np.zeros(ccg_corrected.shape[:2])
for duration in np.arange(max_duration, -1, -1): # reverse order, so that sharp peaks can override highland
print('duration {}'.format(duration))
zscore, ccg_mat_extreme = find_peak_zscore(ccg_corrected, duration, maxlag)
indx = np.abs(zscore) > np.abs(all_zscore)
# highland_ccg, confidence_level, offset, indx = find_highland(corr, min_spike, duration, maxlag, n)
if np.sum(indx):
all_zscore[indx] = zscore[indx]
all_ccg[indx] = ccg_mat_extreme[indx]
return all_zscore, all_ccg
def get_connectivity_data(G_dict, session_ind, stimulus_ind):
sessions, stimuli = get_session_stimulus(G_dict)
session, stimulus = sessions[session_ind], stimuli[stimulus_ind]
directory = './data/ecephys_cache_dir/sessions/adj_mat_ccg_corrected/'
file = session + '_' + stimulus + '.npz'
ccg = load_sparse_npz(os.path.join(directory, file))
ccg_jittered = load_sparse_npz(os.path.join(directory, file.replace('.npz', '_bl.npz')))
ccg_corrected = ccg - ccg_jittered
ccg_zscore, ccg_value = ccg2zscore(ccg_corrected, max_duration=11, maxlag=12)
return ccg_zscore, ccg_value
def plot_connectivity_matrix_annotation(G_dict, active_area_dict, session_ind, stimulus_ind, ccg_zscore, ccg_value, weight=None, ratio=15):
sessions, stimuli = get_session_stimulus(G_dict)
session, stimulus = sessions[session_ind], stimuli[stimulus_ind]
G = G_dict[session][stimulus]
nsession = 2
nstimulus = 2
active_area = active_area_dict[session]
ordered_nodes = [] # order nodes based on hierarchical order
region_size = np.zeros(len(visual_regions))
for r_ind, region in enumerate(visual_regions):
for node in active_area:
if active_area[node] == region:
ordered_nodes.append(node)
region_size[r_ind] += 1
A = nx.to_numpy_array(G, nodelist=ordered_nodes, weight='weight').T # source on the bottom, target on the left
areas = [active_area[node] for node in ordered_nodes]
areas_num = [(np.array(areas)==a).sum() for a in visual_regions]
rareas_num = [(np.array(areas)==a).sum() for a in visual_regions[::-1]]
area_inds = [0] + np.cumsum(areas_num).tolist()
r_area_inds = ([0]+np.cumsum(rareas_num)[:-1].tolist())[::-1] # low to high from left to right
vareas_start_pos = list(np.insert(np.cumsum(areas_num)[:-1], 0, 0))
vtext_pos = [s + (areas_num[vareas_start_pos.index(s)] - 1) / 2 for s in vareas_start_pos]
hareas_start_pos = list(np.insert(np.cumsum(rareas_num)[:-1], 0, 0))
htext_pos = [s + (rareas_num[hareas_start_pos.index(s)] - 1) / 2 for s in hareas_start_pos]
region_bar = []
for r_ind in range(len(visual_regions)):
region_bar += [r_ind] * int(region_size[r_ind])
cmap = colors.ListedColormap(region_colors)
bounds = [-.5,.5,1.5,2.5,3.5,4.5,5.5]
norm = colors.BoundaryNorm(bounds, cmap.N)
alpha_list = [.6, .6, .6, .6, .6, .6]
colors_transparency = colors.ListedColormap([transparent_rgb(colors.to_rgb(color), [1,1,1], alpha=alpha_list[c_ind]) for c_ind, color in enumerate(region_colors)])
fig = plt.figure(figsize=(10, 10))
gs = gridspec.GridSpec(nsession, nstimulus, width_ratios=[1, ratio-1], height_ratios=[1, ratio-1],
wspace=0.0, hspace=0.0, top=1, bottom=0.001, left=0., right=.999)
ax= plt.subplot(gs[0,1])
ax.set_xticklabels([])
ax.set_yticklabels([])
# reverse order, low to high from left to right
ax.imshow(np.repeat(np.array(region_bar[::-1])[None,:],len(region_bar)//ratio, 0), cmap=colors_transparency, norm=norm)
ax.set_xticks([])
ax.set_yticks([])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
for ind, t_pos in enumerate(htext_pos):
ax.text(t_pos, 6.7, region_labels[len(region_labels)-ind-1], va='center', ha='center', size=30, color='k')
ax= plt.subplot(gs[1,0])
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.imshow(np.repeat(np.array(region_bar)[:,None],len(region_bar)//ratio, 1), cmap=colors_transparency, norm=norm)
ax.set_xticks([])
ax.set_yticks([])
for ind, t_pos in enumerate(vtext_pos):
ax.text(6.7, t_pos, region_labels[ind], va='center', ha='center', size=30, color='k', rotation=90)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax= plt.subplot(gs[1,1])
ax.set_xticklabels([])
ax.set_yticklabels([])
nodes = sorted(active_area.keys())
node2idx = {node:nodes.index(node) for node in nodes}
if weight is None:
mat = np.flip(A, 1) # from left to right
vmin = np.percentile(mat[mat<0], 20)
vmax = np.percentile(mat[mat>0], 85)
elif weight=='confidence':
mat = ccg_zscore
reordered_nodes = np.array([node2idx[node] for node in ordered_nodes])
mat = mat[reordered_nodes[:,None], reordered_nodes]
mat = np.flip(mat, 1) # from left to right
vmin = np.percentile(mat[mat<0], .5)
vmax = np.percentile(mat[mat>0], 99.2)
elif weight=='weight':
mat = ccg_value
reordered_nodes = np.array([node2idx[node] for node in ordered_nodes])
mat = mat[reordered_nodes[:,None], reordered_nodes]
mat = np.flip(mat, 1) # from left to right
vmin = np.percentile(mat[mat<0], 2)
vmax = np.percentile(mat[mat>0], 98)
cmap = plt.cm.coolwarm
cmap = plt.cm.Spectral
cmap = plt.cm.RdBu_r
norm = colors.TwoSlopeNorm(vmin=vmin, vcenter=0, vmax=vmax)
im = ax.imshow(mat, cmap=cmap, norm=norm)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
if weight is not None:
ec = '.4'
else:
ec = '.8'
for region_ind in range(len(visual_regions)):
ax.add_patch(Rectangle((r_area_inds[region_ind],area_inds[region_ind]),areas_num[region_ind]-1,areas_num[region_ind]-1,linewidth=5,edgecolor=ec,alpha=.6,facecolor='none')) # region_colors[region_ind]
ax.set_xticks([])
ax.set_yticks([])
figname = './figures/figure1D_left.pdf' if weight is not None else './figures/figure1D_right.pdf'
plt.savefig(figname.format(session, stimulus), transparent=True)
################### Figure 1E ###################
def plot_new_ex_in_bar(G_dict, density=False):
df = pd.DataFrame()
sessions, stimuli = get_session_stimulus(G_dict)
for stimulus_ind, stimulus in enumerate(stimuli):
print(stimulus)
combined_stimulus_name = combine_stimulus(stimulus)[1]
ex_data, in_data = [], []
for session_ind, session in enumerate(sessions):
G = G_dict[session][stimulus] if stimulus in G_dict[session] else nx.Graph()
signs = list(nx.get_edge_attributes(G, "sign").values())
num = G.number_of_nodes()
if density:
ex_data.append(signs.count(1) / (num * (num-1)))
in_data.append(signs.count(-1) / (num * (num-1)))
else:
ex_data.append(signs.count(1))
in_data.append(signs.count(-1))
df = pd.concat([df, pd.DataFrame(np.concatenate((np.array(ex_data)[:,None], np.array(['excitatory'] * len(ex_data))[:,None], np.array([combined_stimulus_name] * len(ex_data))[:,None]), 1), columns=['number of connections', 'type', 'stimulus']),
pd.DataFrame(np.concatenate((np.array(in_data)[:,None], np.array(['inhibitory'] * len(in_data))[:,None], np.array([combined_stimulus_name] * len(in_data))[:,None]), 1), columns=['number of connections', 'type', 'stimulus'])], ignore_index=True)
df['number of connections'] = pd.to_numeric(df['number of connections'])
if density:
y = 'density'
df['density'] = df['number of connections']
else:
y = 'number of connections'
fig = plt.figure(figsize=(8, 5))
barcolors = ['firebrick', 'navy']
ax = sns.barplot(x="stimulus", y=y, hue="type", data=df, palette=barcolors, errorbar="sd", edgecolor="black", errcolor="black", errwidth=1.5, capsize = 0.1, alpha=0.5) #, width=.6
sns.stripplot(x="stimulus", y=y, hue="type", palette=barcolors, data=df, dodge=True, alpha=0.6, ax=ax)
# remove extra legend handles
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[2:], labels[2:], title='', bbox_to_anchor=(.7, 1.), loc='upper left', fontsize=28, frameon=False)
plt.yticks(fontsize=25) #, weight='bold'
plt.ylabel(y.capitalize())
ax.set_ylabel(ax.get_ylabel(), fontsize=30,color='k') #, weight='bold'
for axis in ['bottom', 'left']:
ax.spines[axis].set_linewidth(2.5)
ax.spines[axis].set_color('k')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(width=2.5)
ax.set(xlabel=None)
plt.xticks([])
plt.tight_layout()
figname = './figures/figure1E.pdf'
plt.savefig(figname, transparent=True)
################### Figure 1F ###################
def scatter_dataVSdensity(G_dict, area_dict, regions, name='intra'):
sessions, stimuli = get_session_stimulus(G_dict)
fig, ax = plt.subplots(figsize=(5, 5))
X, Y = [], []
df = pd.DataFrame()
region_connection = np.zeros((len(sessions), len(stimuli), len(regions), len(regions)))
for stimulus_ind, stimulus in enumerate(stimuli):
intra_data, inter_data, density_data, ex_data, in_data, cluster_data = [], [], [], [], [], []
for session_ind, session in enumerate(sessions):
G = G_dict[session][stimulus]
nodes = list(G.nodes())
node_area = {key: area_dict[session][key] for key in nodes}
A = nx.to_numpy_array(G)
A[A.nonzero()] = 1
for region_ind_i, region_i in enumerate(regions):
for region_ind_j, region_j in enumerate(regions):
region_indices_i = np.array([k for k, v in area_dict[session].items() if v==region_i])
region_indices_j = np.array([k for k, v in area_dict[session].items() if v==region_j])
region_indices_i = np.array([nodes.index(i) for i in list(set(region_indices_i) & set(nodes))]) # some nodes not in cc are removed
region_indices_j = np.array([nodes.index(i) for i in list(set(region_indices_j) & set(nodes))])
if len(region_indices_i) and len(region_indices_j):
region_connection[session_ind, stimulus_ind, region_ind_i, region_ind_j] = np.sum(A[region_indices_i[:, None], region_indices_j])
assert np.sum(A[region_indices_i[:, None], region_indices_j]) == len(A[region_indices_i[:, None], region_indices_j].nonzero()[0])
diag_indx = np.eye(len(regions),dtype=bool)
intra_data.append(np.sum(region_connection[session_ind, stimulus_ind][diag_indx])/np.sum(region_connection[session_ind, stimulus_ind]))
inter_data.append(np.sum(region_connection[session_ind, stimulus_ind][~diag_indx])/np.sum(region_connection[session_ind, stimulus_ind]))
density_data.append(nx.density(G))
signs = list(nx.get_edge_attributes(G, "sign").values())
ex_data.append(signs.count(1) / len(signs))
in_data.append(signs.count(-1) / len(signs))
cluster_data.append(calculate_directed_metric(G, 'clustering'))
X += density_data
if name == 'intra':
Y += intra_data
elif name == 'ex':
Y += ex_data
elif name == 'cluster':
Y += cluster_data
df = pd.concat([df, pd.DataFrame(np.concatenate((np.array(intra_data)[:,None], np.array(inter_data)[:,None], np.array(ex_data)[:,None], np.array(cluster_data)[:,None], np.array(density_data)[:,None], np.array([combine_stimulus(stimulus)[1]] * len(intra_data))[:,None]), 1), columns=['ratio of intra-region connections', 'ratio of inter-region connections', 'ratio of excitatory connections', 'cluster', 'density', 'stimulus'])], ignore_index=True)
df['ratio of intra-region connections'] = pd.to_numeric(df['ratio of intra-region connections'])
df['ratio of inter-region connections'] = pd.to_numeric(df['ratio of inter-region connections'])
df['ratio of excitatory connections'] = pd.to_numeric(df['ratio of excitatory connections'])
df['cluster'] = pd.to_numeric(df['cluster'])
df['density'] = pd.to_numeric(df['density'])
for cs_ind, combined_stimulus_name in enumerate(combined_stimulus_names):
x = df[df['stimulus']==combined_stimulus_name]['density'].values
if name == 'intra':
y = df[df['stimulus']==combined_stimulus_name]['ratio of intra-region connections'].values
elif name == 'ex':
y = df[df['stimulus']==combined_stimulus_name]['ratio of excitatory connections'].values
elif name == 'cluster':
y = df[df['stimulus']==combined_stimulus_name]['cluster'].values
ax.scatter(x, y, ec='.1', fc='none', marker=stimulus2marker[combined_stimulus_name], s=10*marker_size_dict[stimulus2marker[combined_stimulus_name]], alpha=.9, linewidths=1.5)
X, Y = (list(t) for t in zip(*sorted(zip(X, Y))))
X, Y = np.array(X), np.array(Y)
if name in ['intra']:
slope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)
line = slope*X+intercept
locx, locy = .8, .9
text = 'r={:.2f}, p={:.2f}'.format(r_value, p_value)
elif name in ['ex', 'cluster']:
slope, intercept, r_value, p_value, std_err = stats.linregress(np.log10(X),Y)
line = slope*np.log10(X)+intercept
locx, locy = .4, 1.
text = 'r={:.2f}, p={:.1e}'.format(r_value, p_value)
ax.plot(X, line, color='.2', linestyle=(5,(10,3)), alpha=.5)
# ax.plot(X, line, color='.4', linestyle='-', alpha=.5) # (5,(10,3))
# ax.scatter(X, Y, facecolors='none', edgecolors='.2', alpha=.6)
ax.text(locx, locy, text, horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, fontsize=22)
plt.xticks(fontsize=22) #, weight='bold'
plt.yticks(fontsize=22) # , weight='bold'
plt.xlabel('Density')
if name == 'intra':
ylabel = 'Within-area fraction'
elif name == 'ex':
ylabel = 'Excitatory fraction'
plt.xscale('log')
elif name == 'cluster':
ylabel = 'Clustering coefficient'
plt.xscale('log')
plt.ylabel(ylabel)
ax.set_xlabel(ax.get_xlabel(), fontsize=28,color='k') #, weight='bold'
ax.set_ylabel(ax.get_ylabel(), fontsize=28,color='k') #, weight='bold'
for axis in ['bottom', 'left']:
ax.spines[axis].set_linewidth(1.5)
ax.spines[axis].set_color('0.2')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(width=1.5)
plt.tight_layout()
# plt.show()
if name == 'intra':
fname = 'left'
elif name == 'ex':
fname = 'middle'
elif name == 'cluster':
fname = 'right'
plt.savefig(f'./figures/figure1F_{fname}.pdf', transparent=True)
################### Figure 1G ###################
def get_pos_neg_p_signalcorr(G_dict, active_area_dict, signal_correlation_dict, pairtype='all'):
sessions = signal_correlation_dict.keys()
pos_connect_dict, neg_connect_dict, dis_connect_dict, signal_corr_dict = [{session:{csn:[] for csn in combined_stimulus_names[1:]} for session in sessions} for _ in range(4)]
for session_ind, session in enumerate(sessions):
print(session)
active_area = active_area_dict[session]
node_idx = sorted(active_area.keys())
for combined_stimulus_name in combined_stimulus_names[2:]: # exclude spontaneous and flashes in signal correlation analysis
cs_ind = combined_stimulus_names.index(combined_stimulus_name)
signal_correlation = signal_correlation_dict[session][combined_stimulus_name]
pos_connect, neg_connect, dis_connect, signal_corr = [], [], [], []
for stimulus in combined_stimuli[cs_ind]:
G = G_dict[session][stimulus].copy()
nodes = sorted(G.nodes())
for nodei, nodej in itertools.combinations(node_idx, 2):
scorr = signal_correlation[nodes.index(nodei), nodes.index(nodej)] # abs(signal_correlation[nodei, nodej])
if not np.isnan(scorr):
if G.has_edge(nodei, nodej):
signal_corr.append(scorr)
w = G[nodei][nodej]['weight']
if w > 0:
pos_connect.append(1)
neg_connect.append(0)
elif w < 0:
pos_connect.append(0)
neg_connect.append(1)
if G.has_edge(nodej, nodei):
signal_corr.append(scorr)
w = G[nodej][nodei]['weight']
if w > 0:
pos_connect.append(1)
neg_connect.append(0)
elif w < 0:
pos_connect.append(0)
neg_connect.append(1)
if pairtype == 'all':
if (not G.has_edge(nodei, nodej)) and (not G.has_edge(nodej, nodei)):
dis_connect.append(scorr)
signal_corr.append(scorr)
pos_connect.append(0)
neg_connect.append(0)
signal_corr_dict[session][combined_stimulus_name] += signal_corr
pos_connect_dict[session][combined_stimulus_name] += pos_connect
neg_connect_dict[session][combined_stimulus_name] += neg_connect
dis_connect_dict[session][combined_stimulus_name] += dis_connect
pos_df, neg_df, dis_df = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
for combined_stimulus_name in combined_stimulus_names[1:]:
print(combined_stimulus_name)
for session in sessions:
pos_connect, neg_connect, dis_connect, signal_corr = pos_connect_dict[session][combined_stimulus_name], neg_connect_dict[session][combined_stimulus_name], dis_connect_dict[session][combined_stimulus_name], signal_corr_dict[session][combined_stimulus_name]
# within_comm, across_comm = [e for e in within_comm if not np.isnan(e)], [e for e in across_comm if not np.isnan(e)] # remove nan values
pos_df = pd.concat([pos_df, pd.DataFrame(np.concatenate((np.array(signal_corr)[:,None], np.array(pos_connect)[:,None], np.array([combined_stimulus_name] * len(pos_connect))[:,None], np.array([session] * len(pos_connect))[:,None]), 1), columns=['signal correlation', 'type', 'stimulus', 'session'])], ignore_index=True)
neg_df = pd.concat([neg_df, pd.DataFrame(np.concatenate((np.array(signal_corr)[:,None], np.array(neg_connect)[:,None], np.array([combined_stimulus_name] * len(neg_connect))[:,None], np.array([session] * len(neg_connect))[:,None]), 1), columns=['signal correlation', 'type', 'stimulus', 'session'])], ignore_index=True)
dis_df = pd.concat([dis_df, pd.DataFrame(np.concatenate((np.array(dis_connect)[:,None], np.array([combined_stimulus_name] * len(dis_connect))[:,None], np.array([session] * len(dis_connect))[:,None]), 1), columns=['signal correlation', 'stimulus', 'session'])], ignore_index=True)
pos_df['signal correlation'] = pd.to_numeric(pos_df['signal correlation'])
pos_df['type'] = pd.to_numeric(pos_df['type'])
neg_df['signal correlation'] = pd.to_numeric(neg_df['signal correlation'])
neg_df['type'] = pd.to_numeric(neg_df['type'])
dis_df['signal correlation'] = pd.to_numeric(dis_df['signal correlation'])
return pos_df, neg_df, dis_df
def plot_pos_neg_signal_correlation_distri(pos_df, neg_df, dis_df):
fig, axes = plt.subplots(1,len(combined_stimulus_names)-2, figsize=(5*(len(combined_stimulus_names)-2), 3), sharex=True)
for cs_ind in range(len(axes)):
ax = axes[cs_ind]
pos_data = pos_df[(pos_df.stimulus==combined_stimulus_names[cs_ind+2]) & (pos_df.type==1)].copy() # & (df.session==session)
neg_data = neg_df[(neg_df.stimulus==combined_stimulus_names[cs_ind+2]) & (neg_df.type==1)].copy() # & (df.session==session)
dis_data = dis_df[dis_df.stimulus==combined_stimulus_names[cs_ind+2]].copy()
pos_x, neg_x, dis_x = pos_data['signal correlation'].values.flatten(), neg_data['signal correlation'].values.flatten(), dis_data['signal correlation'].values.flatten()
df = pd.DataFrame()
df = pd.concat([df, pd.DataFrame(np.concatenate((np.array(pos_x)[:,None], np.array(['excitatory'] * len(pos_x))[:,None]), 1), columns=['signal correlation', 'type'])], ignore_index=True)
df = pd.concat([df, pd.DataFrame(np.concatenate((np.array(neg_x)[:,None], np.array(['inhibitory'] * len(neg_x))[:,None]), 1), columns=['signal correlation', 'type'])], ignore_index=True)
df = pd.concat([df, pd.DataFrame(np.concatenate((np.array(dis_x)[:,None], np.array(['disconnected'] * len(dis_x))[:,None]), 1), columns=['signal correlation', 'type'])], ignore_index=True)
df['signal correlation'] = pd.to_numeric(df['signal correlation'])
# sns.histplot(data=df, x='signal correlation', hue='type', stat='probability', common_norm=False, ax=ax, palette=['r', 'b', 'grey'], alpha=0.4)
sns.kdeplot(data=df, x='signal correlation', hue='type', common_norm=False, ax=ax, palette=['r', 'b', 'grey'], alpha=.8)
ax.xaxis.set_tick_params(labelsize=30)
ax.yaxis.set_tick_params(labelsize=30)
for axis in ['bottom', 'left']:
ax.spines[axis].set_linewidth(2.5)
ax.spines[axis].set_color('k')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(width=2.5)
ax.set_xlabel([], fontsize=0)
if cs_ind == 0:
ax.set_ylabel('KDE', fontsize=30)
else:
ax.set_ylabel([], fontsize=0)
# ax.set_xlabel('Signal correlation', fontsize=25)
# handles, labels = ax.get_legend_handles_labels()
ax.legend().set_visible(False)
plt.tight_layout(rect=[.01, 0, 1, 1])
plt.savefig('./figures/figure1G.pdf', transparent=True)
################### Figure 2A ###################
def safe_division(n, d):
return n / d if d else 0
def count_signed_triplet_connection_p(G):
num0, num1, num2, num3, num4, num5 = 0, 0, 0, 0, 0, 0
nodes = list(G.nodes())
edge_sign = nx.get_edge_attributes(G,'sign')
for node_i in range(len(nodes)):
for node_j in range(len(nodes)):
if node_i != node_j:
edge_sum = edge_sign.get((nodes[node_i], nodes[node_j]), 0) + edge_sign.get((nodes[node_j], nodes[node_i]), 0)
if edge_sum == 0:
if G.has_edge(nodes[node_i], nodes[node_j]) and G.has_edge(nodes[node_j], nodes[node_i]):
num4 += 1
else:
num0 += 1
elif edge_sum == 1:
num1 += 1
elif edge_sum == 2:
num3 += 1
elif edge_sum == -1:
num2 += 1
elif edge_sum == -2:
num5 += 1
total_num = num0+num1+num2+num3+num4+num5
assert total_num == len(nodes) * (len(nodes) - 1)
assert (num1+num2)/2 + num3+num4+num5 == G.number_of_edges()
p0, p1, p2, p3, p4, p5 = safe_division(num0, total_num), safe_division(num1, total_num), safe_division(num2, total_num), safe_division(num3, total_num), safe_division(num4, total_num), safe_division(num5, total_num)
return p0, p1, p2, p3, p4, p5
def plot_signed_pair_relative_count(G_dict, p_signed_pair_func, log=False):
sessions, stimuli = get_session_stimulus(G_dict)
fig, axes = plt.subplots(len(combined_stimulus_names), 1, figsize=(8, 1.*len(combined_stimulus_names)), sharex=True, sharey=True)
for cs_ind, stimulus_name in enumerate(combined_stimulus_names):
ax = axes[len(axes)-1-cs_ind] # spontaneous in the bottom
all_pair_count = defaultdict(lambda: [])
for stimulus in combined_stimuli[cs_ind]:
for session in sessions:
G = G_dict[session][stimulus].copy()
signs = list(nx.get_edge_attributes(G, "sign").values())
p_pos, p_neg = signs.count(1)/(G.number_of_nodes()*(G.number_of_nodes()-1)), signs.count(-1)/(G.number_of_nodes()*(G.number_of_nodes()-1))
p0, p1, p2, p3, p4, p5 = count_signed_triplet_connection_p(G)
all_pair_count['0'].append(p0 / p_signed_pair_func['0'](p_pos, p_neg))
all_pair_count['+'].append(p1 / p_signed_pair_func['1'](p_pos, p_neg))
all_pair_count['-'].append(p2 / p_signed_pair_func['2'](p_pos, p_neg))
all_pair_count['++'].append(p3 / p_signed_pair_func['3'](p_pos, p_neg))
all_pair_count['+-'].append(p4 / p_signed_pair_func['4'](p_pos, p_neg))
all_pair_count['--'].append(p5 / p_signed_pair_func['5'](p_pos, p_neg))
# ax.set_ylabel('Relative count')
triad_types, triad_counts = [k for k,v in all_pair_count.items()], [v for k,v in all_pair_count.items()]
box_color = '.2'
boxprops = dict(color=box_color,linewidth=1.5)
medianprops = dict(color=box_color,linewidth=1.5)
box_plot = ax.boxplot(triad_counts, showfliers=False, patch_artist=True, boxprops=boxprops,medianprops=medianprops)
for item in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
plt.setp(box_plot[item], color=box_color)
for patch in box_plot['boxes']:
patch.set_facecolor('none')
ax.set_xticks([])
left, right = plt.xlim()
ax.hlines(1, xmin=left, xmax=right, color='.5', alpha=.6, linestyles='--', linewidth=2)
if log:
ax.set_yscale('log')
ax.yaxis.set_tick_params(labelsize=18)
ax.set_ylabel('', fontsize=20,color='k') #, weight='bold'
for axis in ['bottom', 'left']:
ax.spines[axis].set_linewidth(1.)
ax.spines[axis].set_color('k')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(width=1.)
relative_x = 0.1
relative_y = 0.9
ax.text(relative_x, relative_y, stimulus_name.replace('\n', ' '), transform=ax.transAxes,
ha='left', va='center', fontsize=20, color='black')
fig.subplots_adjust(hspace=.7) #wspace=0.2
plt.savefig('./figures/figure2A.pdf', transparent=True)
p_signed_pair_func = {
'0': lambda p_pos, p_neg: (1 - p_pos - p_neg)**2,
'1': lambda p_pos, p_neg: 2 * p_pos * (1 - p_pos - p_neg),
'2': lambda p_pos, p_neg: 2 * p_neg * (1 - p_pos - p_neg),
'3': lambda p_pos, p_neg: p_pos ** 2,
'4': lambda p_pos, p_neg: 2 * p_pos * p_neg,
'5': lambda p_pos, p_neg: p_neg ** 2,
}
################## find significant signed motifs using z score for motif intensity and coherence
################## first Z score, then average
def get_intensity_zscore(intensity_dict, coherence_dict, baseline_intensity_dict, baseline_coherence_dict, num_baseline=100):
sessions, stimuli = get_session_stimulus(intensity_dict)
signed_motif_types = set()
for session in sessions:
for stimulus in stimuli:
signed_motif_types = signed_motif_types.union(set(list(intensity_dict[session][stimulus].keys())).union(set(list(baseline_intensity_dict[session][stimulus].keys()))))
signed_motif_types = list(signed_motif_types)
pseudo_intensity = np.zeros(num_baseline)
pseudo_intensity[0] = 5 # if a motif is not found in random graphs, assume it appeared once
whole_df = pd.DataFrame()
for stimulus in stimuli:
for session in sessions:
motif_list = []
for motif_type in signed_motif_types:
motif_list.append([motif_type, session, stimulus, intensity_dict[session][stimulus].get(motif_type, 0), baseline_intensity_dict[session][stimulus].get(motif_type, pseudo_intensity).mean(),
baseline_intensity_dict[session][stimulus].get(motif_type, pseudo_intensity).std(), coherence_dict[session][stimulus].get(motif_type, 0),
baseline_coherence_dict[session][stimulus].get(motif_type, np.zeros(10)).mean(), baseline_coherence_dict[session][stimulus].get(motif_type, np.zeros(10)).std()])
df = pd.DataFrame(motif_list, columns =['signed motif type', 'session', 'stimulus', 'intensity', 'intensity mean', 'intensity std', 'coherence', 'coherence mean', 'coherence std'])
whole_df = pd.concat([whole_df, df], ignore_index=True, sort=False)
whole_df['intensity z score'] = (whole_df['intensity']-whole_df['intensity mean'])/whole_df['intensity std']
whole_df['coherence z score'] = (whole_df['coherence']-whole_df['coherence mean'])/whole_df['coherence std']
mean_df = whole_df.groupby(['stimulus', 'signed motif type'], as_index=False).agg('mean') # average over session
std_df = whole_df.groupby(['stimulus', 'signed motif type'], as_index=False).agg('std')
mean_df['intensity z score std'] = std_df['intensity z score']
return whole_df, mean_df, signed_motif_types
################### Figure 2C ###################
def plot_zscore_allmotif_lollipop(df, model_name):
fig, axes = plt.subplots(len(combined_stimulus_names),1, sharex=True, sharey=True, figsize=(50, 3*len(combined_stimulus_names)))
sorted_types = [sorted([smotif for smotif in df['signed motif type'].unique() if mt in smotif]) for mt in TRIAD_NAMES]
sorted_types = [item for sublist in sorted_types for item in sublist]
motif_types = TRIAD_NAMES[3:]
motif_loc = [np.mean([i for i in range(len(sorted_types)) if mt in sorted_types[i]]) for mt in motif_types]
palette = [[plt.cm.tab20b(i) for i in range(20)][i] for i in [0,2,3,4,6,8,10,12,16,18,19]] + [[plt.cm.tab20c(i) for i in range(20)][i] for i in [4,16]]
for s_ind, combined_stimulus_name in enumerate(combined_stimulus_names):
print(combined_stimulus_name)
data = df[df.apply(lambda x: combine_stimulus(x['stimulus'])[1], axis=1)==combined_stimulus_name]
data = data.groupby('signed motif type').mean()
ax = axes[len(axes)-1-s_ind] # spontaneous in the bottom
# ax.set_title(combined_stimulus_names[s_ind].replace('\n', ' '), fontsize=35, rotation=0)
for t, y in zip(sorted_types, data.loc[sorted_types, "intensity z score"]):
color = palette[motif_types.index(t.replace('+', '').replace('\N{MINUS SIGN}', ''))]
ax.plot([t,t], [0,y], color=color, marker="o", linewidth=7, markersize=20, markevery=(1,2))
ax.set_xlim(-.5,len(sorted_types)+.5)
ax.set_xticks([])
ax.yaxis.set_tick_params(labelsize=45)
for axis in ['bottom', 'left']:
ax.spines[axis].set_linewidth(4.5)
ax.spines[axis].set_color('k')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(width=4.5)
ax.xaxis.set_tick_params(length=0)
ax.set_ylabel('')
# ax.set_ylabel('Z score', fontsize=40)
if model_names.index(model_name) <= 1:
ax.set_yscale('symlog')
else:
ax.set_ylim(-13, 21)
plt.tight_layout()
plt.savefig('./figures/figure2C.pdf', transparent=True)
################### Figure 3A ###################
def scatter_ZscoreVSdensity(origin_df, G_dict):
df = origin_df.copy()
df['density'] = 0
sessions, stimuli = get_session_stimulus(G_dict)
fig, ax = plt.subplots(figsize=(5, 5))
for session_ind, session in enumerate(sessions):
for stimulus in stimuli:
G = G_dict[session][stimulus]
df.loc[(df['session']==session) & (df['stimulus']==stimulus), 'density'] = nx.density(G)
df['density'] = pd.to_numeric(df['density'])
df['intensity z score'] = df['intensity z score'].abs()
X, Y = [], []
for cs_ind, combined_stimulus_name in enumerate(combined_stimulus_names):
print(combined_stimulus_name)
data = df[df.apply(lambda x: combine_stimulus(x['stimulus'])[1], axis=1)==combined_stimulus_name]
data = data.groupby(['stimulus', 'session']).mean(numeric_only=True)
# print(data['density'].values)
x = data['density'].values.tolist()
y = data['intensity z score'].values.tolist()
X += x
Y += y
ax.scatter(x, y, ec='.1', fc='none', marker=stimulus2marker[combined_stimulus_name], s=10*marker_size_dict[stimulus2marker[combined_stimulus_name]], alpha=.9, linewidths=1.5)
X, Y = (list(t) for t in zip(*sorted(zip(X, Y))))
X, Y = np.array(X), np.array(Y)
slope, intercept, r_value, p_value, std_err = stats.linregress(np.log10(X),Y)
line = slope*np.log10(X)+intercept
locx, locy = .8, .1
text = 'r={:.2f}, p={:.1e}'.format(r_value, p_value)
ax.plot(X, line, color='.2', linestyle=(5,(10,3)), alpha=.5)
ax.text(locx, locy, text, horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes, fontsize=22)
ax.xaxis.set_tick_params(labelsize=25)
ax.yaxis.set_tick_params(labelsize=25)
plt.xlabel('Density')
ylabel = 'Absolute motif significance' # 'Absolute Z score'
plt.xscale('log')
plt.ylabel(ylabel)
ax.set_xlabel(ax.get_xlabel(), fontsize=28,color='k') #, weight='bold'
ax.set_ylabel(ax.get_ylabel(), fontsize=28,color='k') #, weight='bold'
for axis in ['bottom', 'left']:
ax.spines[axis].set_linewidth(1.5)
ax.spines[axis].set_color('k')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(width=1.5)
plt.tight_layout(rect=[0, 0, 1, .9])
plt.savefig(f'./figures/figure3A.pdf', transparent=True)
################### Figure 3B ###################
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
new_cmap = colors.LinearSegmentedColormap.from_list(
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
cmap(np.linspace(minval, maxval, n)))
return new_cmap
######################## Heatmap of Pearson Correlation r of Z score
def plot_heatmap_correlation_zscore(df):
fig, ax = plt.subplots(1,1, figsize=(5.6,5))
sorted_types = [sorted([smotif for smotif in df['signed motif type'].unique() if mt in smotif]) for mt in TRIAD_NAMES]
sorted_types = [item for sublist in sorted_types for item in sublist]
data_mat = np.zeros((len(combined_stimulus_names), len(sorted_types)))
for s_ind, combined_stimulus_name in enumerate(combined_stimulus_names):
print(combined_stimulus_name)
data = df[df.apply(lambda x: combine_stimulus(x['stimulus'])[1], axis=1)==combined_stimulus_name]
data = data.groupby('signed motif type').mean(numeric_only=True)
data_mat[s_ind] = data.loc[sorted_types, "intensity z score"].values.flatten()
hm_z = np.corrcoef(data_mat)
np.fill_diagonal(hm_z, np.nan)
colors = ['w', '.3'] # first color is black, last is red
cm = LinearSegmentedColormap.from_list(
"Custom", colors, N=20)
hm = sns.heatmap(hm_z, ax=ax, cmap=cm, vmin=0, vmax=1, cbar=True, annot=True, annot_kws={'fontsize':20})#, mask=mask
cbar = hm.collections[0].colorbar
cbar.ax.tick_params(labelsize=24)
ax.set_title('Motif significance correlation', fontsize=25)
ax.set_xticks([])
ax.set_yticks([])
ax.invert_yaxis() # put spontaneous on the bottom
hm.tick_params(left=False) # remove the ticks
hm.tick_params(bottom=False)
hm.tick_params(top=False)
fig.tight_layout()
plt.savefig('./figures/figure3B.pdf', transparent=True)
################### Figure 3C ###################
def get_signalcorr_within_across_motif(G_dict, active_area_dict, mean_df, eFFLb_types, all_motif_types, signal_correlation_dict, pair_type='all'):
sessions, stimuli = get_session_stimulus(G_dict)
within_eFFLb_dict, within_motif_dict, across_motif_dict = {}, {}, {}
motif_types = []
motif_edges, motif_sms = {}, {}
for signed_motif_type in all_motif_types:
motif_types.append(signed_motif_type.replace('+', '').replace('-', ''))
for motif_type in motif_types:
motif_edges[motif_type], motif_sms[motif_type] = get_edges_sms(motif_type, weight='confidence')
for session_ind, session in enumerate(sessions):
print(session)
active_area = active_area_dict[session]
node_idx = sorted(active_area.keys())
within_eFFLb_dict[session], within_motif_dict[session], across_motif_dict[session] = {}, {}, {}
for cs_ind, combined_stimulus_name in enumerate(combined_stimulus_names[2:]):
for stimulus in combined_stimuli[combined_stimulus_names.index(combined_stimulus_name)]:
print(stimulus)
df = mean_df[mean_df['stimulus']==stimulus]
sig_motifs = df.loc[df['intensity z score'] > 2.576]['signed motif type'].tolist() # 99%
within_eFFLb_dict[session][stimulus], within_motif_dict[session][stimulus], across_motif_dict[session][stimulus] = [], [], []
G = G_dict[session][stimulus]
nodes = sorted(G.nodes())
signal_corr = signal_correlation_dict[session][combined_stimulus_name]
motifs_by_type = find_triads(G)
if pair_type == 'all': # all neuron pairs
neuron_pairs = list(itertools.combinations(node_idx, 2))
elif pair_type == 'connected': # limited to connected pairs only
neuron_pairs = list(G.to_undirected().edges())
neuron_pairs = [tuple([nodes.index(node) for node in e]) for e in neuron_pairs]
other_edges = set(neuron_pairs)
for motif_type in motif_types:
motifs = motifs_by_type[motif_type]
for motif in motifs:
smotif_type = motif_type + get_motif_sign(motif, motif_edges[motif_type], motif_sms[motif_type], weight='confidence')
# smotif_type = motif_type + get_motif_sign(motif, motif_type, weight='weight')
if pair_type == 'all': # all neuron pairs
motif_pairs = list(itertools.combinations(motif.nodes(), 2))
elif pair_type == 'connected': # limited to connected pairs only
motif_pairs = list(motif.to_undirected().edges())
motif_pairs = [tuple([nodes.index(node) for node in e]) for e in motif_pairs]
within_signal_corr = [signal_corr[e] for e in motif_pairs if not np.isnan(signal_corr[e])]
if len(within_signal_corr):
if smotif_type in eFFLb_types:
within_eFFLb_dict[session][stimulus] += within_signal_corr
other_edges -= set(motif_pairs)
# else: # if all motifs
elif smotif_type in sig_motifs:
within_motif_dict[session][stimulus] += within_signal_corr
other_edges -= set(motif_pairs)
for e in other_edges:
if not np.isnan(signal_corr[e]):
across_motif_dict[session][stimulus].append(signal_corr[e])
df = pd.DataFrame()
for cs_ind, combined_stimulus_name in enumerate(combined_stimulus_names[2:]):
for stimulus in combined_stimuli[combined_stimulus_names.index(combined_stimulus_name)]:
for session in sessions:
within_eFFLb, within_motif, across_motif = within_eFFLb_dict[session][stimulus], within_motif_dict[session][stimulus], across_motif_dict[session][stimulus]
# within_motif, across_motif = [e for e in within_motif if not np.isnan(e)], [e for e in across_motif if not np.isnan(e)] # remove nan values
df = pd.concat([df, pd.DataFrame(np.concatenate((np.array(within_eFFLb)[:,None], np.array(['within eFFLb'] * len(within_eFFLb))[:,None], np.array([combined_stimulus_name] * len(within_eFFLb))[:,None], np.array([session] * len(within_eFFLb))[:,None]), 1), columns=['signal_corr', 'type', 'stimulus', 'session'])], ignore_index=True)
df = pd.concat([df, pd.DataFrame(np.concatenate((np.array(within_motif)[:,None], np.array(['within other motif'] * len(within_motif))[:,None], np.array([combined_stimulus_name] * len(within_motif))[:,None], np.array([session] * len(within_motif))[:,None]), 1), columns=['signal_corr', 'type', 'stimulus', 'session'])], ignore_index=True)
df = pd.concat([df, pd.DataFrame(np.concatenate((np.array(across_motif)[:,None], np.array(['otherwise'] * len(across_motif))[:,None], np.array([combined_stimulus_name] * len(across_motif))[:,None], np.array([session] * len(across_motif))[:,None]), 1), columns=['signal_corr', 'type', 'stimulus', 'session'])], ignore_index=True)
df['signal_corr'] = pd.to_numeric(df['signal_corr'])
return df
def plot_signalcorr_within_across_motif_significance(origin_df, pair_type='all'):
df = origin_df.copy()
# df = df[df['stimulus']!='Flashes'] # remove flashes
fig, ax = plt.subplots(1,1, figsize=(2*(len(combined_stimulus_names)-2), 5))
df = df.set_index('stimulus')
df = df.loc[combined_stimulus_names[2:]]
df.reset_index(inplace=True)
palette = ['k', 'grey','w']
y = 'signal_corr'
barplot = sns.barplot(x='stimulus', y=y, hue="type", hue_order=['within eFFLb', 'within other motif', 'otherwise'], palette=palette, ec='k', linewidth=2., data=df, ax=ax, capsize=.05, width=0.6)
ax.yaxis.set_tick_params(labelsize=30)
plt.setp(ax.get_legend().get_title(), fontsize='0') # for legend title
plt.xticks([], []) # use markers to represent stimuli!
ax.xaxis.set_tick_params(length=0)
for axis in ['bottom', 'left']:
ax.spines[axis].set_linewidth(2)
ax.spines[axis].set_color('k')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(width=2)
ax.set_xlabel('')
ax.set_ylabel('Signal correlation', fontsize=40) #'Absolute ' +
handles, labels = ax.get_legend_handles_labels()
ax.legend([], [], fontsize=0)
# add significance annotation
alpha_list = [.0001, .001, .01, .05]
maxx = 0
for cs_ind, combined_stimulus_name in enumerate(combined_stimulus_names[2:]):
within_eFFLb, within_motif, across_motif = df[(df.stimulus==combined_stimulus_name)&(df.type=='within eFFLb')][y].values.flatten(), df[(df.stimulus==combined_stimulus_name)&(df.type=='within other motif')][y].values.flatten(), df[(df.stimulus==combined_stimulus_name)&(df.type=='otherwise')][y].values.flatten()
eFFLb_sr, within_sr, across_sr = confidence_interval(within_eFFLb)[1], confidence_interval(within_motif)[1], confidence_interval(across_motif)[1]
maxx = max(eFFLb_sr, within_sr, across_sr) if max(eFFLb_sr, within_sr, across_sr) > maxx else maxx
h, l = .05 * maxx, .05 * maxx
for cs_ind, combined_stimulus_name in enumerate(combined_stimulus_names[2:]):
within_eFFLb, within_motif, across_motif = df[(df.stimulus==combined_stimulus_name)&(df.type=='within eFFLb')][y].values.flatten(), df[(df.stimulus==combined_stimulus_name)&(df.type=='within other motif')][y].values.flatten(), df[(df.stimulus==combined_stimulus_name)&(df.type=='otherwise')][y].values.flatten()
if len(within_motif):