Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

06362f9a-b688-4395-b925-675f34e6002e 27 KB
Raw

You have to be logged in to leave a comment. Sign In
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
  1. """
  2. This gather some function usefull for some clusetring algos.
  3. """
  4. import numpy as np
  5. from spikeinterface.core.job_tools import fix_job_kwargs
  6. from spikeinterface.postprocessing import check_equal_template_with_distribution_overlap
  7. def _split_waveforms(
  8. wfs_and_noise, noise_size, n_components_by_channel, n_components, hdbscan_params, probability_thr, debug
  9. ):
  10. import sklearn.decomposition
  11. import hdbscan
  12. valid_size = wfs_and_noise.shape[0] - noise_size
  13. local_feature = np.zeros((wfs_and_noise.shape[0], n_components_by_channel * wfs_and_noise.shape[2]))
  14. tsvd = sklearn.decomposition.TruncatedSVD(n_components=n_components_by_channel)
  15. for c in range(wfs_and_noise.shape[2]):
  16. local_feature[:, c * n_components_by_channel : (c + 1) * n_components_by_channel] = tsvd.fit_transform(
  17. wfs_and_noise[:, :, c]
  18. )
  19. n_components = min(n_components, local_feature.shape[1])
  20. pca = sklearn.decomposition.PCA(n_components=n_components, whiten=True)
  21. local_feature = pca.fit_transform(local_feature)
  22. # hdbscan on pca
  23. clustering = hdbscan.hdbscan(local_feature, **hdbscan_params)
  24. local_labels_with_noise = clustering[0]
  25. cluster_probability = clustering[2]
  26. (persistent_clusters,) = np.nonzero(cluster_probability > probability_thr)
  27. local_labels_with_noise[~np.isin(local_labels_with_noise, persistent_clusters)] = -1
  28. # remove super small cluster
  29. labels, count = np.unique(local_labels_with_noise[:valid_size], return_counts=True)
  30. mask = labels >= 0
  31. labels, count = labels[mask], count[mask]
  32. minimum_cluster_size_ratio = 0.05
  33. # ~ print(labels, count)
  34. to_remove = labels[(count / valid_size) < minimum_cluster_size_ratio]
  35. # ~ print('to_remove', to_remove, count / valid_size)
  36. if to_remove.size > 0:
  37. local_labels_with_noise[np.isin(local_labels_with_noise, to_remove)] = -1
  38. local_labels_with_noise[valid_size:] = -2
  39. if debug:
  40. import matplotlib.pyplot as plt
  41. import umap
  42. fig, ax = plt.subplots()
  43. # ~ reducer = umap.UMAP()
  44. # ~ local_feature_plot = reducer.fit_transform(local_feature)
  45. local_feature_plot = local_feature
  46. unique_lab = np.unique(local_labels_with_noise)
  47. cmap = plt.get_cmap("jet", unique_lab.size)
  48. cmap = {k: cmap(l) for l, k in enumerate(unique_lab)}
  49. cmap[-1] = "k"
  50. active_ind = np.arange(local_feature.shape[0])
  51. for k in unique_lab:
  52. plot_mask_1 = (active_ind < valid_size) & (local_labels_with_noise == k)
  53. plot_mask_2 = (active_ind >= valid_size) & (local_labels_with_noise == k)
  54. ax.scatter(
  55. local_feature_plot[plot_mask_1, 0],
  56. local_feature_plot[plot_mask_1, 1],
  57. color=cmap[k],
  58. marker="o",
  59. alpha=0.3,
  60. s=1,
  61. )
  62. ax.scatter(
  63. local_feature_plot[plot_mask_2, 0],
  64. local_feature_plot[plot_mask_2, 1],
  65. color=cmap[k],
  66. marker="*",
  67. alpha=0.3,
  68. s=1,
  69. )
  70. # ~ plt.show()
  71. return local_labels_with_noise
  72. def _split_waveforms_nested(
  73. wfs_and_noise, noise_size, nbefore, n_components_by_channel, n_components, hdbscan_params, probability_thr, debug
  74. ):
  75. import sklearn.decomposition
  76. import hdbscan
  77. valid_size = wfs_and_noise.shape[0] - noise_size
  78. local_labels_with_noise = np.zeros(wfs_and_noise.shape[0], dtype=np.int64)
  79. local_count = 1
  80. while True:
  81. # ~ print(' local_count', local_count, np.sum(local_labels_with_noise[:-noise_size] == 0), local_labels_with_noise.size - noise_size)
  82. if np.all(local_labels_with_noise[:-noise_size] != 0):
  83. break
  84. (active_ind,) = np.nonzero(local_labels_with_noise == 0)
  85. # reduce dimention in 2 step
  86. active_wfs = wfs_and_noise[active_ind, :, :]
  87. local_feature = np.zeros((active_wfs.shape[0], n_components_by_channel * active_wfs.shape[2]))
  88. tsvd = sklearn.decomposition.TruncatedSVD(n_components=n_components_by_channel)
  89. for c in range(wfs_and_noise.shape[2]):
  90. local_feature[:, c * n_components_by_channel : (c + 1) * n_components_by_channel] = tsvd.fit_transform(
  91. active_wfs[:, :, c]
  92. )
  93. # ~ n_components = min(n_components, local_feature.shape[1])
  94. # ~ pca = sklearn.decomposition.PCA(n_components=n_components, whiten=True)
  95. # ~ local_feature = pca.fit_transform(local_feature)
  96. # hdbscan on pca
  97. clustering = hdbscan.hdbscan(local_feature, **hdbscan_params)
  98. active_labels_with_noise = clustering[0]
  99. cluster_probability = clustering[2]
  100. (persistent_clusters,) = np.nonzero(clustering[2] > probability_thr)
  101. active_labels_with_noise[~np.isin(active_labels_with_noise, persistent_clusters)] = -1
  102. active_labels = active_labels_with_noise[active_ind < valid_size]
  103. active_labels_set = np.unique(active_labels)
  104. active_labels_set = active_labels_set[active_labels_set >= 0]
  105. num_cluster = active_labels_set.size
  106. if debug:
  107. import matplotlib.pyplot as plt
  108. fig, ax = plt.subplots()
  109. import umap
  110. reducer = umap.UMAP()
  111. local_feature_plot = reducer.fit_transform(local_feature)
  112. unique_lab = np.unique(active_labels_with_noise)
  113. cmap = plt.get_cmap("jet", unique_lab.size)
  114. cmap = {k: cmap(l) for l, k in enumerate(unique_lab)}
  115. cmap[-1] = "k"
  116. cmap[-2] = "b"
  117. for k in unique_lab:
  118. plot_mask_1 = (active_ind < valid_size) & (active_labels_with_noise == k)
  119. plot_mask_2 = (active_ind >= valid_size) & (active_labels_with_noise == k)
  120. ax.scatter(
  121. local_feature_plot[plot_mask_1, 0], local_feature_plot[plot_mask_1, 1], color=cmap[k], marker="o"
  122. )
  123. ax.scatter(
  124. local_feature_plot[plot_mask_2, 0], local_feature_plot[plot_mask_2, 1], color=cmap[k], marker="*"
  125. )
  126. # ~ plt.show()
  127. if num_cluster > 1:
  128. # take the best one
  129. extremum_values = []
  130. assert active_ind.size == active_labels_with_noise.size
  131. for k in active_labels_set:
  132. # ~ sel = active_labels_with_noise == k
  133. # ~ sel[-noise_size:] = False
  134. sel = (active_ind < valid_size) & (active_labels_with_noise == k)
  135. if np.sum(sel) == 1:
  136. # only one spike
  137. extremum_values.append(0)
  138. else:
  139. v = np.mean(np.abs(np.mean(active_wfs[sel, nbefore, :], axis=0)))
  140. extremum_values.append(v)
  141. best_label = active_labels_set[np.argmax(extremum_values)]
  142. # ~ inds = active_ind[active_labels_with_noise == best_label]
  143. inds = active_ind[(active_ind < valid_size) & (active_labels_with_noise == best_label)]
  144. # ~ inds_no_noise = inds[inds < valid_size]
  145. if inds.size > 1:
  146. # avoid cluster with one spike
  147. local_labels_with_noise[inds] = local_count
  148. local_count += 1
  149. else:
  150. local_labels_with_noise[inds] = -1
  151. local_count += 1
  152. elif num_cluster == 1:
  153. best_label = active_labels_set[0]
  154. # ~ inds = active_ind[active_labels_with_noise == best_label]
  155. # ~ inds_no_noise = inds[inds < valid_size]
  156. inds = active_ind[(active_ind < valid_size) & (active_labels_with_noise == best_label)]
  157. if inds.size > 1:
  158. # avoid cluster with one spike
  159. local_labels_with_noise[inds] = local_count
  160. local_count += 1
  161. else:
  162. local_labels_with_noise[inds] = -1
  163. # last loop
  164. local_labels_with_noise[active_ind[active_labels_with_noise == -1]] = -1
  165. else:
  166. local_labels_with_noise[active_ind] = -1
  167. break
  168. # ~ local_labels = local_labels_with_noise[:-noise_size]
  169. local_labels_with_noise[local_labels_with_noise > 0] -= 1
  170. return local_labels_with_noise
  171. def auto_split_clustering(
  172. wfs_arrays,
  173. sparsity_mask,
  174. labels,
  175. peak_labels,
  176. nbefore,
  177. nafter,
  178. noise,
  179. n_components_by_channel=3,
  180. n_components=5,
  181. hdbscan_params={},
  182. probability_thr=0,
  183. debug=False,
  184. debug_folder=None,
  185. ):
  186. """
  187. Loop over sparse waveform and try to over split.
  188. Internally used by PositionAndPCAClustering for the second step.
  189. """
  190. import sklearn.decomposition
  191. import hdbscan
  192. split_peak_labels = -1 * np.ones(peak_labels.size, dtype=np.int64)
  193. nb_clusters = 0
  194. main_channels = {}
  195. for l, label in enumerate(labels):
  196. # ~ print()
  197. # ~ print('auto_split_clustering', label, l, len(labels))
  198. (chans,) = np.nonzero(sparsity_mask[l, :])
  199. wfs = wfs_arrays[label]
  200. valid_size = wfs.shape[0]
  201. wfs_and_noise = np.concatenate([wfs, noise[:, :, chans]], axis=0)
  202. noise_size = noise.shape[0]
  203. local_labels_with_noise = _split_waveforms(
  204. wfs_and_noise, noise_size, n_components_by_channel, n_components, hdbscan_params, probability_thr, debug
  205. )
  206. # local_labels_with_noise = _split_waveforms_nested(wfs_and_noise, noise_size, nbefore, n_components_by_channel, n_components, hdbscan_params, probability_thr, debug)
  207. local_labels = local_labels_with_noise[:valid_size]
  208. if noise_size > 0:
  209. local_labels_with_noise[valid_size:] = -2
  210. for k in np.unique(local_labels):
  211. if k < 0:
  212. continue
  213. template = np.mean(wfs[local_labels == k, :, :], axis=1)
  214. (chan_inds,) = np.nonzero(sparsity_mask[l, :])
  215. assert wfs.shape[2] == chan_inds.size
  216. main_chan = chan_inds[np.argmax(np.max(np.abs(template), axis=0))]
  217. main_channels[k + nb_clusters] = main_chan
  218. if debug:
  219. # ~ local_labels_with_noise[-noise_size:] = -2
  220. import matplotlib.pyplot as plt
  221. # ~ fig, axs = plt.subplots(ncols=3)
  222. fig, ax = plt.subplots()
  223. plot_labels_set = np.unique(local_labels_with_noise)
  224. cmap = plt.get_cmap("jet", plot_labels_set.size)
  225. cmap = {k: cmap(l) for l, k in enumerate(plot_labels_set)}
  226. cmap[-1] = "k"
  227. cmap[-2] = "b"
  228. for plot_label in plot_labels_set:
  229. plot_mask = local_labels_with_noise == plot_label
  230. color = cmap[plot_label]
  231. wfs_flat = wfs_and_noise[plot_mask, :, :].swapaxes(1, 2).reshape(np.sum(plot_mask), -1).T
  232. ax.plot(wfs_flat, color=color, alpha=0.1)
  233. if plot_label >= 0:
  234. ax.plot(wfs_flat.mean(1), color=color, lw=2)
  235. for c in range(wfs.shape[2]):
  236. ax.axvline(c * (nbefore + nafter) + nbefore, color="k", ls="-", alpha=0.5)
  237. if debug_folder is not None:
  238. fig.savefig(debug_folder / f"auto_split_{label}.png")
  239. plt.show()
  240. # remove noise labels
  241. (mask,) = np.nonzero(peak_labels == label)
  242. (mask2,) = np.nonzero(local_labels >= 0)
  243. split_peak_labels[mask[mask2]] = local_labels[mask2] + nb_clusters
  244. nb_clusters += local_labels.max() + 1
  245. return split_peak_labels, main_channels
  246. def auto_clean_clustering(
  247. wfs_arrays,
  248. sparsity_mask,
  249. labels,
  250. peak_labels,
  251. nbefore,
  252. nafter,
  253. channel_distances,
  254. radius_um=50,
  255. auto_merge_num_shift=7,
  256. auto_merge_quantile_limit=0.8,
  257. ratio_num_channel_intersect=0.8,
  258. ):
  259. """ """
  260. clean_peak_labels = peak_labels.copy()
  261. # ~ labels = np.unique(peak_labels)
  262. # ~ labels = labels[labels >= 0]
  263. # Check debug
  264. assert sparsity_mask.shape[0] == labels.shape[0]
  265. # get main channel on new wfs
  266. templates = []
  267. main_channels = []
  268. for l, label in enumerate(labels):
  269. wfs = wfs_arrays[label]
  270. template = np.mean(wfs, axis=0)
  271. (chan_inds,) = np.nonzero(sparsity_mask[l, :])
  272. assert wfs.shape[2] == chan_inds.size
  273. main_chan = chan_inds[np.argmax(np.max(np.abs(template), axis=0))]
  274. templates.append(template)
  275. main_channels.append(main_chan)
  276. # ~ plot_debug = True
  277. # ~ if plot_debug:
  278. # ~ import matplotlib.pyplot as plt
  279. # ~ wfs_flat = wfs.swapaxes(1, 2).reshape(wfs.shape[0], -1).T
  280. # ~ fig, ax = plt.subplots()
  281. # ~ ax.plot(wfs_flat, color='g', alpha=0.1)
  282. # ~ ax.plot(template.T.flatten(), color='c', lw=2)
  283. # ~ plt.show()
  284. ## Step 1 : auto merge
  285. auto_merge_list = []
  286. for l0 in range(len(labels)):
  287. for l1 in range(l0 + 1, len(labels)):
  288. label0, label1 = labels[l0], labels[l1]
  289. main_chan0 = main_channels[l0]
  290. main_chan1 = main_channels[l1]
  291. if channel_distances[main_chan0, main_chan1] > radius_um:
  292. continue
  293. (channel_inds0,) = np.nonzero(sparsity_mask[l0, :])
  294. (channel_inds1,) = np.nonzero(sparsity_mask[l1, :])
  295. intersect_chans = np.intersect1d(channel_inds0, channel_inds1)
  296. # union_chans = np.union1d(channel_inds0, channel_inds1)
  297. # we use
  298. (radius_chans,) = np.nonzero(
  299. (channel_distances[main_chan0, :] <= radius_um) | (channel_distances[main_chan1, :] <= radius_um)
  300. )
  301. if radius_chans.size < (intersect_chans.size * ratio_num_channel_intersect):
  302. # ~ print('WARNING INTERSECT')
  303. # ~ print(intersect_chans.size, radius_chans.size, used_chans.size)
  304. continue
  305. used_chans = np.intersect1d(radius_chans, intersect_chans)
  306. if used_chans.size == 0:
  307. continue
  308. wfs0 = wfs_arrays[label0]
  309. wfs0 = wfs0[:, :, np.isin(channel_inds0, used_chans)]
  310. wfs1 = wfs_arrays[label1]
  311. wfs1 = wfs1[:, :, np.isin(channel_inds1, used_chans)]
  312. # TODO : remove
  313. assert wfs0.shape[2] == wfs1.shape[2]
  314. equal, shift = check_equal_template_with_distribution_overlap(
  315. wfs0, wfs1, num_shift=auto_merge_num_shift, quantile_limit=auto_merge_quantile_limit, return_shift=True
  316. )
  317. if equal:
  318. auto_merge_list.append((l0, l1, shift))
  319. # DEBUG plot
  320. # ~ plot_debug = debug
  321. # ~ plot_debug = True
  322. plot_debug = False
  323. # ~ plot_debug = equal
  324. if plot_debug:
  325. import matplotlib.pyplot as plt
  326. wfs_flat0 = wfs0.swapaxes(1, 2).reshape(wfs0.shape[0], -1).T
  327. wfs_flat1 = wfs1.swapaxes(1, 2).reshape(wfs1.shape[0], -1).T
  328. fig, ax = plt.subplots()
  329. ax.plot(wfs_flat0, color="g", alpha=0.1)
  330. ax.plot(wfs_flat1, color="r", alpha=0.1)
  331. ax.plot(np.mean(wfs_flat0, axis=1), color="c", lw=2)
  332. ax.plot(np.mean(wfs_flat1, axis=1), color="m", lw=2)
  333. for c in range(len(used_chans)):
  334. ax.axvline(c * (nbefore + nafter) + nbefore, color="k", ls="--")
  335. ax.set_title(
  336. f"label0={label0} label1={label1} equal{equal} shift{shift} \n chans intersect{intersect_chans.size} radius{radius_chans.size} used{used_chans.size}"
  337. )
  338. plt.show()
  339. # ~ print('auto_merge_list', auto_merge_list)
  340. # merge in reverse order because of shift accumulation
  341. peak_sample_shifts = np.zeros(peak_labels.size, dtype="int64")
  342. for l0, l1, shift in auto_merge_list[::-1]:
  343. label0, label1 = labels[l0], labels[l1]
  344. (inds,) = np.nonzero(peak_labels == label1)
  345. clean_peak_labels[inds] = label0
  346. peak_sample_shifts[inds] += shift
  347. # update label list
  348. labels_clean = np.unique(clean_peak_labels)
  349. labels_clean = labels_clean[labels_clean >= 0]
  350. # Step 2 : remove none aligner units
  351. # some unit have a secondary peak that can be detected
  352. # lets remove the secondary template
  353. # to avoid recomputing template this is done on the original list
  354. auto_trash_list = []
  355. auto_trash_misalignment_shift = auto_merge_num_shift + 1
  356. for l, label in enumerate(labels):
  357. if label not in labels_clean:
  358. continue
  359. template = templates[l]
  360. main_chan = main_channels[l]
  361. (chan_inds,) = np.nonzero(sparsity_mask[l, :])
  362. max_ind = list(chan_inds).index(main_chan)
  363. sample_max = np.argmax(np.abs(template[:, max_ind]))
  364. not_aligned = np.abs(sample_max - nbefore) >= auto_trash_misalignment_shift
  365. if not_aligned:
  366. auto_trash_list.append(label)
  367. # ~ plot_debug = not_aligned
  368. # ~ plot_debug = True
  369. plot_debug = False
  370. # ~ plot_debug = label in (23, )
  371. if plot_debug:
  372. import matplotlib.pyplot as plt
  373. fig, axs = plt.subplots(nrows=2)
  374. ax = axs[0]
  375. wfs_flat = template.T.flatten()
  376. ax.plot(wfs_flat)
  377. for c in range(template.shape[1]):
  378. ax.axvline(c * (nbefore + nafter) + nbefore, color="k", ls="--")
  379. if c == max_ind:
  380. ax.axvline(c * (nbefore + nafter) + sample_max, color="b")
  381. ax.set_title(
  382. f"label={label} not_aligned{not_aligned} chan_inds={chan_inds} chan={chan_inds[max_ind]} max_ind{max_ind}"
  383. )
  384. ax = axs[1]
  385. ax.plot(template[:, max_ind])
  386. ax.axvline(sample_max)
  387. ax.axvline(nbefore, color="r", ls="--")
  388. plt.show()
  389. # ~ print('auto_trash_list', auto_trash_list)
  390. for label in auto_trash_list:
  391. (inds,) = np.nonzero(clean_peak_labels == label)
  392. clean_peak_labels[inds] = -label
  393. return clean_peak_labels, peak_sample_shifts
  394. def remove_duplicates(
  395. wfs_arrays, noise_levels, peak_labels, num_samples, num_chans, cosine_threshold=0.975, sparsify_threshold=0.99
  396. ):
  397. num_templates = len(wfs_arrays.keys())
  398. templates = np.zeros((num_templates, num_samples, num_chans), dtype=np.float32)
  399. # All of this is to sparsity the templates
  400. for t, wfs in wfs_arrays.items():
  401. templates[t] = np.median(wfs, axis=0)
  402. is_silent = templates[t].std(0) < 0.1 * noise_levels
  403. templates[t, :, is_silent] = 0
  404. channel_norms = np.linalg.norm(templates[t], axis=0) ** 2
  405. total_norm = np.linalg.norm(templates[t]) ** 2
  406. idx = np.argsort(channel_norms)[::-1]
  407. explained_norms = np.cumsum(channel_norms[idx] / total_norm)
  408. channel = np.searchsorted(explained_norms, sparsify_threshold)
  409. active_channels = np.sort(idx[:channel])
  410. templates[t, :, idx[channel:]] = 0
  411. from sklearn.metrics.pairwise import cosine_similarity
  412. similarities = cosine_similarity(templates.reshape(num_templates, -1))
  413. # Set the diagonal to -1
  414. for i in range(num_templates):
  415. similarities[i, i] = -1
  416. similar_templates = np.nonzero(similarities > cosine_threshold)
  417. new_labels = peak_labels.copy()
  418. labels = np.unique(new_labels)
  419. labels = labels[labels >= 0]
  420. for x, y in zip(similar_templates[0], similar_templates[1]):
  421. mask = new_labels == y
  422. new_labels[mask] = x
  423. labels = np.unique(new_labels)
  424. labels = labels[labels >= 0]
  425. return labels, new_labels
  426. def remove_duplicates_via_matching(
  427. waveform_extractor,
  428. peak_labels,
  429. method_kwargs={},
  430. job_kwargs={},
  431. tmp_folder=None,
  432. method="circus-omp-svd",
  433. ):
  434. from spikeinterface.sortingcomponents.matching import find_spikes_from_templates
  435. from spikeinterface.core import BinaryRecordingExtractor
  436. from spikeinterface.core import NumpySorting
  437. from spikeinterface.core import extract_waveforms
  438. from spikeinterface.core import get_global_tmp_folder
  439. import string, random, shutil, os
  440. from pathlib import Path
  441. job_kwargs = fix_job_kwargs(job_kwargs)
  442. if waveform_extractor.is_sparse():
  443. sparsity = waveform_extractor.sparsity.mask
  444. templates = waveform_extractor.get_all_templates(mode="median").copy()
  445. nb_templates = len(templates)
  446. duration = waveform_extractor.nbefore + waveform_extractor.nafter
  447. fs = waveform_extractor.recording.get_sampling_frequency()
  448. num_chans = waveform_extractor.recording.get_num_channels()
  449. if waveform_extractor.is_sparse():
  450. for count, unit_id in enumerate(waveform_extractor.sorting.unit_ids):
  451. templates[count][:, ~sparsity[count]] = 0
  452. zdata = templates.reshape(nb_templates, -1)
  453. padding = 2 * duration
  454. blanck = np.zeros(padding * num_chans, dtype=np.float32)
  455. if tmp_folder is None:
  456. tmp_folder = get_global_tmp_folder()
  457. tmp_folder.mkdir(parents=True, exist_ok=True)
  458. tmp_filename = tmp_folder / "tmp.raw"
  459. f = open(tmp_filename, "wb")
  460. f.write(blanck)
  461. f.write(zdata.flatten())
  462. f.write(blanck)
  463. f.close()
  464. recording = BinaryRecordingExtractor(tmp_filename, num_channels=num_chans, sampling_frequency=fs, dtype="float32")
  465. recording = recording.set_probe(waveform_extractor.recording.get_probe())
  466. recording.annotate(is_filtered=True)
  467. margin = 2 * max(waveform_extractor.nbefore, waveform_extractor.nafter)
  468. half_marging = margin // 2
  469. chunk_size = duration + 3 * margin
  470. local_params = method_kwargs.copy()
  471. local_params.update({"waveform_extractor": waveform_extractor, "amplitudes": [0.975, 1.025], "omp_min_sps": 1e-3})
  472. spikes_per_units, counts = np.unique(waveform_extractor.sorting.to_spike_vector()["unit_index"], return_counts=True)
  473. indices = np.argsort(counts)
  474. ignore_ids = []
  475. similar_templates = [[], []]
  476. for i in indices:
  477. t_start = padding + i * duration
  478. t_stop = padding + (i + 1) * duration
  479. sub_recording = recording.frame_slice(t_start - half_marging, t_stop + half_marging)
  480. local_params.update({"ignored_ids": ignore_ids + [i]})
  481. spikes, computed = find_spikes_from_templates(
  482. sub_recording, method=method, method_kwargs=local_params, extra_outputs=True, **job_kwargs
  483. )
  484. if method == "circus-omp-svd":
  485. local_params.update(
  486. {
  487. "overlaps": computed["overlaps"],
  488. "templates": computed["templates"],
  489. "norms": computed["norms"],
  490. "temporal": computed["temporal"],
  491. "spatial": computed["spatial"],
  492. "singular": computed["singular"],
  493. "units_overlaps": computed["units_overlaps"],
  494. "unit_overlaps_indices": computed["unit_overlaps_indices"],
  495. "sparsity_mask": computed["sparsity_mask"],
  496. }
  497. )
  498. elif method == "circus-omp":
  499. local_params.update(
  500. {
  501. "overlaps": computed["overlaps"],
  502. "templates": computed["templates"],
  503. "norms": computed["norms"],
  504. "sparsities": computed["sparsities"],
  505. }
  506. )
  507. valid = (spikes["sample_index"] >= half_marging) * (spikes["sample_index"] < duration + half_marging)
  508. if np.sum(valid) > 0:
  509. if np.sum(valid) == 1:
  510. j = spikes[valid]["cluster_index"][0]
  511. ignore_ids += [i]
  512. similar_templates[1] += [i]
  513. similar_templates[0] += [j]
  514. elif np.sum(valid) > 1:
  515. similar_templates[0] += [-1]
  516. ignore_ids += [i]
  517. similar_templates[1] += [i]
  518. new_labels = peak_labels.copy()
  519. labels = np.unique(new_labels)
  520. labels = labels[labels >= 0]
  521. for x, y in zip(similar_templates[0], similar_templates[1]):
  522. mask = new_labels == y
  523. new_labels[mask] = x
  524. labels = np.unique(new_labels)
  525. labels = labels[labels >= 0]
  526. del recording, sub_recording, local_params, waveform_extractor
  527. os.remove(tmp_filename)
  528. return labels, new_labels
  529. def remove_duplicates_via_dip(wfs_arrays, peak_labels, dip_threshold=1, cosine_threshold=None):
  530. import sklearn
  531. from spikeinterface.sortingcomponents.clustering.isocut5 import isocut5
  532. new_labels = peak_labels.copy()
  533. keep_merging = True
  534. fused = {}
  535. templates = {}
  536. similarities = {}
  537. diptests = {}
  538. cosine = 0
  539. for i in wfs_arrays.keys():
  540. fused[i] = [i]
  541. while keep_merging:
  542. min_dip = np.inf
  543. to_merge = None
  544. labels = np.unique(new_labels)
  545. labels = labels[labels >= 0]
  546. for i in labels:
  547. if len(fused[i]) > 1:
  548. all_data_i = np.vstack([wfs_arrays[c] for c in fused[i]])
  549. else:
  550. all_data_i = wfs_arrays[i]
  551. n_i = len(all_data_i)
  552. if n_i > 0:
  553. if i in templates:
  554. t_i = templates[i]
  555. else:
  556. t_i = np.median(all_data_i, axis=0).flatten()
  557. templates[i] = t_i
  558. data_i = all_data_i.reshape(n_i, -1)
  559. if i not in similarities:
  560. similarities[i] = {}
  561. if i not in diptests:
  562. diptests[i] = {}
  563. for j in labels[i + 1 :]:
  564. if len(fused[j]) > 1:
  565. all_data_j = np.vstack([wfs_arrays[c] for c in fused[j]])
  566. else:
  567. all_data_j = wfs_arrays[j]
  568. n_j = len(all_data_j)
  569. if n_j > 0:
  570. if j in templates:
  571. t_j = templates[j]
  572. else:
  573. t_j = np.median(all_data_j, axis=0).flatten()
  574. templates[j] = t_j
  575. if cosine_threshold is not None:
  576. if j in similarities[i]:
  577. cosine = similarities[i][j]
  578. else:
  579. cosine = sklearn.metrics.pairwise.cosine_similarity(
  580. t_i[np.newaxis, :], t_j[np.newaxis, :]
  581. )[0][0]
  582. similarities[i][j] = cosine
  583. if cosine_threshold is None or cosine > cosine_threshold:
  584. if j in diptests[i]:
  585. diptest = diptests[i][j]
  586. else:
  587. data_j = all_data_j.reshape(n_j, -1)
  588. v = t_i - t_j
  589. pr_i = np.dot(data_i, v)
  590. pr_j = np.dot(data_j, v)
  591. diptest, _ = isocut5(np.concatenate((pr_i, pr_j)))
  592. diptests[i][j] = diptest
  593. if diptest < min_dip:
  594. min_dip = diptest
  595. to_merge = [i, j]
  596. if min_dip < dip_threshold:
  597. fused[to_merge[0]] += [to_merge[1]]
  598. mask = new_labels == to_merge[1]
  599. new_labels[mask] = to_merge[0]
  600. templates.pop(to_merge[0])
  601. similarities.pop(to_merge[0])
  602. diptests.pop(to_merge[0])
  603. else:
  604. keep_merging = False
  605. labels = np.unique(new_labels)
  606. labels = labels[labels >= 0]
  607. return labels, new_labels
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...