-
Notifications
You must be signed in to change notification settings - Fork 4
/
subtract.py
1855 lines (1685 loc) · 60.3 KB
/
subtract.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import contextlib
import gc
import logging
import multiprocessing
import time
from collections import namedtuple
from pathlib import Path
import h5py
import numpy as np
import pandas as pd
import spikeinterface.core as sc
import torch
import torch.nn.functional as F
from tqdm.auto import tqdm
from . import chunk_features, denoise, detect, localize_index
from .multiprocessing_utils import MockQueue, ProcessPoolExecutor, get_pool
from .py_utils import noint, timer
from .spikeio import read_waveforms_in_memory
from .waveform_utils import make_channel_index, make_contiguous_channel_index
try:
from dartsort.transform.enforce_decrease import EnforceDecrease
except ImportError:
pass
_logger = logging.getLogger(__name__)
default_extra_feats = [
chunk_features.MaxPTP,
chunk_features.TroughDepth,
chunk_features.PeakHeight,
]
def subtraction(
recording,
out_folder,
out_filename="subtraction.h5",
# should we start over?
overwrite=False,
# waveform args
trough_offset=42,
spike_length_samples=121,
# tpca args
tpca_rank=8,
n_sec_pca=40,
pca_t_start=0,
pca_t_end=None,
# time / input binary details
n_sec_chunk=1,
# detection
thresholds=[12, 10, 8, 6, 5, 4],
peak_sign="both",
nn_detect=False,
denoise_detect=False,
do_nn_denoise=True,
residnorm_decrease=np.sqrt(10.0),
# waveform extraction channels
neighborhood_kind="circle",
extract_box_radius=200,
extract_firstchan_n_channels=40,
box_norm_p=np.inf,
dedup_spatial_radius=70,
enforce_decrease_kind="radial",
do_phaseshift=False,
ci_graph_all_maxCH_uniq=None,
maxCH_neighbor=None,
# what to save?
save_residual=False,
save_subtracted_waveforms=False,
save_cleaned_waveforms=False,
save_denoised_waveforms=False,
save_subtracted_tpca_projs=False,
save_cleaned_tpca_projs=True,
save_denoised_tpca_projs=False,
save_denoised_ptp_vectors=True,
# we will save spatiotemporal PCA embeds if this is >0
save_cleaned_pca_projs_on_n_channels=None,
save_cleaned_pca_projs_rank=5,
# localization args
# set this to None or "none" to turn off
localization_model="pointsource",
localization_kind="logbarrier",
localize_radius=100,
localize_firstchan_n_channels=20,
loc_workers=4,
loc_feature="ptp",
loc_ptp_precision_decimals=None,
# want to compute any other features of the waveforms?
extra_features="default",
# misc kwargs
random_seed=0,
denoiser_init_kwargs={},
denoiser_weights_path=None,
dtype=np.float32,
n_jobs=1,
device=None,
):
"""Subtraction-based waveform extraction
Runs subtraction pipeline, and optionally also the localization.
Loads data from a binary file (standardized_bin), and loads geometry
from the associated meta file if `geom=None`.
Results are saved to `out_folder` in the following format:
- residual_[dataset name]_[time region].bin
- a binary file like the input binary
- subtraction_[dataset name]_[time region].h5
- An HDF5 file containing all of the resulting data.
In detail, if N is the number of discovered waveforms,
n_channels is the number of channels in the probe,
T is `spike_len_samples`, C is the number of channels
of the extracted waveforms (determined from `extract_box_radius`),
then this HDF5 file contains the following datasets:
geom : (n_channels, 2)
start_sample : scalar
end_sample : scalar
First and last sample of time region considered
(controlled by arguments `t_start`, `t_end`)
channel_index : (n_channels, C)
Array of channel indices. channel_index[c] contains the
channels that a waveform with max channel `c` was extracted
on.
tpca_mean, tpca_components : arrays
The fitted temporal PCA parameters.
spike_index : (N, 2)
The columns are (sample, max channel)
subtracted_waveforms : (N, T, C)
Waveforms that were subtracted
cleaned_waveforms : (N, T, C)
Final denoised waveforms, only computed/saved if
`do_clean=True`
localizations : (N, 5)
Only computed/saved if `localization_kind` is `"logbarrier"`
or `"original"`
The columsn are: x, y, z, alpha, z relative to max channel
maxptps : (N,)
Only computed/saved if `localization_kind="logbarrier"`
Returns
-------
out_h5 : path to output hdf5 file
residual : path to residual if save_residual
"""
# validate and process args
if neighborhood_kind not in ("firstchan", "box", "circle"):
raise ValueError(
"Neighborhood kind", neighborhood_kind, "not understood."
)
if enforce_decrease_kind not in ("columns", "radial", "none", "new"):
raise ValueError(
"Enforce decrease method", enforce_decrease_kind, "not understood."
)
if peak_sign not in ("neg", "both"):
raise ValueError("peak_sign", peak_sign, "not understood.")
if neighborhood_kind == "circle":
neighborhood_kind = "box"
box_norm_p = 2
batch_len_samples = int(
np.floor(n_sec_chunk * recording.get_sampling_frequency())
)
print(device)
# prepare output dir
out_folder = Path(out_folder)
out_folder.mkdir(exist_ok=True)
batch_data_folder = out_folder / f"subtraction_batches"
batch_data_folder.mkdir(exist_ok=True)
assert out_filename.endswith(".h5"), "Nice try."
out_h5 = out_folder / out_filename
if save_residual:
residual_bin = out_folder / f"residual.bin"
try:
# this is to check if another program is using our h5, in which
# case we should crash early rather than late.
if out_h5.exists():
with h5py.File(out_h5, "r+") as _:
pass
del _
gc.collect()
except BlockingIOError as e:
raise ValueError(
f"Output HDF5 {out_h5} is currently in use by another program. "
"Maybe a Jupyter notebook that's still running?"
) from e
# pick torch device if it's not supplied
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if device.type == "cuda":
torch.cuda._lazy_init()
else:
device = torch.device(device)
torch.set_grad_enabled(False)
# figure out if we will use a NN detector, and if so which
nn_detector_path = None
if nn_detect:
raise NotImplementedError(
"Need to find out how to get Neuropixels version from SI."
)
# nn_detector_path = (
# Path(__file__).parent.parent / f"pretrained/detect_{probe}.pt"
# )
# print("Using pretrained detector for", probe, "from", nn_detector_path)
detection_kind = "voltage->NN"
elif denoise_detect:
print("Using denoising NN detection")
detection_kind = "denoised PTP"
else:
print("Using voltage detection")
detection_kind = "voltage"
print(
f"Running subtraction on: {recording}. "
f"Using {detection_kind} detection with thresholds: {thresholds}."
)
# compute helper data structures
# channel indexes for extraction, NN detection, deduplication
geom = recording.get_channel_locations()
print(f"{geom.shape=}")
dedup_channel_index = make_channel_index(
geom, dedup_spatial_radius, steps=2
)
nn_channel_index = make_channel_index(geom, dedup_spatial_radius, steps=1)
if neighborhood_kind == "box":
extract_channel_index = make_channel_index(
geom, extract_box_radius, distance_order=False, p=box_norm_p
)
elif neighborhood_kind == "firstchan":
extract_channel_index = make_contiguous_channel_index(
recording.get_num_channels(),
n_neighbors=extract_firstchan_n_channels,
)
else:
assert False
# handle ChunkFeature pipeline
do_clean = (
save_denoised_tpca_projs
or save_denoised_ptp_vectors
or localization_kind
in (
"original",
"logbarrier",
)
)
if extra_features == "default":
feat_wfs = "denoised" if do_clean else "subtracted"
extra_features = [
F(which_waveforms=feat_wfs) for F in default_extra_feats
]
if save_denoised_ptp_vectors:
extra_features += [
chunk_features.PTPVector(which_waveforms="denoised")
]
if save_cleaned_pca_projs_on_n_channels:
extra_features += [
chunk_features.STPCA(
channel_index=extract_channel_index,
which_waveforms="cleaned",
rank=save_cleaned_pca_projs_rank,
n_channels=save_cleaned_pca_projs_on_n_channels,
geom=geom,
)
]
# helper data structure for radial enforce decrease
do_enforce_decrease = True
radial_parents = None
enfdec = None
if enforce_decrease_kind == "radial":
radial_parents = denoise.make_radial_order_parents(
geom, extract_channel_index, n_jumps_per_growth=1, n_jumps_parent=3
)
elif enforce_decrease_kind == "columns":
pass
elif enforce_decrease_kind == "new":
enfdec = EnforceDecrease(
channel_index=extract_channel_index, geom=geom
)
else:
print("Skipping enforce decrease.")
do_enforce_decrease = False
maxCH_neighbor = None
ci_graph_all_maxCH_uniq = None
if do_phaseshift == True:
ci_graph_on_probe, maxCH_neighbor = denoise.make_ci_graph(
extract_channel_index, geom, device
)
ci_graph_all_maxCH_uniq = denoise.make_ci_graph_all_maxCH(
ci_graph_on_probe, maxCH_neighbor, device
)
else:
print("No phase-shift.")
do_phaseshift = False
# check localization arg
if localization_model not in ("pointsource", "CoM", "dipole"):
raise ValueError(f"Unknown localization model: {localization_model}")
if localization_kind in ("original", "logbarrier"):
print("Using", localization_kind, "localization")
if not isinstance(loc_feature, (list, tuple)):
loc_feature = (loc_feature,)
for lf in loc_feature:
extra_features += [
chunk_features.Localization(
geom,
extract_channel_index,
loc_n_chans=localize_firstchan_n_channels
if neighborhood_kind == "firstchan"
else None,
loc_radius=localize_radius
if neighborhood_kind != "firstchan"
else None,
localization_kind=localization_kind,
localization_model=localization_model,
feature=lf,
ptp_precision_decimals=loc_ptp_precision_decimals,
)
]
else:
print("No localization")
# see if we are asked to save any waveforms
wf_bools = (
save_subtracted_waveforms,
save_cleaned_waveforms,
save_denoised_waveforms,
)
wf_names = ("subtracted", "cleaned", "denoised")
for do_save, kind in zip(wf_bools, wf_names):
if do_save:
extra_features += [
chunk_features.Waveform(
which_waveforms=kind,
)
]
# see if we are asked to save tpca projs for
# collision-cleaned or denoised waveforms
subtracted_tpca_feat = chunk_features.TPCA(
tpca_rank,
extract_channel_index,
which_waveforms="subtracted",
random_state=random_seed,
)
if save_subtracted_tpca_projs:
extra_features += [subtracted_tpca_feat]
if save_cleaned_tpca_projs:
extra_features += [
chunk_features.TPCA(
tpca_rank,
extract_channel_index,
which_waveforms="cleaned",
random_state=random_seed,
)
]
fit_feats = []
if do_clean:
denoised_tpca_feat = chunk_features.TPCA(
tpca_rank,
extract_channel_index,
which_waveforms="denoised",
random_state=random_seed,
)
if save_denoised_tpca_projs:
extra_features += [denoised_tpca_feat]
else:
fit_feats += [denoised_tpca_feat]
# try to load feats from h5
if not overwrite and out_h5.exists():
with h5py.File(out_h5, "r") as output_h5:
for feat in [subtracted_tpca_feat] + fit_feats:
feat.from_h5(output_h5)
del output_h5
gc.collect()
# otherwise, train it
# TODO: ideally would run this on another process,
# because this is the only time the main thread uses
# GPU, and we could avoid initializing torch runtime.
if subtracted_tpca_feat.needs_fit:
with timer("Training TPCA..."):
train_featurizers(
recording,
extract_channel_index,
geom,
radial_parents,
enfdec,
dedup_channel_index,
thresholds,
nn_detector_path=nn_detector_path,
denoise_detect=denoise_detect,
nn_channel_index=nn_channel_index,
extra_features=[subtracted_tpca_feat],
subtracted_tpca=None,
peak_sign=peak_sign,
do_nn_denoise=do_nn_denoise,
residnorm_decrease=residnorm_decrease,
do_enforce_decrease=do_enforce_decrease,
do_phaseshift=do_phaseshift,
ci_graph_all_maxCH_uniq=ci_graph_all_maxCH_uniq,
maxCH_neighbor=maxCH_neighbor,
denoiser_init_kwargs=denoiser_init_kwargs,
denoiser_weights_path=denoiser_weights_path,
n_sec_pca=n_sec_pca,
pca_t_start=pca_t_start,
pca_t_end=pca_t_end,
random_seed=random_seed,
device="cpu",
trough_offset=trough_offset,
spike_length_samples=spike_length_samples,
dtype=dtype,
)
# train featurizers
if any(f.needs_fit for f in extra_features + fit_feats):
# try to load old featurizers
if not overwrite and out_h5.exists():
with h5py.File(out_h5, "r") as output_h5:
for f in extra_features + fit_feats:
if f.needs_fit:
f.from_h5(output_h5)
# train any which couldn't load
if any(f.needs_fit for f in extra_features + fit_feats):
train_featurizers(
recording,
extract_channel_index,
geom,
radial_parents,
enfdec,
dedup_channel_index,
thresholds,
nn_detector_path,
denoise_detect,
nn_channel_index,
subtracted_tpca=subtracted_tpca_feat,
extra_features=extra_features + fit_feats,
peak_sign=peak_sign,
do_nn_denoise=do_nn_denoise,
residnorm_decrease=residnorm_decrease,
do_enforce_decrease=do_enforce_decrease,
do_phaseshift=do_phaseshift,
ci_graph_all_maxCH_uniq=ci_graph_all_maxCH_uniq,
maxCH_neighbor=maxCH_neighbor,
denoiser_init_kwargs=denoiser_init_kwargs,
denoiser_weights_path=denoiser_weights_path,
n_sec_pca=n_sec_pca,
pca_t_start=pca_t_start,
pca_t_end=pca_t_end,
random_seed=random_seed,
device="cpu",
dtype=dtype,
trough_offset=trough_offset,
spike_length_samples=spike_length_samples,
)
# if we're on GPU, we can't use processes, since each process will
# have it's own torch runtime and those will use all the memory
if device.type == "cuda":
pass
else:
if loc_workers > 1:
print(
"Setting number of localization workers to 1. (Since "
"you're on CPU, use a large n_jobs for parallelism.)"
)
loc_workers = 1
# parallel batches
jobs = list(
enumerate(
range(
0,
recording.get_num_samples(),
batch_len_samples,
)
)
)
# -- initialize storage
with get_output_h5(
out_h5,
recording,
extract_channel_index,
extra_features,
fit_features=[subtracted_tpca_feat] + fit_feats,
overwrite=overwrite,
dtype=dtype,
) as (output_h5, last_sample):
# residual binary file -- append if we're resuming
if save_residual:
residual_mode = "ab" if last_sample > 0 else "wb"
residual = open(residual_bin, mode=residual_mode)
extra_features = [ef.to("cpu") for ef in extra_features]
# no-threading/multiprocessing execution for debugging if n_jobs == 0
Executor, context = get_pool(n_jobs, cls=ProcessPoolExecutor)
manager = context.Manager() if n_jobs > 1 else None
id_queue = manager.Queue() if n_jobs > 1 else MockQueue()
n_jobs = n_jobs or 1
if n_jobs < 0:
n_jobs = multiprocessing.cpu_count() - 1
for id in range(n_jobs):
id_queue.put(id)
with Executor(
max_workers=n_jobs,
mp_context=context,
initializer=_subtraction_batch_init,
initargs=(
device,
nn_detector_path,
nn_channel_index,
denoise_detect,
do_nn_denoise,
id_queue,
denoiser_init_kwargs,
denoiser_weights_path,
recording.to_dict(),
extra_features,
subtracted_tpca_feat,
denoised_tpca_feat if do_clean else None,
enfdec,
),
) as pool:
spike_index = output_h5["spike_index"]
feature_dsets = [output_h5[f.name] for f in extra_features]
N = len(spike_index)
# if we're resuming, filter out jobs we already did
jobs = [
(batch_id, start)
for batch_id, start in jobs
if start >= last_sample
]
n_batches = len(jobs)
if n_batches > 0:
jobs = (
(
batch_data_folder,
batch_len_samples,
s_start,
thresholds,
dedup_channel_index,
trough_offset,
spike_length_samples,
extract_channel_index,
do_clean,
residnorm_decrease,
save_residual,
radial_parents,
geom,
do_enforce_decrease,
do_phaseshift,
ci_graph_all_maxCH_uniq,
maxCH_neighbor,
peak_sign,
dtype,
)
for batch_id, s_start in jobs
)
count = sum(
s < last_sample
for s in range(
0,
recording.get_num_samples(),
batch_len_samples,
)
)
# now run subtraction in parallel
pbar = tqdm(
pool.map(_subtraction_batch, jobs),
total=n_batches,
desc="Batches",
smoothing=0.01,
)
for result in pbar:
with noint:
N_new = result.N_new
# write new residual
if save_residual:
np.load(result.residual).tofile(residual)
Path(result.residual).unlink()
if result.spike_index is None:
continue
# grow arrays as necessary and write results
if N_new > 0:
spike_index.resize(N + N_new, axis=0)
spike_index[N:] = np.load(result.spike_index)
if Path(result.spike_index).exists():
Path(result.spike_index).unlink()
for f, dset in zip(extra_features, feature_dsets):
fnpy = (
batch_data_folder
/ f"{result.prefix}{f.name}.npy"
)
if N_new > 0:
dset.resize(N + N_new, axis=0)
dset[N:] = np.load(fnpy)
if Path(fnpy).exists():
Path(fnpy).unlink()
# update spike count
N += N_new
count += 1
pbar.set_description(
f"{n_sec_chunk}s/it [spk/it={N / count:0.1f}]"
)
# -- done!
if save_residual:
residual.close()
print("Done. Detected", N, "spikes")
print("Results written to:")
if save_residual:
print(residual_bin)
print(out_h5)
try:
batch_data_folder.rmdir()
except OSError as e:
print(e)
return out_h5
def subtraction_binary(
standardized_bin,
*args,
geom=None,
t_start=0,
t_end=None,
sampling_rate=30_000,
nsync=0,
binary_dtype=np.float32,
time_axis=0,
**kwargs,
):
"""Wrapper around `subtraction` to provide the old binary file API"""
# if no geometry is supplied, try to load it from meta file
if geom is None:
geom = read_geom_from_meta(standardized_bin)
if geom is None:
raise ValueError(
"Either pass `geom` or put meta file in folder with binary."
)
n_channels = geom.shape[0]
recording = sc.read_binary(
file_paths=standardized_bin,
sampling_frequency=sampling_rate,
num_channels=n_channels,
dtype=binary_dtype,
time_axis=time_axis,
is_filtered=True,
)
# set geometry
recording.set_dummy_probe_from_locations(
geom, shape_params=dict(radius=10)
)
if nsync > 0:
recording = recording.channel_slice(
channel_ids=recording.get_channel_ids()[:-nsync]
)
T_samples = recording.get_num_samples()
T_sec = T_samples / recording.get_sampling_frequency()
assert t_start >= 0 and (t_end is None or t_end <= T_sec)
start_sample = int(np.floor(t_start * sampling_rate))
end_sample = (
T_samples if t_end is None else int(np.floor(t_end * sampling_rate))
)
if start_sample > 0 or end_sample < T_samples:
recording = recording.frame_slice(
start_frame=start_sample, end_frame=end_sample
)
return subtraction(recording, *args, **kwargs)
# -- subtraction routines
# the return type for `subtraction_batch` below
SubtractionBatchResult = namedtuple(
"SubtractionBatchResult",
["N_new", "s_start", "s_end", "spike_index", "residual", "prefix"],
)
# Parallelism helpers
def _subtraction_batch(args):
return subtraction_batch(
*args,
_subtraction_batch.extra_features,
_subtraction_batch.subtracted_tpca,
_subtraction_batch.denoised_tpca,
_subtraction_batch.recording,
_subtraction_batch.device,
_subtraction_batch.denoiser,
_subtraction_batch.detector,
_subtraction_batch.dn_detector,
_subtraction_batch.enfdec,
)
def _subtraction_batch_init(
device,
nn_detector_path,
nn_channel_index,
denoise_detect,
do_nn_denoise,
id_queue,
denoiser_init_kwargs,
denoiser_weights_path,
recording_dict,
extra_features,
subtracted_tpca,
denoised_tpca,
enfdec,
):
"""Thread/process initializer -- loads up neural nets"""
rank = id_queue.get()
torch.set_grad_enabled(False)
if device.type == "cuda" and device.index is None:
if not rank:
print("num gpus:", torch.cuda.device_count())
if torch.cuda.device_count() > 1:
device = torch.device(
"cuda", index=rank % torch.cuda.device_count()
)
print(
f"Worker {rank} using GPU {rank % torch.cuda.device_count()} "
f"out of {torch.cuda.device_count()} available."
)
elif device.type == "cuda" and device.index is not None and not rank:
print(
f"All workers will live on {device} since a specific GPU was chosen"
)
_subtraction_batch.device = device
time.sleep(rank / 20)
print(f"Worker {rank} init", flush=True)
denoiser = None
if do_nn_denoise:
denoiser = denoise.SingleChanDenoiser(**denoiser_init_kwargs)
if denoiser_weights_path is not None:
denoiser.load(fname_model=denoiser_weights_path)
else:
denoiser.load()
denoiser.requires_grad_(False)
denoiser.to(device)
_subtraction_batch.denoiser = denoiser
detector = None
if nn_detector_path:
detector = detect.Detect(nn_channel_index)
detector.load(nn_detector_path)
detector.requires_grad_(False)
detector.to(device)
_subtraction_batch.detector = detector
dn_detector = None
if denoise_detect:
dn_detector = detect.DenoiserDetect(denoiser)
dn_detector.requires_grad_(False)
dn_detector.to(device)
_subtraction_batch.dn_detector = dn_detector
_subtraction_batch.extra_features = [
ef.to(device) for ef in extra_features
]
_subtraction_batch.subtracted_tpca = subtracted_tpca.to(device)
if denoised_tpca is not None:
denoised_tpca = denoised_tpca.to(device)
_subtraction_batch.denoised_tpca = denoised_tpca
_subtraction_batch.enfdec = enfdec
if enfdec is not None:
_subtraction_batch.enfdec.to(device)
# this is a hack to fix ibl streaming in parallel
stack = [recording_dict]
for d in stack:
for k, v in d.items():
if isinstance(v, dict):
if (
"class" in v
and "IblStreamingRecordingExtractor" in v["class"]
):
v["kwargs"]["cache_folder"] = (
Path(v["kwargs"]["cache_folder"]) / f"cache{rank}"
)
else:
stack.append(v)
_subtraction_batch.recording = sc.BaseRecording.from_dict(recording_dict)
def subtraction_batch(
batch_data_folder,
batch_len_samples,
s_start,
thresholds,
dedup_channel_index,
trough_offset,
spike_length_samples,
extract_channel_index,
do_clean,
residnorm_decrease,
save_residual,
radial_parents,
geom,
do_enforce_decrease,
do_phaseshift,
ci_graph_all_maxCH_uniq,
maxCH_neighbor,
peak_sign,
dtype,
extra_features,
subtracted_tpca,
denoised_tpca,
recording,
device,
denoiser,
detector,
dn_detector,
enfdec,
):
"""Runs subtraction on a batch
This function handles the logic of loading data from disk
(padding it with a buffer where necessary), running the loop
over thresholds for `detect_and_subtract`, handling spikes
that were in the buffer, and applying the denoising pipeline.
A note on buffer logic:
- We load a buffer of twice the spike length.
- The outer buffer of size spike length is to ensure that
spikes inside the inner buffer of size spike length can be
loaded
- We subtract spikes inside the inner buffer in `detect_and_subtract`
to ensure consistency of the residual across batches.
Arguments
---------
batch_data_folder : string
Where temporary results are being stored
s_start : int
The batch's starting time in samples
batch_len_samples : int
The length of a batch in samples
standardized_bin : int
The path to the standardized binary file
thresholds : list of int
Voltage thresholds for subtraction
tpca : sklearn PCA object or None
A pre-trained temporal PCA (or None in which case no PCA
is applied)
trough_offset : int
42 in practice, the alignment of the max channel's trough
in the extracted waveforms
dedup_channel_index : int array (num_channels, num_neighbors)
Spatial neighbor structure for deduplication
spike_length_samples : int
121 in practice, temporal length of extracted waveforms
extract_channel_index : int array (num_channels, extract_channels)
Channel neighborhoods for extracted waveforms
device : string or torch.device
start_sample, end_sample : int
Temporal boundary of the region of the recording being
considered (in samples)
radial_parents
Helper data structure for enforce_decrease
localization_kind : str
How should we run localization?
loc_workers : int
on how many threads?
geom : array
The probe geometry
denoiser, detector : torch nns or None
probe : string or None
Returns
-------
res : SubtractionBatchResult
"""
# we use a double buffer: inner buffer of length spike_length,
# outer buffer of length spike_length
# - detections are restricted to the inner buffer
# - outer buffer allows detections on the border of the inner
# buffer to be loaded
# - using the inner buffer allows for subtracted residuals to be
# consistent (more or less) across batches
# - only the spikes in the center (i.e. not in either buffer)
# will be returned to the caller
buffer = 2 * spike_length_samples
# load raw data with buffer
s_end = min(recording.get_num_samples(), s_start + batch_len_samples)
n_channels = len(dedup_channel_index)
load_start = max(0, s_start - buffer)
load_end = min(recording.get_num_samples(), s_end + buffer)
residual = recording.get_traces(start_frame=load_start, end_frame=load_end)
residual = residual.astype(dtype)
assert np.isfinite(residual).all()
prefix = f"{s_start:010d}_"
# 0 padding if we were at the edge of the data
pad_left = pad_right = 0
if load_start == 0:
pad_left = buffer
if load_end == recording.get_num_samples():
pad_right = buffer - (recording.get_num_samples() - s_end)
if pad_left != 0 or pad_right != 0:
residual = np.pad(
residual, [(pad_left, pad_right), (0, 0)], mode="edge"
)
# now, no matter where we were, the data has the following shape
assert residual.shape == (2 * buffer + s_end - s_start, n_channels)
# main subtraction loop
subtracted_wfs = []
spike_index = []
for threshold in thresholds:
subwfs, subpcs, residual, spind = detect_and_subtract(
residual,
threshold,
radial_parents,
enfdec,
subtracted_tpca,
dedup_channel_index,
extract_channel_index,
peak_sign=peak_sign,
detector=detector,
denoiser=denoiser,
denoiser_detector=dn_detector,
trough_offset=trough_offset,
spike_length_samples=spike_length_samples,
device=device,
do_enforce_decrease=do_enforce_decrease,
do_phaseshift=do_phaseshift,
ci_graph_all_maxCH_uniq=ci_graph_all_maxCH_uniq,
maxCH_neighbor=maxCH_neighbor,
geom=geom,
residnorm_decrease=residnorm_decrease,
)
if len(spind):
subtracted_wfs.append(subwfs)
spike_index.append(spind)
# at this point, trough times in the spike index are relative
# to the full buffer of length 2 * spike length
# strip buffer from residual and remove spikes in buffer
residual_singlebuf = residual[spike_length_samples:-spike_length_samples]
residual = residual[buffer:-buffer]
if batch_data_folder is not None and save_residual:
np.save(batch_data_folder / f"{prefix}res.npy", residual.cpu().numpy())
# return early if there were no spikes
if batch_data_folder is None and not spike_index:
# this return is used by `train_pca` as an early exit
return spike_index, subtracted_wfs, residual_singlebuf
elif not spike_index:
return SubtractionBatchResult(
N_new=0,
s_start=s_start,
s_end=s_end,
spike_index=None,
residual=batch_data_folder / f"{prefix}res.npy",
prefix=prefix,
)
subtracted_wfs = torch.cat(subtracted_wfs, dim=0)