-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpaper_plots.py
7447 lines (6256 loc) · 242 KB
/
paper_plots.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
# ------------------------------------------------------------------------------ #
# @Author: F. Paul Spitzner
# @Email: [email protected]
# @Created: 2021-11-08 17:51:24
# @Last Modified: 2023-05-16 14:11:34
# ------------------------------------------------------------------------------ #
#
# How to read / work this monstrosity of a file?
#
# * Start at the high-level functions for compound figures, they are named `fig_x()`
# and are placed in the beginning. From there, use your code editor to jump
# to lower-level functions that come further down. (in vscode option/alt+click)
#
# * Take a look at the strucutre of the data frames, e.g.
# ```
# dfs = pp.load_pd_hdf5(f"{pp.p_exp}/processed/1b.hdf5")
# dfs["trials"]
# dfs["bursts"]
# ```
# Note that we refactored "Fraction" to "Event size" in the manuscript at some point,
# which has not been translated back into code (yet?).
#
# * I (tried to) prefix functions according to which part they belong to:
# `exp_` `sim_` `meso_` ...
#
# ------------------------------------------------------------------------------ #
import os
from pydoc import doc
import sys
import glob
import re
import h5py
import argparse
import numbers
import logging
import warnings
import functools
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import xarray as xr
import palettable
from tqdm.auto import tqdm
from scipy import stats
from benedict import benedict
# our tools
import bitsandbobs as bnb
from bitsandbobs import plt as cc
import plot_helper as ph
import ana_helper as ah
import ndim_helper as nh
import meso_helper as mh
logging.basicConfig(
format="%(asctime)s | %(levelname)-8s | %(name)-12s | %(message)s",
datefmt="%y-%m-%d %H:%M",
)
log = logging.getLogger(__name__)
log.setLevel("INFO")
warnings.filterwarnings("ignore") # suppress numpy warnings
# ------------------------------------------------------------------------------ #
# Settings
# ------------------------------------------------------------------------------ #
# this is the point in phase space (simulations) that we usually plot.
reference_coordinates = dict()
reference_coordinates["jA"] = 45
reference_coordinates["jG"] = 50
reference_coordinates["tD"] = 20
reference_coordinates["k_inter"] = 5 # connections between modules
reference_coordinates["k_in"] = 30 # avg. in-degree for each neuron. 15 or 30
# we had one trial for single bond where we saw more bursts than everywhere else
remove_outlier = True
# some default file paths, relative to this file
_p_base = os.path.dirname(os.path.realpath(__file__))
# output path for figure panels
p_fo = os.path.abspath(_p_base + f"/../fig/paper/")
p_exp = os.path.abspath(_p_base + f"/../dat/experiments/")
p_sim = os.path.abspath(_p_base + f"/../dat/simulations/")
# ------------------------------------------------------------------------------ #
# Settings, Styling
# ------------------------------------------------------------------------------ #
# select default things to draw for every panel
show_title = True
show_xlabel = True
show_ylabel = True
# legends were mostly done in affinity designer so dont rely on those to work well
show_legend = True
show_legend_in_extra_panel = False
matplotlib.rcParams["axes.labelcolor"] = "black"
matplotlib.rcParams["axes.edgecolor"] = "black"
matplotlib.rcParams["xtick.color"] = "black"
matplotlib.rcParams["ytick.color"] = "black"
matplotlib.rcParams["xtick.labelsize"] = 6
matplotlib.rcParams["ytick.labelsize"] = 6
matplotlib.rcParams["xtick.major.pad"] = 2 # padding between text and the tick
matplotlib.rcParams["ytick.major.pad"] = 2 # default 3.5
matplotlib.rcParams["lines.dash_capstyle"] = "round"
matplotlib.rcParams["lines.solid_capstyle"] = "round"
matplotlib.rcParams["font.size"] = 6
matplotlib.rcParams["mathtext.default"] = "regular"
matplotlib.rcParams["axes.titlesize"] = 6
matplotlib.rcParams["axes.labelsize"] = 6
matplotlib.rcParams["legend.fontsize"] = 6
matplotlib.rcParams["legend.facecolor"] = "#D4D4D4"
matplotlib.rcParams["legend.framealpha"] = 0.8
matplotlib.rcParams["legend.frameon"] = True
matplotlib.rcParams["axes.spines.right"] = False
matplotlib.rcParams["axes.spines.top"] = False
matplotlib.rcParams["figure.figsize"] = [3.4, 2.7] # APS single column
matplotlib.rcParams["figure.dpi"] = 300
matplotlib.rcParams["savefig.facecolor"] = (0.9, 1.0, 1.0, 0.0) # transparent figure bg
matplotlib.rcParams["axes.facecolor"] = (0.9, 1.0, 1.0, 0.0)
# style of error bars 'butt' or 'round'
# "butt" gives precise errors, "round" looks much nicer but most people find it confusing.
# https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/joinstyle.html
_error_bar_cap_style = "butt"
colors = dict()
colors["pre"] = "#9D799D" # old: "#8C668C"
colors["post"] = "#541854"
colors["Off"] = colors["pre"]
colors["stim"] = "#BD6B00"
colors["On"] = colors["stim"]
colors["90 Hz"] = colors["stim"]
# new experimental conditions
colors["stim2"] = "#BD6B00" # stimulating two modules asynchronously, same as stim
colors["stim1"] = "#777" # stimulating one module with full-module pulses
colors["KCl_0mM"] = "gray"
colors["KCl_2mM"] = "gray"
colors["spon_Bic_20uM"] = colors["pre"]
colors["stim_Bic_20uM"] = colors["stim"]
colors["rij_within_stim"] = "#BD6B00"
colors["rij_within_nonstim"] = "#135985"
colors["rij_across"] = "#B31518"
colors["rij_all"] = "#222"
# colors for rasters need to be set when loading the data,
# so its convenient to have a list
# default_mod_colors = ['#9f7854', '#135985', '#ca8933', '#5B647B']
default_mod_colors = ["#BD6B00", "#135985", "#ca8933", "#427A9D"]
colors["k=1"] = dict()
colors["k=1"]["75.0 Hz"] = colors["pre"]
colors["k=1"]["85.0 Hz"] = colors["stim"]
colors["k=5"] = dict()
colors["k=5"]["80.0 Hz"] = colors["pre"]
colors["k=5"]["90.0 Hz"] = colors["stim"]
colors["k=10"] = dict()
colors["k=10"]["85.0 Hz"] = colors["pre"]
colors["k=10"]["92.5 Hz"] = colors["stim"]
colors["partial"] = dict()
colors["partial"]["0.0 Hz"] = colors["pre"]
colors["partial"]["20.0 Hz"] = colors["stim"]
# ------------------------------------------------------------------------------ #
# Whole-figure wrapper functions
# ------------------------------------------------------------------------------ #
def fig_1(show_time_axis=False):
"""
Wrapper for Figure 1 containing
- an example raster plot for single-bond topology
at the stimulation conditions pre | stim | post
- an example raster plot of the single-bond controls exposed to KCl ("chemical")
- Trial-level "stick" plots for Functional Complexity and Event Size,
* comparing pre (left) vs stim (right)
* for optogenetic stimulation (yellow) and chemical (gray)
"""
# set the global seed once for each figure to produce consistent results, when
# calling repeatedly.
# many panels rely on bootstrapping and drawing random samples
np.random.seed(811)
# ------------------------------------------------------------------------------ #
# Create raster plots, need `raw` files
# ------------------------------------------------------------------------------ #
# optogenetic
path = f"{p_exp}/raw/1b"
experiment = "210719_B"
conditions = ["1_pre", "2_stim", "3_post"]
fig_widths = dict()
fig_widths["1_pre"] = 2.4
fig_widths["2_stim"] = 7.2
fig_widths["3_post"] = 2.4
time_ranges = dict()
time_ranges["1_pre"] = [60, 180]
time_ranges["2_stim"] = [58, 418]
time_ranges["3_post"] = [100, 220]
# ph.log.setLevel("DEBUG")
for idx, condition in enumerate(conditions):
log.info(condition)
c_str = condition[2:]
fig = exp_raster_plots(
path,
experiment,
condition,
time_range=time_ranges[condition],
fig_width=fig_widths[condition] * 1.2 / 2.54,
show_fluorescence=False,
)
# if we want axes to have the same size across figures,
# we need to set the axes size again (as figures include padding for legends)
_set_size(ax=fig.axes[0], w=fig_widths[condition], h=None)
if not show_time_axis:
fig.axes[-1].xaxis.set_visible(False)
sns.despine(ax=fig.axes[-1], bottom=True, left=False)
if show_title:
fig.axes[1].set_title(f"{c_str}")
if show_ylabel:
fig.axes[-1].set_ylabel(f"Rate (Hz)")
fig.savefig(f"{p_fo}/exp_combined_{c_str}.pdf", dpi=300, transparent=False)
# chemical
path = f"{p_exp}/raw/KCl_1b"
experiment = "210720_B"
conditions = ["1_KCl_0mM", "2_KCl_2mM"]
fig_widths = dict()
fig_widths["1_KCl_0mM"] = 2.4
fig_widths["2_KCl_2mM"] = 3.6
time_ranges = dict()
time_ranges["1_KCl_0mM"] = [395, 395 + 120]
time_ranges["2_KCl_2mM"] = [295, 295 + 180]
for idx, condition in enumerate(conditions):
log.info(condition)
c_str = condition[2:]
fig = exp_raster_plots(
path,
experiment,
condition,
time_range=time_ranges[condition],
fig_width=fig_widths[condition] * 1.2 / 2.54,
show_fluorescence=False,
)
_set_size(ax=fig.axes[0], w=fig_widths[condition], h=None)
if not show_time_axis:
fig.axes[-1].xaxis.set_visible(False)
sns.despine(ax=fig.axes[-1], bottom=True, left=False)
if show_title:
fig.axes[1].set_title(f"{c_str}")
if show_ylabel:
fig.axes[-1].set_ylabel(f"Rate (Hz)")
fig.savefig(f"{p_fo}/exp_combined_{c_str}.pdf", dpi=300, transparent=False)
# ------------------------------------------------------------------------------ #
# Stick plots for optogenetic vs chemical
# ------------------------------------------------------------------------------ #
for obs in [
"Functional Complexity",
"Median Fraction",
"Median Neuron Correlation",
# "Median Module Correlation",
# "Mean Rate",
# "Mean IBI",
]:
ax = exp_chemical_vs_opto(observable=obs, draw_error_bars=False)
cc.set_size(ax, w=1.2, h=1.6, l=1.2, r=0.7, b=0.2, t=0.5)
ax.grid(axis="y", which="both", color="0.8", lw=0.5, zorder=-1, clip_on=False)
ax.set_ylim(0, 1.0)
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.5))
ax.yaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(0.1))
sns.despine(ax=ax, bottom=True, left=False, trim=True, offset=2)
ax.get_figure().savefig(f"{p_fo}/exp_chem_vs_opto_{obs}.pdf", dpi=300)
if show_title or show_ylabel:
# we changed naming conventions at some point
o_str = "Event size" if obs == "Mean Fraction" else obs
ax.set_title(f"{o_str}")
def fig_2(skip_plots=False, pd_folder=None, out_prefix=None):
"""
Wrapper for Figure 2 containing
- pooled Violins that aggregate the results of all trials for
* observables: Event size, Correclation Coefficient, IEI, Burst-Core delay
* sorted by topology: single-bond | triple-bond | merged
* for conditions: pre | stim | post,
- Decomposition plots (scatter and bar) that show Correlation Coefficients
* sorted by the location of the neuron pairs:
- both targeted (yellow)
- both not targeted (blue)
- either one targeted (red)
* for conditions: pre (dark) vs stim (light)
- Trial level stick plots of FC for all topologies, 1-b, 3-b, merged
"""
if pd_folder is None:
pd_folder = f"{p_exp}/processed"
if out_prefix is None:
out_prefix = f"{p_fo}/exp_f2_"
# set the global seed once for each figure to produce consistent results, when
# calling repeatedly.
# many panels rely on bootstrapping and drawing random samples
np.random.seed(812)
filter_trials = {
"single-bond": "210719_B",
# '210315_C', '210406_B', '210406_C', '210726_B', '210315_A', '210719_C', '210719_B'
"triple-bond": "210402_B",
# '210713_A', '210316_C', '210402_B', '210401_A', '210713_C', '210713_B', '210316_A'
"merged": "210726_C",
# '210406_B', '210405_A', '210726_B', '210401_A', '210726_C', '210713_C', '210406_A'
}
filter_trials = None # pool everything, specify to only plot violins for those.
if not skip_plots:
exp_violins_for_layouts(
pd_folder=pd_folder,
out_prefix=f"{out_prefix}",
filter_trials=filter_trials,
)
exp_rij_for_layouts(
pd_folder=pd_folder,
out_prefix=out_prefix,
filter_trials=filter_trials,
)
# fig_sm_exp_trialwise_observables(
# pd_folder=pd_folder,
# out_prefix=out_prefix,
# )
def fig_3_snapshots(k_in=30):
def path(k, rate, rep):
# we additonally sampled a few simulations at higher time resolution. this gives
# higher precision for the resource variable, but takes tons of disk space.
path = f"{p_sim}/lif/raw/highres_"
path += f"stim=02_k={k:d}_kin={k_in:d}_jA=45.0_jG=50.0_jM=15.0_tD=20.0_rate=80.0_"
path += f"stimrate={rate:.1f}_rep={rep:03d}.hdf5"
return path
for sdx, stim in enumerate([0, 20]):
h5f = ph.ah.prepare_file(path(k=3, rate=stim, rep=1))
log.info("Using file: %s", path(k=3, rate=stim, rep=1))
fig, ax = plt.subplots()
ph.plot_raster(
h5f,
ax,
clip_on=True,
zorder=-2,
markersize=0.75,
alpha=0.5,
color="#333",
)
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(180))
ax.xaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(60))
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
sns.despine(ax=ax, left=True, right=True, bottom=True, top=True)
ax.set_xlim(0, 180)
cc.set_size(ax, 2.7, 0.9, l=0.1, t=0.1, r=0.1, b=0.1)
fig.savefig(f"{p_fo}/sim_raster_bw_stim_02_{stim}Hz.pdf", dpi=900)
def fig_3_violins(pd_path, out_prefix, out_suffix="", combine_panels=False):
"""
Wrapper for Figure 3 on Simulations containing
- pooled Violins that aggregate the results of all trials for
* Event size and Correlation Coefficient
* at 0Hz vs 20Hz additional stimulation in targeted modules (on top of 80Hz baseline)
- Decomposition plots (scatter and bar) anaologous to Figure 2
optionally creates a figure with multiple panels, instead of indiviaul panels
# Parameters:
pd_path : str
path to datafile, produced by `process_conditions.py`
e.g. f"{pp.p_sim}/lif/processed/k=5.hdf5"
out_prefix : str
prefix for output files, use this to set the ouputfolder
e.g. f"{p_fo}/sim_f3_"
out_suffix : str
suffix for output files, added before `.pdf`
combine_panels : bool
if True, creates a single figure with multiple panels
"""
# set the global seed once for each figure to produce consistent results, when
# calling repeatedly.
# many panels rely on bootstrapping and drawing random samples
np.random.seed(813)
trial = None
# trial = "005"
# rij_stats_for = "007"
# rij_stats_for = "pooled"
rij_stats_for = "ensemble"
dfs = load_pd_hdf5(pd_path, ["bursts", "rij", "rij_paired", "mod_rij_paired"])
# experimental were 3.0 x 2.0, but had 3 violins
col_width = 2.2 # cm
row_height = 1.5 # cm
num_panels = 6
if combine_panels:
fig, axes = plt.subplots(ncols=1, nrows=num_panels, figsize=(2, num_panels * 1.5))
else:
axes = [plt.subplots()[1] for _ in range(num_panels)]
def apply_formatting(ax, ylim=True, trim=True):
_noclip(ax)
if ylim:
ax.set_ylim(0, 1)
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.5))
ax.yaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(0.1))
ax.tick_params(bottom=False)
ax.set_xlabel(f"")
ax.set_ylabel(f"")
ax.set_xticklabels([])
if not combine_panels:
# set violin size
cc.set_size(ax, col_width, row_height, l=1.5, b=0.5, t=0.5)
sns.despine(ax=ax, bottom=True, left=False, trim=trim, offset=2)
# ------------------------------------------------------------------------------ #
# violins
# ------------------------------------------------------------------------------ #
log.debug("violins for simulation with two targeted modules")
ax = axes[0]
ax = custom_violins(
dfs["bursts"],
category="Condition",
observable="Fraction",
ylim=[0, 1],
num_swarm_points=300,
bw=0.2,
palette=colors["partial"],
ax=ax,
trial=trial,
)
apply_formatting(ax)
ax.set_ylabel("Event size" if show_ylabel else "")
ax = axes[1]
ax = custom_violins(
dfs["rij"],
category="Condition",
observable="Correlation Coefficient",
ylim=[0, 1],
num_swarm_points=600,
bw=0.2,
palette=colors["partial"],
ax=ax,
trial=trial,
)
apply_formatting(ax)
ax.set_ylabel("Correlation" if show_ylabel else "")
ax = axes[2]
ax = custom_violins(
dfs["bursts"],
category="Condition",
observable="Inter-burst-interval",
ylim=[0, 70],
num_swarm_points=300,
bw=0.2,
palette=colors["partial"],
ax=ax,
trial=trial,
)
apply_formatting(ax, ylim=False)
ax.set_ylabel("IBI" if show_ylabel else "")
ax.set_ylim(0, 70)
# ------------------------------------------------------------------------------ #
# pairwise rij plots
# ------------------------------------------------------------------------------ #
log.debug("barplot rij paired for simulations")
df = dfs["rij_paired"]
ax = axes[3]
ax = custom_rij_barplot(
df, conditions=["0.0 Hz", "20.0 Hz"], recolor=True, ax=ax, stats_for=rij_stats_for
)
ax.set_ylim(0, 1)
ax.set_ylabel("Median Neuron correlation" if show_ylabel else "")
ax.set_xlabel("Pairing" if show_xlabel else "")
ax.grid(axis="y", which="both", color="0.8", lw=0.5, zorder=-1, clip_on=False)
df = dfs["mod_rij_paired"]
ax = axes[4]
ax = custom_rij_barplot(
dfs["mod_rij_paired"],
conditions=["0.0 Hz", "20.0 Hz"],
recolor=True,
ax=ax,
stats_for=rij_stats_for,
)
ax.set_ylim(0, 1)
ax.set_ylabel("Median Module correlation" if show_ylabel else "")
ax.set_xlabel("Pairing" if show_xlabel else "")
ax.grid(axis="y", which="both", color="0.8", lw=0.5, zorder=-1, clip_on=False)
df = dfs["rij_paired"]
if trial is not None:
df = df.query(f"Trial == '{trial}'")
log.debug("scattered 2d rij paired for simulations")
ax = axes[5]
ax = custom_rij_scatter(
df,
max_sample_size=2500,
scatter=True,
kde_levels=[0.9, 0.95, 0.975],
solid_alpha=0.4,
ax=ax,
)
ax.set_xlabel("$r_{ij}$ pre")
ax.set_ylabel("$r_{ij}$ stim")
# ------------------------------------------------------------------------------ #
# saving
# ------------------------------------------------------------------------------ #
osx = out_suffix
opx = out_prefix
if combine_panels:
fig = ax.get_figure()
fig.tight_layout()
fig.savefig(f"{opx}combined{osx}.pdf", dpi=300)
else:
axes[0].get_figure().savefig(f"{opx}violins_event_size{osx}.pdf", dpi=300)
axes[1].get_figure().savefig(f"{opx}violins_neuron_rij{osx}.pdf", dpi=300)
axes[2].get_figure().savefig(f"{opx}violins_ibi{osx}.pdf", dpi=300)
cc.set_size(axes[3], col_width, row_height, b=1.0, l=1.0)
cc.set_size(axes[4], col_width, row_height, b=1.0, l=1.0)
axes[3].get_figure().savefig(f"{opx}barplot_neuron_rij{osx}.pdf", dpi=300)
axes[4].get_figure().savefig(f"{opx}barplot_module_rij{osx}.pdf", dpi=300)
cc.set_size(axes[5], row_height, row_height, b=1.0, l=1.0)
axes[5].get_figure().savefig(f"{opx}scatter_neuron_rij{osx}.pdf", dpi=300)
def fig_3_observables_for_different_k(
pd_path=None, x_dim=None, out_prefix=None, iter_coords=None
):
"""
Wrapper to create stick plots for simulations.
In the manuscript, we plot different observables as a function of `k_inter` and
color the bars according to conditions:
- For correlations
- both modules/neurons are targeted (yellow)
- none of the two are targeted (blue)
- or one is targeted, one is not (red)
- For other observables (but also including correlations) we alternative split
simply by "under stimulation" (orange) vs "no stimulation" (purple)
# Parameters
pd_path: str
datafile to use, produced by `ana/ndim_merge.py`
e.g. `f"{pp.p_sim}/lif/processed/ndim.hdf5"`
x_dim: str
"k_inter" (or "stim_rate", for fig S5)
iter_coords : None or dict
needs to have one key - the one str not used as x_dim,
and a list of values to iterate over for that (orhtogonal) dim
out_prefix: str
recommended is f"{p_fo}/sim_f3_"
"""
if out_prefix is None:
opx = f"{p_fo}/sim_f4_"
else:
opx = out_prefix
if pd_path is None:
pd_path = f"{p_sim}/lif/processed/ndim.hdf5"
if x_dim is None:
x_dim = "k_inter"
# for the things not becoming the x-axis, what to iterate over
# only affects the line part (ie. NOT which sticks to show when x_dim = "k_inter")
if iter_coords is None:
iter_coords = dict()
iter_coords["stim_rate"] = [0, 20]
# this went to the SI
iter_coords["k_inter"] = [0, 1, 3, 5, 10]
# for a reviewer answer, comparing merged and k=0
# iter_coords["k_inter"] = [0, -1]
col_width = 2.7
row_height = 1.5
dx = 0.18
# spacing between within-category markers, categories are spaced by 1
coords = reference_coordinates.copy()
coords["k_in"] = 30
coords["stim_mods"] = "02"
# this stuff goes on the x-axis
# cant pass everythign via args, adapt as needed
if x_dim == "k_inter":
kind = "cat"
coords["k_inter"] = [0, 1, 3, 5, 10]
coords["stim_rate"] = [0.0]
elif x_dim == "stim_rate":
coords["k_inter"] = [3]
kind = "line"
# ------------------------------------------------------------------------------ #
# correlations by module pairs
# ------------------------------------------------------------------------------ #
observables = [
# these are module correlations
# "mod_median_correlation_across",
# "mod_median_correlation_within_stim",
# "mod_median_correlation_within_nonstim",
#
# and these are neuron correlations. naming developed over time, sorry.
"sys_median_correlation_within_stim",
"sys_median_correlation_across",
"sys_median_correlation_within_nonstim",
]
if x_dim == "k_inter":
for sdx, stim in enumerate([0.0, 20.0]):
coords = coords.copy()
coords["stim_rate"] = stim
ax = None
for odx, obs in enumerate(observables):
base_color = colors["rij_all"]
if "within_stim" in obs:
base_color = colors["rij_within_stim"]
elif "within_nonstim" in obs:
base_color = colors["rij_within_nonstim"]
elif "across" in obs:
base_color = colors["rij_across"]
if stim == 0.0:
base_color = cc.alpha_to_solid_on_bg(base_color, 0.3)
ax = sim_plot_obs_from_ndim(
pd_path,
coords=coords,
x_dim=x_dim,
kind=kind,
observable=obs,
x_shift=odx * dx - (len(observables) - 1) / 2 * dx,
color=base_color,
ax=ax,
zorder=3 + 3 * odx,
# tried to code it, failed and eyeballed it
grid_dashes=(27.1, 4),
)
ax.set_xlim(-0.45, 4.5)
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.5))
ax.yaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(0.1))
ax.set_ylim(0, 1.0)
if obs[0:4] == "mod_":
ax.set_ylabel("Module correlation" if show_ylabel else "")
elif obs[0:4] == "sys_":
ax.set_ylabel("Neuron correlation" if show_ylabel else "")
cc.set_size(ax, w=col_width, h=row_height, b=1.0, l=1.2, t=0.5, r=0.2)
ax.get_figure().savefig(f"{opx}rij_{stim:.0f}_vs_{x_dim}.pdf", dpi=300)
# ------------------------------------------------------------------------------ #
# correlations by module pairs, in a wider panel, grouped by condition.
# ------------------------------------------------------------------------------ #
ax = None
for sdx, stim in enumerate([0.0, 20.0]):
for odx, obs in enumerate(observables):
num_s = 2
num_o = len(observables)
base_color = colors["rij_all"]
if "within_stim" in obs:
base_color = colors["rij_within_stim"]
elif "within_nonstim" in obs:
base_color = colors["rij_within_nonstim"]
elif "across" in obs:
base_color = colors["rij_across"]
if stim == 0.0:
base_color = cc.alpha_to_solid_on_bg(base_color, 0.3)
# dx = 0.18
dxo = 0.25
dxs = 0.09
x_shift = 0
x_shift += (sdx - 0.5) * dxs
x_shift += (odx - (num_o - 1) / 2) * dxo
coords = coords.copy()
coords["stim_rate"] = stim
ax = sim_plot_obs_from_ndim(
pd_path,
coords=coords,
x_dim=x_dim,
kind=kind,
observable=obs,
x_shift=x_shift,
color=base_color,
ax=ax,
zorder=3 + 3 * odx,
grid_dashes=(73, 4),
)
ax.set_xticklabels([f"k={k:d}" for k in [0, 1, 3, 5, 10]])
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.5))
ax.yaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(0.1))
ax.set_ylim(0, 1.0)
if obs[0:4] == "mod_":
ax.set_ylabel("Module correlation" if show_ylabel else "")
elif obs[0:4] == "sys_":
ax.set_ylabel("Neuron correlation" if show_ylabel else "")
cc.set_size(ax, w=col_width * 2.5, h=row_height, b=1.0, l=1.2, t=0.5, r=0.2)
ax.get_figure().savefig(f"{opx}rij_prevstrim_vs_{x_dim}.pdf", dpi=300)
# ------------------------------------------------------------------------------ #
# Differences between module correlations pre and stim
# ------------------------------------------------------------------------------ #
diff_coords = coords.copy()
coords["stim_rate"] = 20.0
diff_coords["stim_rate"] = 0.0
ax = None
for odx, obs in enumerate(observables):
base_color = colors["rij_all"]
if "within_stim" in obs:
base_color = colors["rij_within_stim"]
elif "within_nonstim" in obs:
base_color = colors["rij_within_nonstim"]
elif "across" in obs:
base_color = colors["rij_across"]
# base_color = cc.alpha_to_solid_on_bg(base_color, 0.8)
ax = sim_plot_obs_from_ndim(
pd_path,
coords=coords,
diff_coords=diff_coords,
x_dim=x_dim,
x_shift=odx * dx - (len(observables) - 1) / 2 * dx,
kind=kind,
observable=obs,
color=base_color,
ax=ax,
zorder=3 + odx,
clip_on=False,
grid_dashes=(27.1, 4),
)
ax.set_xlim(-0.45, 4.5)
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.5))
ax.yaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(0.1))
ax.set_ylim(-1, 0.0)
ax.set_ylabel(r"Correlation change" if show_ylabel else "")
cc.set_size(ax, w=col_width, h=row_height, b=1.0, l=1.2, t=0.5, r=0.2)
ax.get_figure().savefig(f"{opx}rij_change_vs_{x_dim}.pdf", dpi=300)
# ------------------------------------------------------------------------------ #
# our other observables
# ------------------------------------------------------------------------------ #
observables = [
"sys_median_correlation_within_stim",
"sys_mean_rate",
"sys_median_participating_fraction",
# "sys_mean_participating_fraction",
# "sys_mean_correlation",
"sys_functional_complexity",
# "mod_mean_correlation",
"sys_median_correlation",
"any_num_spikes_in_bursts",
# "sys_median_any_ibis",
"sys_mean_any_ibis",
# testing order parameters
# "sys_orderpar_fano_neuron",
# "sys_orderpar_fano_population",
# "sys_orderpar_baseline_neuron",
# "sys_orderpar_baseline_population",
"sys_mean_core_delay",
"sys_mean_resources_at_burst_beg",
"sys_modularity",
]
for odx, obs in enumerate(observables):
# ax = None
fig, ax = plt.subplots()
if x_dim == "k_inter":
iter_dim = "stim_rate"
elif x_dim == "stim_rate" or x_dim == "rate":
iter_dim = "k_inter"
iters = iter_coords[iter_dim]
for idx, itel in enumerate(iters):
coords[iter_dim] = itel
if kind == "cat":
x_shift = (idx * dx - (len(iters) - 1) / 2 * dx,)
errortype = "percentile"
estimator = "median"
else:
x_shift = 0
errortype = "sem"
estimator = "mean"
# default color
color = cc.alpha_to_solid_on_bg("#333", cc.fade(idx, len(iters), invert=True))
# but for pre vs stim at 0 vs 20 Hz we have presets
if iter_dim == "stim_rate":
if itel == 0:
color = colors["pre"]
color = cc.alpha_to_solid_on_bg(color, 0.8)
elif itel == 20:
color = colors["stim"]
ax = sim_plot_obs_from_ndim(
pd_path,
coords=coords,
x_dim=x_dim,
kind=kind,
x_shift=x_shift,
observable=obs,
estimator=estimator,
errortype=errortype,
color=color,
zorder=3 + idx,
label=f"{itel}",
ax=ax,
grid_dashes=(27.1, 4) if kind == "cat" else None,
)
if kind == "cat":
ax.set_xlim(-0.45, 4.5)
# if show_legend:
# ax.legend()
ax.set_ylim(*_lif_lims(obs))
ax.set_ylabel(_lif_labels(obs) if show_ylabel else "")
if _lif_lims(obs)[1] == 1:
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.5))
ax.yaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(0.1))
if obs == "sys_mean_any_ibis":
ax.set_ylim(0, 30)
if x_dim == "stim_rate":
ax.set_xlabel("Stimulation rate (Hz)" if show_xlabel else "")
# sns.despine(ax=ax, offset=3)
cc.set_size(ax, w=col_width, h=row_height, b=1.0, l=1.2, t=0.5, r=0.2)
ax.get_figure().savefig(f"{opx}{obs}_vs_{x_dim}.pdf", dpi=300)
def fig_4_snapshots(
k_in=30, do_rasters=True, do_cycles=True, do_topo=True, out_prefix=None
):
"""
Wrapper to create the snapshots of LIF simulations in Figure 4 and the SM.
- example raster plots
* A sketch of the topology
* Population-level rates in Hz (top)
* Raster, color coded by module
* Module-level synaptic resources available (bottom)
* A zoomin of the raster of a single bursting event (right)
Sorted by
- the number of connections between modules (k)
- and the "Synaptic Noise Rate" - a Poisson input provided to all neurons.
- charge-discharge cycles for the examples in the raster plots.
"""
# ------------------------------------------------------------------------------ #
# raster plots
# ------------------------------------------------------------------------------ #
if out_prefix is None:
opx = f"{p_fo}/sim_f4_lif_"
else:
opx = out_prefix
def path(k, rate, rep):
# we additonally sampled a few simulations at higher time resolution. this gives
# higher precision for the resource variable, but takes tons of disk space.
path = f"{p_sim}/lif/raw/highres_"
path += f"stim=02_k={k:d}_kin={k_in:d}_jA=45.0_jG=50.0_jM=15.0_tD=20.0_rate=80.0_"
path += f"stimrate={rate:.1f}_rep={rep:03d}.hdf5"
return path
coords = []
times = [] # start time for the large time window of ~ 180 seconds
zooms = [] # start time for an interesting 250 ms time window showing a burst
coords.append(dict(k=0, rate=0, rep=0))
zooms.append(162.7)
times.append(0)
coords.append(dict(k=0, rate=20, rep=0))
zooms.append(160.55)
times.append(0)
coords.append(dict(k=1, rate=0, rep=1))
zooms.append(171.83)
times.append(0)
coords.append(dict(k=1, rate=20, rep=1))
zooms.append(171.83)
times.append(0)
coords.append(dict(k=3, rate=0, rep=1))
zooms.append(166.50)
times.append(0)
coords.append(dict(k=3, rate=20, rep=1))
zooms.append(166.51)
times.append(0)
coords.append(dict(k=5, rate=0, rep=0))
zooms.append(162.77)
times.append(0)
coords.append(dict(k=5, rate=20, rep=0))
zooms.append(162.77)
times.append(0)
coords.append(dict(k=10, rate=0, rep=0))
zooms.append(141.5)
times.append(0)
coords.append(dict(k=10, rate=20, rep=0))
zooms.append(170.475)
times.append(0)
# coords.append(dict(k=-1, rate=0, rep=1))
# zooms.append(143.2)
# times.append(0)
# coords.append(dict(k=-1, rate=20, rep=1))
# zooms.append(146.95)
# times.append(0)
for idx in range(0, len(coords)):
if not do_rasters:
break
cs = coords[idx]
if not os.path.exists(path(**cs)):
log.info(f"File not found, skipping {path(**cs)}")
continue