-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathana_helper.py
3145 lines (2537 loc) · 103 KB
/
ana_helper.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-03-10 13:23:16
# @Last Modified: 2023-05-05 14:05:08
# ------------------------------------------------------------------------------ #
# Here we collect all functions for importing and analyzing the data.
# A central idea is that for every simulated/experimental trial, we have a
# nested dictionary (a benedict) that is named `h5f` (because it reflects
# an initially loaded hdf5 file).
# We then step-by-step keep adding details to this dictionary: Many analysis
# functions directly add into it, and we have a helper that can save such a
# structure to disk.
# This way, plot functions etc. can rely on the structure of the dictionary,
# and we only have to pass a single argument to later functions.
# ------------------------------------------------------------------------------ #
import os
import sys
import glob
import h5py
import re
import tempfile
import numbers
import numpy as np
import pandas as pd
import networkx as nx
from bitsandbobs import hi5 as h5
from benedict import benedict
from tqdm import tqdm
from itertools import permutations
import logging
import warnings
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
try:
from numba import jit, prange
# raise ImportError
# let's not print this 256 times on import when using 256 threads :P
# log.info("Using numba for parallelizable functions")
try:
from numba.typed import List
except:
# older numba versions dont have this
def List(*args):
return list(*args)
# silence deprications
try:
from numba.core.errors import (
NumbaDeprecationWarning,
NumbaPendingDeprecationWarning,
)
warnings.simplefilter("ignore", category=NumbaDeprecationWarning)
warnings.simplefilter("ignore", category=NumbaPendingDeprecationWarning)
except:
pass
except ImportError:
log.info("Numba not available, skipping compilation")
# replace numba functions if numba not available:
# we only use jit and prange
# helper needed for decorators with kwargs
def parametrized(dec):
def layer(*args, **kwargs):
def repl(f):
return dec(f, *args, **kwargs)
return repl
return layer
@parametrized
def jit(func, **kwargs):
return func
def prange(*args):
return range(*args)
def List(*args):
return list(*args)
# ------------------------------------------------------------------------------ #
# high level functions
# ------------------------------------------------------------------------------ #
def prepare_file(
h5f,
mod_colors="auto",
hot=True,
skip=None,
):
"""
modifies h5f in place! (not on disk, only in RAM)
# Parameters
h5f : file path as str or existing h5f benedict
mod_colors : "auto" or False (all back) or list of colors
hot : wether to load data to ram (true) or fetch as needed (false)
skip : lists of names of datasets of the h5file that are excluded,
if `h5f` is a path
# adds the following attributes:
h5f["ana.mod_sort"] : function that maps from neuron_id to sorted id, by module
h5f["ana.mods"] : list of unique module ids
h5f["ana.mod_colors"] : list of colors associated with each module
h5f["ana.neuron_ids"] : array of neurons, if we speciefied a sensor, this will
only contain the recorded ones.
"""
log.debug("Preparing File:")
log.debug(f"{h5f}")
if isinstance(h5f, str):
h5f = h5.recursive_load(h5f, hot=hot, skip=skip, dtype=benedict)
h5f["ana"] = benedict()
num_n = h5f["meta.topology_num_neur"]
# if we had a sensor, many neurons were not recorded and cannot be analyzed.
if "meta.topology_n_within_sensor" in h5f.keypaths():
num_n = h5f["meta.topology_n_within_sensor"]
# ------------------------------------------------------------------------------ #
# mod sorting
# ------------------------------------------------------------------------------ #
try:
# get the neurons sorted according to their modules
mod_sorted = np.zeros(num_n, dtype=int)
mod_ids = h5f["data.neuron_module_id"][:]
mods = np.sort(np.unique(mod_ids))
if len(mods) == 1:
log.debug("Only one module, no sorting needed")
raise NotImplementedError # avoid resorting.
temp = np.argsort(mod_ids)
for n_id in range(0, num_n):
mod_sorted[n_id] = np.argwhere(temp == n_id)
h5f["ana.mods"] = [f"mod_{m}" for m in mods]
h5f["ana.mod_ids"] = mods
h5f["ana.mod_sort"] = lambda x: mod_sorted[x]
except Exception as e:
log.debug(e)
h5f["ana.mods"] = ["mod_0"]
h5f["ana.mod_ids"] = [0]
h5f["ana.mod_sort"] = lambda x: x
# ------------------------------------------------------------------------------ #
# assign colors to modules so we can use them in every plot consistently
# ------------------------------------------------------------------------------ #
if mod_colors is False:
h5f["ana.mod_colors"] = ["black"] * len(h5f["ana.mods"])
elif mod_colors == "auto":
h5f["ana.mod_colors"] = [f"C{x}" for x in range(0, len(h5f["ana.mods"]))]
else:
assert isinstance(mod_colors, list)
assert len(mod_colors) >= len(h5f["ana.mods"])
h5f["ana.mod_colors"] = mod_colors[: len(h5f["ana.mods"])]
# ------------------------------------------------------------------------------ #
# spikes
# ------------------------------------------------------------------------------ #
# maybe change this to exclude neurons that did not spike
# neuron_ids = np.unique(spikes[:, 0]).astype(int, copy=False)
neuron_ids = np.arange(0, num_n, dtype=int)
h5f["ana.neuron_ids"] = neuron_ids
# make sure that the 2d_spikes representation is nan-padded, requires loading!
spikes = h5f["data.spiketimes"][:]
if spikes is None:
log.warning("No spikes in file, plotting and analysing dynamics won't work.")
elif np.any(np.isnan(spikes)):
log.debug("spikes seem to be nan-padded, no conversion needed.")
else:
# make sure the format matches
# from simulations, I had a hard time padding with nans in the hdf5 files.
# but needs a workaround, because in rare cases, we might have 0 as a real spike time.
# in essence, this is what we want to do, but it is not as robust:
# spikes[spikes == 0] = np.nan
try:
# new approach: what we expect is that spiketimes always increase,
# until they are padded. detect padding by looking for non-increasing values.
diff = np.diff(spikes, axis=1) < 0
# use scipy label to find consecutive patches, has to be done for each neuron,
# otherwise it connects patches across neurons.
from scipy.ndimage import label
for n_id in range(0, num_n):
patches, _ = label(diff[n_id, :])
_, change_pt_indices = np.unique(patches, return_index=True)
if len(change_pt_indices) == 1:
if spikes[n_id, 0] == 0:
# edge-case, everything zero
spikes[n_id, :] = np.nan
else:
# all consecutive, and non-zero all good
continue
elif len(change_pt_indices) == 2:
# second half needs padding
spikes[n_id, change_pt_indices[1] + 1 :] = np.nan
elif len(change_pt_indices) > 2:
# this should not happen
log.error(
f"More than two change points found for spikes of neuron {n_id}"
)
raise ValueError
h5f["data.spiketimes"] = spikes
except Exception as e:
log.error(e)
log.warning(
"Spike conversion failed, plotting and analysing dynamics won't work."
)
# # now we need to load things. [:] loads to ram and makes everything else faster
# # convert spikes in the convenient nested (2d) format, first dim neuron,
# # then ndarrays of time stamps in seconds
# spikes = h5f["data.spiketimes_as_list"][:]
# spikes_2d = []
# for n_id in neuron_ids:
# idx = np.where(spikes[:, 0] == n_id)[0]
# spikes_2d.append(spikes[idx, 1])
# # the outer array is essentially a list but with fancy indexing.
# # this is a bit counter-intuitive
# h5f["ana.spikes_2d"] = np.array(spikes_2d, dtype=object)
# Stimulation description
stim_str = "Unknown"
if not "data.stimulation_times_as_list" in h5f.keypaths():
stim_str = "Off"
else:
try:
stim_neurons = np.unique(h5f["data.stimulation_times_as_list"][:, 0]).astype(
int
)
stim_mods = np.unique(h5f["data.neuron_module_id"][stim_neurons])
stim_str = f"On {str(tuple(stim_mods)).replace(',)', ')')}"
except Exception as e:
log.warning(e)
stim_str = f"Error"
h5f["ana.stimulation_description"] = stim_str
# Guess the repetition from filename, convention: `foo/bar_parameters_rep=09.hdf5`
try:
fname = str(h5f["uname.original_file_path"].decode("UTF-8"))
rep = re.search("(?<=rep=)(\d+)", fname)[0] # we only use the first match
h5f["ana.repetition"] = int(rep)
except Exception as e:
log.debug(e)
h5f["ana.repetition"] = -1
return h5f
def load_experimental_files(path_prefix, condition="1_pre_"):
"""
helper to import experimental csv files from jordi into a compatible
h5f
# Parameters
path_prefix: str
condition: str
# Returns
h5f: benedict with our needed strucuter
"""
# assert os.path.isdir(path_prefix)
h5f = benedict()
# Load spike times
# in this format, we have a 50 ms timestep, the column is the neuron id
# and the row is whether a neuron fired in this time step.
spikes_as_sparse = np.loadtxt(
f"{path_prefix}{condition}/Raster.csv", delimiter=",", skiprows=0
)
# ROIs as neuron centers
try:
rois = np.loadtxt(
f"{path_prefix}/RoiSet_Cartesian.txt", delimiter=",", skiprows=1
)
h5f["data.neuron_pos_x"] = rois[:, 1].copy()
h5f["data.neuron_pos_y"] = rois[:, 2].copy()
except Exception as e:
log.error(e)
log.warning(f"No ROIs found, setting all neuron position to 100um / 100 um!")
num_n = spikes_as_sparse.shape[1]
h5f["data.neuron_pos_x"] = np.ones(num_n) * 100.0
h5f["data.neuron_pos_y"] = np.ones(num_n) * 100.0
# add some more stuff that is usually already in the meta data
num_n = len(h5f["data.neuron_pos_x"])
h5f["meta.topology_num_neur"] = num_n
# drop first 60 seconds due to artifacts at the beginning of the recording
spikes_as_sparse = spikes_as_sparse[1200:, :]
spikes_as_list = _spikes_as_sparse_to_spikes_as_list(spikes_as_sparse, dt=50 / 1000)
h5f["data.spiketimes_as_list"] = spikes_as_list
h5f["data.spiketimes"] = _spikes_as_list_to_spikes_2d(spikes_as_list, num_n=num_n)
# approximate module ids from position
# 0 lower left, 1 upper left, 2 lower right, 3 upper right
h5f["data.neuron_module_id"] = np.ones(num_n, dtype=int) * -1
if "merged" in path_prefix:
lim = 200
else:
lim = 300
for nid in range(0, num_n):
x = h5f["data.neuron_pos_x"][nid]
y = h5f["data.neuron_pos_y"][nid]
if x < lim and y < lim:
h5f["data.neuron_module_id"][nid] = 0
elif x < lim and y >= lim:
h5f["data.neuron_module_id"][nid] = 1
elif x >= lim and y < lim:
h5f["data.neuron_module_id"][nid] = 2
elif x >= lim and y >= lim:
h5f["data.neuron_module_id"][nid] = 3
h5f["meta.dynamics_simulation_duration"] = 540.0
try:
# fluorescence traces
fl_traces = np.loadtxt(
f"{path_prefix}{condition}/Results.csv", delimiter=",", skiprows=1
)
# for each neuron, we have 4 columns, and want to use the 2nd one, "mean"
# first col is time index, then we start counting neurons
fl_idx = np.arange(0, num_n, dtype="int") * 4 + 2
fl_traces = fl_traces[:, fl_idx]
# drop first 60 seconds due to artifacts at the beginning of the recording
fl_traces = fl_traces[1200:, :]
h5f["data.neuron_fluorescence_trace"] = fl_traces.copy().T
h5f["data.neuron_fluorescence_timestep"] = 50 / 1000
# h5f["pd.fl"] = pd.read_csv(f"{path_prefix}{condition}/Results.csv")
except Exception as e:
log.error(f"No fluorescence data found for {path_prefix} {condition}")
# log.exception(e)
# default preprocessing
h5f = prepare_file(h5f)
# overwrite some details
# we overwrite the stimulation description, maybe even as an potional argument
return h5f
def prepare_minimal(spikes):
"""
Wrapper to create the bare minimum of needed attributes from an array of spiketimes.
For now assuming the 2d nan-padded format.
# Example
```
ph.overview_dynamic(ah.prepare_minimal(foo))
```
"""
h5f = benedict()
num_n = spikes.shape[0]
h5f["meta.topology_num_neur"] = num_n
h5f["data.spiketimes"] = spikes
h5f["data.neuron_module_id"] = np.zeros(num_n, dtype=int)
prepare_file(h5f)
return h5f
def nx_graph_from_connectivity_matrix(h5f):
"""
use the sparse connectivity matrix of the h5f and construct a directed graph in the
networkx format.
The graph gets saved to `'ana.networkx.G'`
"""
# add nodes, generate positions in usable format
G = nx.DiGraph()
G.add_nodes_from(h5f["ana.neuron_ids"])
pos = dict()
for idx, n in enumerate(h5f["ana.neuron_ids"]):
pos[n] = (
h5f["data.neuron_pos_x"][idx],
h5f["data.neuron_pos_y"][idx],
)
# add edges
try:
# for large data, we might not have loaded the matrix.
G.add_edges_from(h5f["data.connectivity_matrix_sparse"][:])
except Exception as e:
log.warning(
"Could not set Graph edges because connectivity matrix was not loaded."
)
# communities according to modules
communities = []
for mod_id in h5f["ana.mod_ids"]:
communities.append(
np.where(h5f["data.neuron_module_id"][:] == mod_id)[0].tolist()
)
# add to h5f
h5f["ana.networkx.G"] = G
h5f["ana.networkx.pos"] = pos
h5f["ana.networkx.communities"] = communities
# depricating, do this more explicitly
def __find_bursts_from_rates(
h5f,
rate_threshold=None, # default 7.5 Hz
merge_threshold=0.1, # seconds, merge bursts if separated by less than this
system_bursts_from_modules=True,
write_to_h5f=True,
return_res=False,
):
"""
Based on module-level firing rates, find bursting events.
returns two benedicts, `bursts` and `rates`,
modifies `h5f`
# Parameters
h5f : benedict, with our usual structure
bs_large : float, seconds, time bin size to smooth over (gaussian kernel)
bs_small : float, seconds, small bin size at which the rate is sampled
rate_threshold : float, Hz, above which we start detecting bursts
merge_threshold : float, seconds merge bursts if separated by less than this
system_bursts_from_modules : bool, whether the system-level bursts are
"stitched together" from individual modules or detected independently
from the system wide rate, using `rate_threshold`
Note on smoothing: previously, we time-binned the activity on the module level
and convolve this series with a gaussian kernel to smooth.
Current, precise way is to convolve the spike-train of each neuron with
the kernel (thus, keeping the high precision of each spike time).
"""
assert h5f["ana"] is not None, "`prepare_file(h5f)` first!"
assert write_to_h5f or return_res
if rate_threshold is None:
rate_threshold = 7.5
spikes = h5f["data.spiketimes"]
bursts = benedict()
rates = benedict()
rates["dt"] = bs_small
beg_times = [] # lists of length num_modules
end_times = []
try:
duration = h5f["meta.dynamics_simulation_duration"]
except KeyError:
duration = np.nanmax(h5f["data.spiketimes"]) + 15
for mdx, m_id in enumerate(h5f["ana.mod_ids"]):
# for keys, use readable description of the module
m_dc = h5f["ana.mods"][mdx]
selects = np.where(h5f["data.neuron_module_id"][:] == m_id)[0]
# if sensor is specified, we might get more neuron_module_id than were recorded
selects = selects[np.isin(selects, h5f["ana.neuron_ids"])]
pop_rate = population_rate_exact_smoothing(
spikes[selects],
bin_size=bs_small,
smooth_width=bs_large,
length=duration,
)
beg_time, end_time = burst_detection_pop_rate(
rate=pop_rate,
bin_size=bs_small,
rate_threshold=rate_threshold,
)
if len(beg_time) > 0:
beg_time, end_time = merge_if_below_separation_threshold(
beg_time, end_time, threshold=merge_threshold
)
beg_times.append(beg_time)
end_times.append(end_time)
rates[f"module_level.{m_dc}"] = pop_rate
rates[f"cv.module_level.{m_dc}"] = np.nanstd(pop_rate) / np.nanmean(pop_rate)
bursts[f"module_level.{m_dc}.beg_times"] = beg_time.copy()
bursts[f"module_level.{m_dc}.end_times"] = end_time.copy()
bursts[f"module_level.{m_dc}.rate_threshold"] = rate_threshold
pop_rate = population_rate_exact_smoothing(
spikes[:],
bin_size=bs_small,
smooth_width=bs_large,
length=duration,
)
rates["system_level"] = pop_rate
rates["cv.system_level"] = np.nanstd(pop_rate) / np.nanmean(pop_rate)
if system_bursts_from_modules:
sys_begs, sys_ends, sys_seqs = system_burst_from_module_burst(
beg_times,
end_times,
threshold=merge_threshold,
)
else:
sys_begs, sys_ends = burst_detection_pop_rate(
rate=pop_rate,
bin_size=bs_small,
rate_threshold=rate_threshold,
)
# in this case, we dont get sequences for free. lets check the first spike
# in each modules
sys_seqs = []
for idx in range(0, len(sys_begs)):
beg = sys_begs[idx]
end = sys_ends[idx]
firsts = np.ones(len(h5f["ana.mods"])) * np.nan
for mdx, m_id in enumerate(h5f["ana.mod_ids"]):
m_dc = h5f["ana.mods"][mdx]
selects = np.where(h5f["data.neuron_module_id"][:] == m_id)[0]
selects = selects[np.isin(selects, h5f["ana.neuron_ids"])]
s = spikes[selects]
s = s[(s >= beg) & (s <= end)]
if len(s) > 0:
firsts[mdx] = np.nanmin(s)
num_valid = len(firsts[np.isfinite(firsts)])
mdx_order = np.argsort(firsts)[0:num_valid]
seq = tuple(np.array(h5f["ana.mod_ids"])[mdx_order])
sys_seqs.append(seq)
bursts["system_level.beg_times"] = sys_begs.copy()
bursts["system_level.end_times"] = sys_ends.copy()
bursts["system_level.module_sequences"] = sys_seqs
if write_to_h5f:
# if isinstance(h5f["ana.bursts"], benedict):
# if isinstance(h5f["ana.rates"], benedict):
try:
h5f["ana.bursts"].clear()
except Exception as e:
log.debug(e)
try:
h5f["ana.rates"].clear()
except Exception as e:
log.debug(e)
# so, overwriting keys with dicts (nesting) can cause memory leaks.
# to avoid this, call .clear() before assigning the new dict
# testwise I made this the default for setting keys of benedict
h5f["ana.bursts"] = bursts
h5f["ana.rates"] = rates
if return_res:
return bursts, rates
def find_rates(
h5f,
bs_large=0.02, # seconds, time bin size to smooth over (gaussian kernel)
bs_small=0.0005, # seconds, small bin size
write_to_h5f=True,
return_res=False,
):
"""
Uses `population_rate_exact_smoothing` to find global system rate
and the rates within modules
Note on smoothing: previously, we time-binned the activity on the module level
and convolve this series with a gaussian kernel to smooth.
Current, precise way is to convolve the spike-train of each neuron with
the kernel (thus, keeping the high precision of each spike time).
"""
assert h5f["ana"] is not None, "`prepare_file(h5f)` first!"
assert write_to_h5f or return_res
spikes = h5f["data.spiketimes"]
rates = benedict()
rates["dt"] = bs_small
beg_times = [] # lists of length num_modules
end_times = []
try:
duration = h5f["meta.dynamics_simulation_duration"]
except KeyError:
duration = np.nanmax(h5f["data.spiketimes"]) + 15
for mdx, m_id in enumerate(h5f["ana.mod_ids"]):
m_dc = h5f["ana.mods"][mdx]
selects = np.where(h5f["data.neuron_module_id"][:] == m_id)[0]
selects = selects[np.isin(selects, h5f["ana.neuron_ids"])]
pop_rate = population_rate_exact_smoothing(
spikes[selects],
bin_size=bs_small,
smooth_width=bs_large,
length=duration,
)
rates[f"module_level.{m_dc}"] = pop_rate
rates[f"cv.module_level.{m_dc}"] = np.nanstd(pop_rate) / np.nanmean(pop_rate)
pop_rate = population_rate_exact_smoothing(
spikes[:],
bin_size=bs_small,
smooth_width=bs_large,
length=duration,
)
rates["system_level"] = pop_rate
rates["cv.system_level"] = np.nanstd(pop_rate) / np.nanmean(pop_rate)
if write_to_h5f:
try:
h5f["ana.rates"].clear()
except Exception as e:
log.debug(e)
# so, overwriting keys with dicts (nesting) can cause memory leaks.
# to avoid this, call .clear() before assigning the new dict
# testwise I made this the default for setting keys of benedict
h5f["ana.rates"] = rates
if return_res:
return rates
def find_system_bursts_from_module_bursts(
h5f,
rate_threshold, # Hz
merge_threshold, # seconds, merge bursts if separated by less than this
write_to_h5f=True,
return_res=False,
):
"""
Based on module-level firing rates, find bursting events.
optionally returns `bursts`
optionally modifies `h5f`
# Parameters
h5f : benedict, with our usual structure
rate_threshold : float in Hz, above which we start detecting bursts
merge_threshold : float, seconds merge bursts if separated by less than this
# Adds to h5f if `write_to_h5f`:
h5f["ana.bursts.module_level.{m_dc}.beg_times"]
h5f["ana.bursts.module_level.{m_dc}.end_times"]
h5f["ana.bursts.module_level.{m_dc}.rate_threshold"]
h5f["ana.system_level.beg_times"]
h5f["ana.system_level.end_times"]
h5f["ana.system_level.module_sequences"]
"""
rate_dt = h5f["ana.rates.dt"]
bursts = benedict()
beg_times = []
end_times = []
for mdx, m_id in enumerate(h5f["ana.mod_ids"]):
m_dc = h5f["ana.mods"][mdx]
rate = h5f[f"ana.rates.module_level.{m_dc}"]
beg_time, end_time = burst_detection_pop_rate(
rate=rate,
bin_size=rate_dt,
rate_threshold=rate_threshold,
)
beg_time, end_time = merge_if_below_separation_threshold(
beg_time, end_time, threshold=merge_threshold
)
beg_times.append(beg_time)
end_times.append(end_time)
bursts[f"module_level.{m_dc}.beg_times"] = beg_time.copy()
bursts[f"module_level.{m_dc}.end_times"] = end_time.copy()
bursts[f"module_level.{m_dc}.rate_threshold"] = rate_threshold
sys_begs, sys_ends, sys_seqs = system_burst_from_module_burst(
beg_times,
end_times,
threshold=merge_threshold,
)
bursts["system_level.beg_times"] = sys_begs.copy()
bursts["system_level.end_times"] = sys_ends.copy()
bursts["system_level.module_sequences"] = sys_seqs
bursts["system_level.algorithm"] = "from_module_bursts"
if write_to_h5f:
try:
h5f["ana.bursts"].clear()
except Exception as e:
log.debug(e)
h5f["ana.bursts"] = bursts
if return_res:
return bursts
def find_system_bursts_from_global_rate(
h5f,
rate_threshold, # Hz
merge_threshold, # seconds, merge bursts if separated by less than this
write_to_h5f=True,
return_res=False,
skip_sequences=False,
**sequence_kwargs,
):
"""
Find global bursting events only based on the merged down rate.
To get sequences, uses `sequences_from_module_contribution` and
passes `sequence_kwargs`.
Per default, to count a module as "contributing" to a sequence,
at least _20%_ of the neurons of the module (but at least one neuron) have to
contribute at least _1_ spike
optionally returns `bursts`
optionally modifies `h5f`
Note: does not provide the
h5f["ana.bursts.module_level.{m_dc}"]
# Parameters
h5f : benedict, with our usual structure
rate_threshold : float, Hz, above which we start detecting bursts
merge_threshold : float, seconds merge bursts if separated by less than this
# Adds to h5f if `write_to_h5f`:
h5f["ana.system_level.beg_times"]
h5f["ana.system_level.end_times"]
"""
bursts = benedict()
rate = h5f[f"ana.rates.system_level"]
rate_dt = h5f["ana.rates.dt"]
beg_times, end_times = burst_detection_pop_rate(
rate=rate,
bin_size=rate_dt,
rate_threshold=rate_threshold,
)
beg_times, end_times = merge_if_below_separation_threshold(
beg_times, end_times, threshold=merge_threshold
)
if skip_sequences:
sys_seqs = [tuple()] * len(beg_times)
else:
sequence_kwargs.setdefault("min_spikes", 1)
# 20% of a modules neurons
npm = h5f["meta.topology_num_neur"] / len(h5f["ana.mod_ids"])
min_neurons = np.nanmax([1, int(0.20 * npm)])
sequence_kwargs.setdefault("min_neurons", min_neurons)
sys_seqs = sequences_from_module_contribution(
h5f, beg_times, end_times, **sequence_kwargs
)
bursts["beg_times"] = beg_times.copy()
bursts["end_times"] = end_times.copy()
bursts["module_sequences"] = sys_seqs
bursts["rate_threshold"] = rate_threshold
bursts["algorithm"] = "from_global_rate"
if write_to_h5f:
try:
h5f["ana.bursts.system_level"].clear()
except Exception as e:
log.debug(e)
h5f["ana.bursts.system_level"] = bursts
if return_res:
return bursts
def find_isis(h5f, write_to_h5f=True, return_res=False):
"""
What are the the inter-spike-intervals within and out of bursts?
"""
assert write_to_h5f or return_res
isi = benedict()
for mdx, m_id in enumerate(h5f["ana.mod_ids"]):
m_dc = h5f["ana.mods"][mdx]
selects = np.where(h5f["data.neuron_module_id"][:] == m_id)[0]
selects = selects[np.isin(selects, h5f["ana.neuron_ids"])] # sensor
spikes_2d = h5f["data.spiketimes"][selects]
try:
b = h5f[f"ana.bursts.module_level.{m_dc}.beg_times"]
e = h5f[f"ana.bursts.module_level.{m_dc}.end_times"]
except:
if mdx == 0:
log.debug("Module bursts were not detected before searching ISI.")
b = None
e = None
ll_isi = _inter_spike_intervals(
spikes_2d,
beg_times=b,
end_times=e,
)
isi[m_dc] = ll_isi
if write_to_h5f:
h5f["ana.isi"] = isi
if return_res:
return isi
def find_ibis(h5f, write_to_h5f=True, return_res=False):
"""
What are the the inter-burst-intervals? End-of-burst to start-of-burst
"""
assert write_to_h5f or return_res
ibi = benedict()
# ibi["module_level"] = benedict()
# ibi["system_level"] = benedict()
l_ibi_across_mods = []
for mdx, m_id in enumerate(h5f["ana.mods"]):
m_dc = h5f["ana.mods"][mdx]
try:
b = np.array(h5f[f"ana.bursts.module_level.{m_dc}.beg_times"])
e = np.array(h5f[f"ana.bursts.module_level.{m_dc}.end_times"])
except Exception as e:
log.debug("Module-level bursts were not detected before searching IBI.")
break
# raise e
if len(b) < 2:
l_ibi = np.array([])
else:
l_ibi = b[1:] - e[:-1]
l_ibi = l_ibi.tolist()
ibi[f"module_level.{m_dc}"] = l_ibi
l_ibi_across_mods.extend(l_ibi)
# and again for system-wide, no matter how many modules involved
try:
b = np.array(h5f["ana.bursts.system_level.beg_times"])
e = np.array(h5f["ana.bursts.system_level.end_times"])
except Exception as e:
log.error("System-level bursts were not detected before searching IBI.")
raise e
if len(b) < 2:
l_ibi = np.array([])
else:
l_ibi = e[1:] - b[:-1]
ibi["system_level.any_module"] = l_ibi.tolist()
ibi["system_level.cv_any_module"] = np.nanstd(l_ibi) / np.nanmean(l_ibi)
ibi["system_level.cv_across_modules"] = np.nanstd(l_ibi_across_mods) / np.nanmean(
l_ibi_across_mods
)
# we are also interested in system-wide bursts that included all modules
try:
# l = np.vectorize(len)(h5f["ana.bursts.system_level.module_sequences"][1:])
# deprication warning -.-
slen = [len(seq) for seq in h5f["ana.bursts.system_level.module_sequences"]]
idx = np.where(np.array(slen) >= len(h5f["ana.mods"]))
b = b[idx]
e = e[idx]
if len(b) < 2:
l_ibi = np.array([])
else:
l_ibi = e[1:] - b[:-1]
ibi["system_level.all_modules"] = l_ibi.tolist()
ibi["system_level.cv_all_modules"] = np.nanstd(l_ibi) / np.nanmean(l_ibi)
except Exception as e:
log.info("Failed to find system-wide ibis (where all modules are involved)")
log.info(e)
if write_to_h5f:
try:
h5f["ana.ibi"].clear()
except:
pass
h5f["ana.ibi"] = ibi
if return_res:
return ibi
def find_participating_fraction_in_bursts(h5f, write_to_h5f=True, return_res=False):
"""
Once we have found bursts, check what is the fraction of neurons participating
in every burst, and the total number of spikes.
adds `participating_fraction` to the bursts: fraction of unique neurons fired
a spike in the burst (relative to total number of neurons in module / system)
adds `num_spikes_in_bursts`: how many spikes per contributing neuron
"""
assert "ana.bursts" in h5f.keypaths(), "run `find_bursts_from_rates` first"
assert write_to_h5f or return_res
spikes = h5f["data.spiketimes"]
bursts = h5f["ana.bursts"]
if not write_to_h5f:
bursts = bursts.clone()
for mdx, m_id in enumerate(h5f["ana.mod_ids"]):
m_dc = h5f["ana.mods"][mdx]
selects = np.where(h5f["data.neuron_module_id"][:] == m_id)[0]
selects = selects[np.isin(selects, h5f["ana.neuron_ids"])] # sensor
try:
bt = bursts[f"module_level.{m_dc}.beg_times"]
et = bursts[f"module_level.{m_dc}.end_times"]
except KeyError:
log.debug("No module bursts for participating fraction. Skipping")
break
fraction = np.zeros(len(bt))
num_spks = np.zeros(len(bt))
for bdx in range(0, len(bt)):
n_ids = np.where((bt[bdx] <= spikes[selects]) & (spikes[selects] <= et[bdx]))[
0
]
n_unk = len(np.unique(n_ids))
fraction[bdx] = n_unk / len(selects)
num_spks[bdx] = len(n_ids) / np.fmax(n_unk, 1)
bursts[f"module_level.{m_dc}.participating_fraction"] = fraction.tolist()
bursts[f"module_level.{m_dc}.num_spikes_in_bursts"] = num_spks.tolist()
# system level
selects = h5f["ana.neuron_ids"]
bt = bursts["system_level.beg_times"]
et = bursts["system_level.end_times"]
fraction = np.zeros(len(bt))
num_spks = np.zeros(len(bt))
for bdx in range(0, len(bt)):
n_ids = np.where((bt[bdx] <= spikes[selects]) & (spikes[selects] <= et[bdx]))[0]
n_unk = len(np.unique(n_ids))
fraction[bdx] = n_unk / len(selects)
num_spks[bdx] = len(n_ids) / np.fmax(n_unk, 1)
bursts["system_level.participating_fraction"] = fraction.tolist()
bursts["system_level.num_spikes_in_bursts"] = num_spks.tolist()
if return_res:
return bursts
def find_onset_durations(h5f, write_to_h5f=True, return_res=False):
"""
Similar to the duration of a burst (start time to end time),
we can ask how long did it take from activating the first
to activating the last module.
where "activating" means the first spike of a module
"""
assert "ana.bursts.system_level" in h5f.keypaths()
spikes = h5f["data.spiketimes"]
beg_times = h5f["ana.bursts.system_level.beg_times"]
end_times = h5f["ana.bursts.system_level.end_times"]
onset_durations = []
for idx in range(0, len(beg_times)):
beg = beg_times[idx]
end = end_times[idx]
nids, tidx = np.where((spikes >= beg) & (spikes <= end))
onsets = []
for nid in np.unique(nids):
ndx = np.where(nids == nid)[0]