-
Notifications
You must be signed in to change notification settings - Fork 17
/
hs2.py
1040 lines (919 loc) · 44.4 KB
/
hs2.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
from __future__ import division
from __future__ import absolute_import
import logging
import pandas as pd
import numpy as np
import h5py
import os
import math
from .detection_localisation.detect import detectData
from matplotlib import pyplot as plt
# from sklearn.cluster import MeanShift # joblib things are broken
from .clustering.mean_shift_ import MeanShift
from sklearn.decomposition import PCA, FastICA, SparsePCA
from os.path import splitext
import warnings
def min_func(x):
return x.min()
def max_func(x):
return x.max()
class HSDetection(object):
""" This class provides a simple interface to the detection, localisation of
spike data from dense multielectrode arrays according to the methods
described in the following papers:
Muthmann, J. O., Amin, H., Sernagor, E., Maccione, A., Panas, D.,
Berdondini, L., ... & Hennig, M. H. (2015). Spike detection for large neural
populations using high density multielectrode arrays. Frontiers in
neuroinformatics, 9.
Hilgen, G., Sorbaro, M., Pirmoradian, S., Muthmann, J. O., Kepiro, I. E.,
Ullo, S., ... & Hennig, M. H. (2017). Unsupervised spike sorting for
large-scale, high-density multielectrode arrays. Cell reports, 18(10),
2521-2532.
Usage:
1. Create a HSDetection object by calling its constructor with a
Probe object and all the detection parameters (see documentation there).
2. Call DetectFromRaw.
3. Save the result, or create a HSClustering object.
"""
def __init__(self, probe, to_localize=True, num_com_centers=1,
cutout_start=None, cutout_end=None,
threshold=20, maa=0, maxsl=None, minsl=None, ahpthr=0,
out_file_name="ProcessedSpikes", file_directory_name="",
decay_filtering=False, save_all=False,
left_cutout_time=1.0, right_cutout_time=2.2,
amp_evaluation_time=0.4, # former minsl
spk_evaluation_time=1.7): # former maxsl
"""
Arguments:
probe -- probe object, with raw data
to_localize -- set False if spikes should only be detected, not
localised (will break sorting)
cutout_start -- deprecated, frame-based version of left_cutout_ms
cutout_end -- deprecated, frame-based version of right_cutout_ms
threshold -- detection threshold
maa -- minimum average amplitude
maxsl -- deprecated, frame-based version of spk_evaluation_time
minsl -- deprecated, frame-based version of amp_evaluation_time
ahpthr --
out_file_name -- base file name (without extension) for the output files
save_all --
left_cutout_ms -- the number of milliseconds, before the spike,
to be included in the spike shape
right_cutout_ms -- the number of milliseconds, after the spike,
to be included in the spike shape
amp_evaluation_time -- the number of milliseconds during which the trace
is integrated, for the purposed of evaluating amplitude, used for later
comparison with maa
spk_evaluation_time -- dead time in ms after spike peak, used for
further testing
"""
self.probe = probe
self.cutout_start = self._deprecate_or_convert(
cutout_start, left_cutout_time, 'cutout_start', 'left_cutout_time')
self.cutout_end = self._deprecate_or_convert(
cutout_end, right_cutout_time, 'cutout_end', 'right_cutout_time')
self.minsl = self._deprecate_or_convert(
minsl, amp_evaluation_time, 'minsl', 'amp_evaluation_time')
self.maxsl = self._deprecate_or_convert(
maxsl, spk_evaluation_time, 'maxsl', 'spk_evaluation_time')
self.to_localize = to_localize
self.cutout_length = self.cutout_start + self.cutout_end + 1
self.threshold = threshold
self.maa = maa
self.ahpthr = ahpthr
self.decay_filtering = decay_filtering
self.num_com_centers = num_com_centers
self.sp_flat = None
self.spikes = None
# Make directory for results if it doesn't exist
os.makedirs(file_directory_name, exist_ok=True)
if out_file_name[-4:] == ".bin":
file_path = file_directory_name + out_file_name
self.out_file_name = file_path
else:
file_path = os.path.join(file_directory_name, out_file_name)
self.out_file_name = file_path + ".bin"
self.save_all = save_all
def _deprecate_or_convert(self, old_var, new_var, old_name, new_name):
if old_var is not None:
warnings.warn("{} is deprecated and will be removed. ".format(old_name) +
"Set {} instead (in milliseconds). ".format(new_name) +
"{} takes priority over {}!".format(old_name, new_name))
return int(old_var)
else:
return int(new_var * self.probe.fps / 1000 + 0.5)
def SetAddParameters(self, dict_of_new_parameters):
"""
Adds and merges dict_of_new_parameters with the current fields of the
object. Uses the PEP448 convention to group two dics together.
"""
self.__dict__.update(dict_of_new_parameters)
def LoadDetected(self):
"""
Reads a binary file with spikes detected with the DetectFromRaw()
method. The file name is contained in HSDetection.out_file_name.
"""
if os.stat(self.out_file_name).st_size == 0:
shapecache = np.asarray([]).reshape(0, 5)
logging.warn(
"Loading an empty file {} . This usually happens " +
"when no spikes were detected due to the detection parameters" +
" being set too strictly".format(self.out_file_name))
else:
try:
del self.spikes
except AttributeError:
pass
if self.sp_flat is not None:
del self.sp_flat
self.sp_flat = np.memmap(self.out_file_name, dtype=np.int32,
mode="r")
assert self.sp_flat.shape[0] // (self.cutout_length + 5) is not \
self.sp_flat.shape[0] / (self.cutout_length + 5), \
"spike data has wrong dimensions" # ???
shapecache = self.sp_flat.reshape((-1, self.cutout_length + 5))
self.spikes = pd.DataFrame({'ch': shapecache[:, 0],
't': shapecache[:, 1],
'Amplitude': shapecache[:, 2],
'x': shapecache[:, 3] / 1000,
'y': shapecache[:, 4] / 1000,
'Shape': list(shapecache[:, 5:])
}, copy=False)
self.IsClustered = False
print('Detected and read ' + str(self.spikes.shape[0]) + ' spikes.')
def DetectFromRaw(self, load=False, nFrames=None,
tInc=50000, recording_duration=None):
"""
This function is a wrapper of the C function `detectData`. It takes
the raw data file, performs detection and localisation, saves the result
to HSDetection.out_file_name and loads the latter into memory by calling
LoadDetected if load=True.
Arguments:
load -- bool: load the detected spikes when finished?
"""
if nFrames is not None:
warnings.warn("nFrames is deprecated and will be removed. Leave " +
"this out if you want to read the whole recording, " +
"or set max_duration to set the limit (in seconds).")
elif recording_duration is not None:
nFrames = int(recording_duration * self.probe.fps)
detectData(probe=self.probe,
file_name=str.encode(self.out_file_name[:-4]),
to_localize=self.to_localize,
sf=self.probe.fps,
thres=self.threshold,
cutout_start=self.cutout_start,
cutout_end=self.cutout_end,
maa=self.maa, maxsl=self.maxsl, minsl=self.minsl,
ahpthr=self.ahpthr, num_com_centers=self.num_com_centers,
decay_filtering=self.decay_filtering,
verbose=self.save_all,
nFrames=nFrames, tInc=tInc)
if load:
# reload data into memory (detect saves it on disk)
self.LoadDetected()
def PlotData(self, length, frame, channel, ax=None, window_size=200):
"""
Draw a figure with an electrode and its neighbours, showing the raw
traces and events. Note that this requires loading the raw data in
memory again.
Arguments:
length -- amount of data to be shown
frame -- frame to be analyzed
channel -- channel where the graph is centered (contains a red dot)
ax -- a matplotlib axes object where to draw. Defaults to current axis.
window_size -- number of samples shown around a spike
"""
pos, neighs = self.probe.positions, self.probe.neighbors
cutlen = length
dst = np.abs(pos[channel][0] - pos[neighs[channel]][:, 0])
interdistance = np.min(dst[dst > 0])
if ax is None:
ax = plt.gca()
# scatter of the large grey balls for electrode location
x = pos[[neighs[channel], 0]]
y = pos[[neighs[channel], 1]]
plt.scatter(x, y, s=1600, alpha=0.2)
# electrode numbers
for i, txt in enumerate(neighs[channel]):
ax.annotate(txt, (x[i], y[i]))
ws = window_size // 2
t1 = np.max((0, frame - ws))
t2 = frame + ws
scale = interdistance / 110.
trange = (np.arange(t1, t2) - frame) * scale
start_bluered = frame - t1 - self.cutout_start
trange_bluered = trange[start_bluered:start_bluered + cutlen]
trange_bluered = np.arange(-self.cutout_start,
-self.cutout_start + cutlen) * scale
data = self.probe.Read(t1, t2).reshape(
(t2 - t1, self.probe.num_channels))
# grey and blue traces
for n in neighs[channel]:
col = 'g' if n in self.probe.masked_channels else 'b'
plt.plot(pos[n][0] + trange,
pos[n][1] + data[:, n] * scale, 'gray')
plt.plot(pos[n][0] + trange_bluered,
pos[n][1] + data[start_bluered:start_bluered + cutlen,
n] * scale, col)
# red overlay for central channel
plt.scatter(pos[channel][0], pos[channel][1], s=200, c='r')
# # red dot of event location
# plt.scatter(event.x, event.y, s=80, c='r')
def PlotTracesChannels(self, eventid, ax=None, window_size=100,
show_channels=True, ascale=1,
show_channel_numbers=True, show_loc=True):
"""
Draw a figure with an electrode and its neighbours, showing the raw
traces and events. Note that this requires loading the raw data in
memory again.
Arguments:
eventid -- centers, spatially and temporally, the plot to a specific
event id.
ax -- a matplotlib axes object where to draw. Defaults to current axis.
window_size -- number of samples shown around a spike
"""
pos, neighs = self.probe.positions, self.probe.neighbors
event = self.spikes.loc[eventid]
print("Spike detected at channel: ", event.ch)
print("Spike detected at frame: ", event.t)
print("Spike localised in position", event.x, event.y)
cutlen = len(event.Shape)
assert window_size > cutlen, "window_size is too small"
dst = np.abs(pos[event.ch][0] - pos[neighs[event.ch]][:, 0])
interdistance = np.min(dst[dst > 0])
if ax is None:
ax = plt.gca()
# scatter of the large grey balls for electrode location
x = pos[(neighs[event.ch], 0)]
y = pos[(neighs[event.ch], 1)]
if show_channels:
plt.scatter(x, y, s=1600, alpha=0.2)
ws = window_size // 2
t1 = np.max((0, event.t - ws))
t2 = event.t + ws
scale = interdistance / 110. * ascale
trange = (np.arange(t1, t2) - event.t) * scale
start_bluered = event.t - t1 - self.cutout_start
trange_bluered = trange[start_bluered:start_bluered + cutlen]
print("trange", trange.shape)
assert start_bluered + cutlen < window_size, "window_size is too small"
data = self.probe.Read(t1, t2).reshape(
(t2 - t1, self.probe.num_channels))
print("Data", data.shape)
ys = np.zeros(len(neighs[event.ch]))
for i, n in enumerate(neighs[event.ch]):
if data[0, n] > 200:
ys[i] = -data[0, n]
# grey and blue traces
for i, n in enumerate(neighs[event.ch]):
dist_from_max = math.sqrt((pos[n][0] - pos[event.ch][0])**2 + (pos[n][1] - pos[event.ch][1])**2)
col = 'g' if n in self.probe.masked_channels else 'b'
col = 'orange' if dist_from_max <= self.probe.inner_radius and n not in self.probe.masked_channels else col
plt.plot(pos[n][0] + trange,
pos[n][1] + (data[:, n] + ys[i]) * scale, 'gray')
plt.plot(pos[n][0] + trange_bluered,
pos[n][1] + (data[start_bluered:start_bluered + cutlen,
n] + ys[i]) * scale, col)
# red overlay for central channel
plt.plot(pos[event.ch][0] + trange_bluered,
pos[event.ch][1] + (event.Shape + ys[
np.where(neighs[event.ch] == event.ch)[0]]) * scale, 'r')
inner_radius_circle = plt.Circle((pos[event.ch][0], pos[event.ch][1]),
self.probe.inner_radius,
color='red', fill=False)
ax.add_artist(inner_radius_circle)
# red dot of event location
if show_loc:
plt.scatter(event.x, event.y, s=80, c='r')
# electrode numbers
if show_channel_numbers:
for i, txt in enumerate(neighs[event.ch]):
ax.annotate(txt, (x[i], y[i]))
return ax
def PlotDensity(self, binsize=1., invert=False, ax=None):
raise NotImplementedError()
if ax is None:
ax = plt.gca()
x, y = self.spikes.x, self.spikes.y
if invert:
x, y = y, x
binsx = np.arange(x.min(), x.max(), binsize)
binsy = np.arange(y.min(), y.max(), binsize)
h, xb, yb = np.histogram2d(x, y, bins=[binsx, binsy])
ax.imshow(np.log10(h), extent=[xb.min(), xb.max(), yb.min(), yb.max()],
interpolation='none', origin='lower')
return h, xb, yb
def PlotAll(self, invert=False, ax=None, max_show=100000, **kwargs):
"""
Plots all the spikes currently stored in the class, in (x, y) space.
Arguments:
invert -- (boolean, optional) if True, flips x and y
ax -- a matplotlib axes object where to draw. Defaults to current axis.
max_show -- maximum number of spikes to show
**kwargs -- additional arguments are passed to pyplot.scatter
"""
if ax is None:
ax = plt.gca()
x, y = self.spikes.x, self.spikes.y
if invert:
x, y = y, x
if self.spikes.shape[0] > max_show:
inds = np.random.choice(
self.spikes.shape[0], max_show, replace=False)
print('We have ' + str(self.spikes.shape[0]) +
' spikes, only showing ' + str(max_show))
else:
inds = np.arange(self.spikes.shape[0])
ax.scatter(x[inds], y[inds], **kwargs)
return ax
def Cluster(self):
return HSClustering(self)
class HSClustering(object):
""" This class provides an easy interface to the clustering of spikes based
on spike location on the chip and spike waveform, as described in:
Hilgen, G., Sorbaro, M., Pirmoradian, S., Muthmann, J. O., Kepiro, I. E.,
Ullo, S., ... & Hennig, M. H. (2017). Unsupervised spike sorting for
large-scale, high-density multielectrode arrays. Cell reports, 18(10),
2521-2532. """
def __init__(self, arg1, cutout_length=None, **kwargs):
""" The constructor can be called in two ways:
- with a filename or list of filenames as an argument. These should be
either .hdf5 files saved by this class or a previous version of this
class, or .bin files saved by the HSDetection class. In the latter case,
the cutout_length must also be passed as a second argument.
- with an instance of HSDetection as a single argument. """
# store the memmapped shapes
self.shapecache = []
if type(arg1) == str: # case arg1 is a single filename
arg1 = [arg1]
if type(arg1) == list: # case arg1 is a list of filenames
for i, f in enumerate(arg1):
filetype = splitext(f)[-1]
not_first_file = i > 0
if filetype == ".hdf5":
_f = h5py.File(f, 'r')
if 'shapes' in list(_f.keys()):
_f.close()
self.LoadHDF5(f, append=not_first_file, **kwargs)
elif 'Shapes' in list(_f.keys()):
_f.close()
self.LoadHDF5_legacy_detected(f, append=not_first_file,
**kwargs)
elif filetype == ".bin":
if cutout_length is None:
raise ValueError(
"You must pass cutout_length for .bin files.")
self.LoadBin(f, cutout_length, append=not_first_file)
else:
raise IOError(
"File format unknown. Expected .hdf5 or .bin")
else: # we suppose arg1 is an instance of Detection
try: # see if LoadDetected was run
self.spikes = arg1.spikes
except NameError:
arg1.LoadDetected()
self.spikes = arg1.spikes
# this computes average amplitudes, disabled for now
# self.spikes['min_amp'] = self.spikes.Shape.apply(min_func)
self.filelist = [arg1.out_file_name]
self.expinds = [0]
self.IsClustered = False
def CombinedClustering(self, alpha, clustering_algorithm=MeanShift,
cluster_subset=None, **kwargs):
"""
Clusters spikes based on their (x, y) location and on the other features
in HSClustering.features. These are normally principal components of the
spike waveforms, computed by HSClustering.ShapePCA. Cluster memberships
are available as HSClustering.spikes.cl. Cluster information is
available in the HSClustering.clusters dataframe.
Arguments:
alpha -- the weight given to the other features, relative to spatial
components (which have weight 1.)
clustering_algorithm -- a sklearn.cluster class, defaults to
sklearn.cluster.MeanShift. sklearn.cluster.DBSCAN is a possible
alternative. The class passed here has to have a method fit, and a
predict method if cluster_subset is non-zero.
cluster_subset -- Number of spikes used to build clusters, spikes are
then assigned to the nearest by Euclidean distance
**kwargs -- additional arguments are passed to the clustering class.
This may include n_jobs > 1 for parallelisation.
"""
try:
fourvec = np.vstack((self.spikes.x, self.spikes.y,
alpha * self.features.T)).T
except AttributeError:
fourvec = np.vstack((self.spikes.x, self.spikes.y)).T
print("Warning: no PCA or other features available, location only!")
print('Clustering...')
clusterer = clustering_algorithm(**kwargs)
if cluster_subset is not None:
print("Clustering using " + str(cluster_subset) + " out of " +
str(self.spikes.shape[0]) + " spikes...")
inds = np.sort(np.random.choice(self.spikes.shape[0],
int(cluster_subset), replace=False))
clusterer.fit(fourvec[inds])
self.NClusters = len(np.unique(clusterer.labels_))
print("Number of estimated units:", self.NClusters)
print("Predicting cluster labels for",
self.spikes.shape[0], "spikes...")
self.spikes['cl'] = clusterer.predict(fourvec)
else:
print("Clustering " + str(self.spikes.shape[0]) + " spikes...")
self.spikes['cl'] = clusterer.fit_predict(fourvec)
self.NClusters = len(np.unique(self.spikes['cl']))
print("Number of estimated units:", self.NClusters)
# methods like DBSCAN assign '-1' to unclustered data
# here we replace these by a new cluster at the end of the list
if self.spikes.cl.min() == -1:
print("There are", (self.spikes.cl == -1).sum(),
"unclustered events, these are now in cluster number ",
self.NClusters - 1)
self.spikes.loc[self.spikes.cl == -1, 'cl'] = self.NClusters - 1
_cl = self.spikes.groupby(['cl'])
_x_mean = _cl.x.mean()
_y_mean = _cl.y.mean()
# this computes average amplitudes, disabled for now
# _avgAmpl = _cl.min_amp.mean()
_cls = _cl.cl.count()
_color = 1. * np.random.permutation(self.NClusters) / self.NClusters
dic_cls = {'ctr_x': _x_mean,
'ctr_y': _y_mean,
'Color': _color,
'Size': _cls}
# 'AvgAmpl': _avgAmpl
# }
self.clusters = pd.DataFrame(dic_cls)
self.IsClustered = True
def ShapePCA(self, pca_ncomponents=2, pca_whiten=True, chunk_size=1000000,
normalise=False):
"""
Finds the principal components (PCs) of spike shapes contained in the
class, and saves them to HSClustering.features, to be used for
clustering.
Arguments -- pca_ncomponents: number of PCs to be used (default 2)
pca_whiten -- whiten data before PCA.
chunk_size -- maximum number of shapes to be used to find PCs, default 1 million.
"""
_pca = PCA(n_components=pca_ncomponents, whiten=pca_whiten)
if self.spikes.shape[0] > chunk_size:
print("Fitting PCA using", chunk_size, "out of ",
self.spikes.shape[0], "spikes...")
inds = np.sort(np.random.choice(self.spikes.shape[0], chunk_size,
replace=False))
if normalise:
print("...normalising shapes by peak...")
s = [row.Shape / row.Shape.min()
for row in self.spikes.loc[inds].itertuples()]
else:
s = self.spikes.Shape.loc[inds].values.tolist()
_pca.fit(np.array(s))
else:
print("Fitting PCA using " + str(self.spikes.shape[0]) + " spikes...")
if normalise:
s = [row.Shape / row.Shape.min()
for row in self.spikes.itertuples()]
else:
s = self.spikes.Shape.values.tolist()
_pca.fit(s)
_pcs = np.empty((self.spikes.shape[0], pca_ncomponents))
print("...projecting...")
for i in range(self.spikes.shape[0] // chunk_size + 1):
# is this the best way? Warning: Pandas slicing with .loc is different!
# print(i*chunk_size, (i + 1)*chunk_size)
if normalise:
s = [row.Shape / row.Shape.min() for row in self.spikes.loc[
i * chunk_size:(i + 1) * chunk_size - 1].itertuples()]
else:
s = self.spikes.Shape.loc[i * chunk_size:(i + 1) * chunk_size - 1].values.tolist()
_pcs[i * chunk_size:(i + 1) * chunk_size, :] = _pca.transform(s)
self.pca = _pca
self.features = _pcs
print("...done")
# return _pcs
def ShapeSparsePCA(self, pca_ncomponents=2, chunk_size=1000000):
"""
Finds the principal components (PCs) of spike shapes contained in the
class, and saves them to HSClustering.features, to be used for
clustering.
Arguments -- pca_ncomponents: number of PCs to be used (default 2)
chunk_size -- maximum number of
shapes to be used to find PCs, default 1 million.
"""
pca = SparsePCA(n_components=pca_ncomponents)
if self.spikes.shape[0] > 1e6:
print("Fitting PCA using 1e6 out of",
self.spikes.shape[0], "spikes...")
inds = np.random.choice(self.spikes.shape[0], int(1e6),
replace=False)
pca.fit(self.spikes.Shape.loc[inds].values.tolist()) # so we need tolist here?
else:
print("Fitting PCA using", self.spikes.shape[0], "spikes...")
pca.fit(self.spikes.Shape.value.tolist())
self.pca = pca
_pcs = np.empty((self.spikes.shape[0], pca_ncomponents))
for i in range(self.spikes.shape[0] // chunk_size + 1):
# is this the best way? Warning: Pandas slicing with .loc is different!
print(i * chunk_size, (i + 1) * chunk_size)
_pcs[i * chunk_size:(i + 1) * chunk_size, :] = pca.transform(np.array(
self.spikes.Shape.loc[
i * chunk_size:(i + 1) * chunk_size - 1].tolist()))
self.features = _pcs
return _pcs
def ShapeICA(self, ica_ncomponents=2, ica_whiten=True, chunk_size=1000000):
"""
Finds the principal components (PCs) of spike shapes contained in the
class, and saves them to HSClustering.features, to be used for
clustering.
Arguments -- ica_ncomponents: number of ICs to be used (default 2)
ica_whiten -- whiten data before ICA. chunk_size: maximum number of
shapes to be used to find ICs, default 1 million.
"""
ica = FastICA(n_components=ica_ncomponents, whiten=ica_whiten)
if self.spikes.shape[0] > 1e6:
print("Fitting ICA using 1e6 out of",
self.spikes.shape[0], "spikes...")
inds = np.random.choice(self.spikes.shape[0], int(1e6),
replace=False)
ica.fit(self.spikes.Shape.loc[inds].values.tolist())
else:
print("Fitting iCA using", self.spikes.shape[0], "spikes...")
ica.fit(self.spikes.Shape.tolist())
self.pca = ica
_ics = np.empty((self.spikes.shape[0], ica_ncomponents))
for i in range(self.spikes.shape[0] // chunk_size + 1):
_ics[i * chunk_size:(i + 1) * chunk_size, :] = ica.transform(
self.spikes.Shape.loc[i * chunk_size:(i + 1) * chunk_size - 1].tolist())
self.features = _ics
return _ics
def _savesinglehdf5(self, filename, limits, compression, sampling,
transpose=False):
if limits is not None:
spikes = self.spikes[limits[0]:limits[1]]
else:
spikes = self.spikes
g = h5py.File(filename, 'w')
if transpose:
g.create_dataset("data", data=np.vstack(
(spikes.y, spikes.x)))
else:
g.create_dataset("data", data=np.vstack(
(spikes.x, spikes.y)))
if sampling is not None:
g.create_dataset("Sampling", data=sampling)
g.create_dataset("times", data=spikes.t)
g.create_dataset("ch", data=spikes.ch)
if self.IsClustered:
if transpose:
g.create_dataset("centres",
data=self.clusters[['ctr_y', 'ctr_x']])
else:
g.create_dataset("centres",
data=self.clusters[['ctr_x', 'ctr_y']])
# g.create_dataset("centres", data=self.centers.T)
g.create_dataset("cluster_id", data=spikes.cl)
else:
g.create_dataset("centres", data=[])
g.create_dataset("cluster_id", data=[])
g.create_dataset("exp_inds", data=self.expinds)
# this is still a little slow (and perhaps memory intensive)
# but I have not yet found a better way:
if(not spikes.empty):
cutout_length = spikes.Shape.iloc[0].size
sh_tmp = np.empty((cutout_length, spikes.Shape.size),
dtype=int)
for i, s in enumerate(spikes.Shape):
sh_tmp[:, i] = s
g.create_dataset("shapes", data=sh_tmp, compression=compression)
else:
g.create_dataset("shapes", data=[], compression=compression)
g.close()
def SaveHDF5(self, filename, compression=None, sampling=None,
transpose=False):
"""
Saves data, cluster centres and ClusterIDs to a hdf5 file. Offers
compression of the shapes, 'lzf' appears a good trade-off between speed
and performance.
If filename is a single name, then all will be saved to a single file.
If filename is a list of names of the same length as the number of
experiments, one file per experiment will be saved.
Arguments:
filename -- the names of the file or list of files to be saved.
compression -- passed to HDF5, for compression of shapes only.
sampling -- provide this information to include it in the file.
"""
if sampling is None:
print("# Warning: no sampling rate given, will be set to 0 in the hdf5 file.")
sampling = 0
if type(filename) == str:
self._savesinglehdf5(filename, None, compression, sampling,
transpose)
elif type(filename) == list:
if len(filename) != len(self.expinds):
raise ValueError("Names list length does not correspond to " +
"number of experiments in memory.")
expinds = self.expinds + [len(self.spikes)]
for i, f in enumerate(filename):
self._savesinglehdf5(f, [expinds[i], expinds[i + 1]],
compression, sampling, transpose)
else:
raise ValueError("filename not understood")
def LoadHDF5(self, filename, append=False, chunk_size=1000000, scale=1):
"""
Load data, cluster centres and ClusterIDs from a hdf5 file created with
HS1 folowing clustering.
Arguments:
filename -- file to load from
append -- append to data alreday im memory
chunk_size -- read shapes in chunks of this size to avoid memory
problems
compute_cluster_sizes -- count number of spikes in each unit (slow)
scale -- re-scale shapes by this factor (may be required for HS1 data)
"""
g = h5py.File(filename, 'r')
print('Reading from clustered (HS1 or HS2) file ' + filename)
print("Creating memmapped cache for shapes, reading in chunks of size",
chunk_size, "and converting to integer...")
i = len(self.shapecache)
# self.shapecache.append(np.memmap("tmp"+str(i)+".bin",
# dtype=np.int32, mode="w+",
# shape=g['shapes'].shape[::-1]))
for i in range(g['shapes'].shape[1] // chunk_size + 1):
tmp = (scale * np.transpose(
g['shapes'][:, i * chunk_size:(i + 1) * chunk_size])).astype(np.int32)
inds = np.where(tmp > 20000)[0]
tmp[inds] = 0
print('Read chunk ' + str(i + 1))
if len(inds) > 0:
print('Found', len(inds), 'data points out of linear regime')
self.shapecache[-1][i * chunk_size:(i + 1) * chunk_size] = tmp[:]
self.cutout_length = self.shapecache[-1].shape[1]
print('Events: ', self.shapecache[-1].shape[0])
print('Cut-out size: ', self.cutout_length)
spikes = pd.DataFrame(
{'ch': np.zeros(g['times'].shape[0], dtype=int),
't': g['times'],
'Amplitude': np.zeros(g['times'].shape[0], dtype=int),
'x': g['data'][0, :],
'y': g['data'][1, :],
'Shape': list(self.shapecache[-1])
}, copy=False)
if 'ch' in list(g.keys()):
spikes.ch = g['ch'].value.T
print('Getting spike amplitudes')
spikes['min_amp'] = spikes.Shape.apply(min_func)
spikes['Amplitude'] = spikes['min_amp']
if 'centres' in list(g.keys()):
self.centerz = g['centres'].value
if len(self.centerz) < 5:
print('WARNING Hack: Assuming HS1 data format')
self.centerz = self.centerz.T
self.NClusters = len(self.centerz)
print('Number of clusters: ', self.NClusters)
spikes['cl'] = g['cluster_id']
inds = spikes.groupby(['cl']).cl.count().index
_cl = spikes.groupby(['cl'])
# this computes average amplitudes, disabled for now
# _avgAmpl = np.zeros(self.NClusters)
# _avgAmpl[inds] = _cl.min_amp.mean()
_cls = np.zeros(self.NClusters)
_cls[inds] = _cl.cl.count()
dic_cls = {'ctr_x': self.centerz[:, 0],
'ctr_y': self.centerz[:, 1],
'Color': 1. * np.random.permutation(
self.NClusters) / self.NClusters,
'Size': _cls}
# 'AvgAmpl': _avgAmpl}
self.clusters = pd.DataFrame(dic_cls)
self.IsClustered = True
else:
self.IsClustered = False
g.close()
if append:
self.expinds.append(len(self.spikes))
self.spikes = pd.concat([self.spikes, spikes], ignore_index=True)
self.filelist.append(filename)
else:
self.spikes = spikes
self.expinds = [0]
self.filelist = [filename]
def LoadHDF5_legacy_detected(self, filename, append=False,
chunk_size=1000000, scale=1):
"""
Load data, cluster centres and ClusterIDs from a hdf5 file created with
the HS1 detector.
Arguments:
filename -- file to load from
append -- append to data alreday im memory
chunk_size -- read shapes in chunks of this size to avoid memory
problems
compute_cluster_sizes -- count number of spikes in each unit (slow)
scale -- re-scale shapes by this factor (may be required for HS1 data)
"""
g = h5py.File(filename, 'r')
print('Reading from unclustered HS1 file ' + filename)
if scale == 1:
scale = -1.0 * g['Ascale'].value
print("Creating memmapped cache for shapes, reading in chunks of size",
chunk_size, "and converting to integer...")
i = len(self.shapecache)
self.shapecache.append(np.memmap("tmp" + str(i) + ".bin",
dtype=np.int32, mode="w+",
shape=g['Shapes'].shape))
for i in range(g['Shapes'].shape[0] // chunk_size + 1):
tmp = (scale * np.transpose(
g['Shapes'][i * chunk_size:(i + 1) * chunk_size, :])).astype(np.int32).T
inds = np.where(tmp > 20000)[0]
tmp[inds] = 0
print('Read chunk ' + str(i + 1))
if len(inds) > 0:
print('Found', len(inds), 'data points out of linear regime')
self.shapecache[-1][i * chunk_size:(i + 1) * chunk_size] = tmp[:]
self.cutout_length = self.shapecache[-1].shape[1]
print('Events: ', self.shapecache[-1].shape[0])
print('Cut-out size: ', self.cutout_length)
spikes = pd.DataFrame(
{'ch': np.zeros(g['Times'].shape[0], dtype=int),
't': g['Times'],
'Amplitude': (-g['Amplitudes'][:] * scale).astype(int),
'x': g['Locations'][:, 0],
'y': g['Locations'][:, 1],
'Shape': list(self.shapecache[-1])
}, copy=False)
self.IsClustered = False
g.close()
if append:
self.expinds.append(len(self.spikes))
self.spikes = pd.concat([self.spikes, spikes], ignore_index=True)
self.filelist.append(filename)
else:
self.spikes = spikes
self.expinds = [0]
self.filelist = [filename]
def LoadBin(self, filename, cutout_length, append=False):
"""
Reads a binary file with spikes detected with the DetectFromRaw() method
"""
# sp_flat = np.memmap(filename, dtype=np.int32, mode="r")
# 5 here are the non-shape data columns
print('# loading', filename)
self.shapecache.append(np.memmap(filename,
dtype=np.int32, mode="r").reshape(
(-1, cutout_length + 5)))
assert self.shapecache[-1].shape[0] // (cutout_length + 5) is not \
self.shapecache[-1].shape[0] / (cutout_length + 5), \
"spike data has wrong dimensions" # ???
spikes = pd.DataFrame({
'ch': self.shapecache[-1][:, 0],
't': self.shapecache[-1][:, 1],
'Amplitude': self.shapecache[-1][:, 2],
'x': self.shapecache[-1][:, 3] / 1000,
'y': self.shapecache[-1][:, 4] / 1000,
'Shape': list(self.shapecache[-1][:, 5:])
}, copy=False)
self.IsClustered = False
# this computes average amplitudes, disabled for now
# spikes['min_amp'] = spikes.Shape.apply(min_func)
if append:
self.expinds.append(len(self.spikes))
self.spikes = pd.concat([self.spikes, spikes], ignore_index=True)
self.filelist.append(filename)
else:
self.spikes = spikes
self.expinds = [0]
self.filelist = [filename]
def PlotShapes(self, units, nshapes=100, ncols=4, ax=None, ylim=None,
max_shapes=1000, n_shapes=100):
"""
Plot a sample of the spike shapes contained in a given set of clusters
and their average.
Arguments:
units -- a list of the cluster IDs to be considered.
nshapes -- the number of shapes to plot (default 100).
ncols -- the number of columns under which to distribute the plots.
ax -- a matplotlib axis object (defaults to current axis).
ylim -- limits of the vertical axis of the plots. If None, try to figure
them out.
"""
nrows = np.ceil(len(units) / ncols)
if ax is None:
plt.figure(figsize=(3 * ncols, 3 * nrows))
cutouts = self.spikes.Shape
# all this is to determine suitable ylims TODO probe should provide
yoff = 0
if ylim is None:
meanshape = np.mean(cutouts.loc[:2000], axis=0)
yoff = -meanshape[0]
maxy, miny = meanshape.max() + yoff, meanshape.min() + yoff
varshape = np.var(cutouts.loc[:1000].values, axis=0) # direct not possible, why?
varmin = varshape[np.argmin(meanshape)]
varmax = varshape[np.argmax(meanshape)]
maxy += 4. * np.sqrt(varmax)
miny -= 2. * np.sqrt(varmin)
ylim = [miny, maxy]
for i, cl in enumerate(units):
inds = np.where(self.spikes.cl == cl)[0][:max_shapes]
meanshape = np.mean(cutouts.loc[inds], axis=0)
yoff = -meanshape[0]
if ax is None:
plt.subplot(nrows, ncols, i + 1)
[plt.plot(v - v[0], 'gray', alpha=0.3)
for v in cutouts.loc[inds[:n_shapes]].values]
plt.plot(meanshape + yoff, c=plt.cm.hsv(self.clusters.Color[cl]), lw=4)
# plt.plot(np.mean(cutouts.loc[inds]+yoff, axis=0),
# c=plt.cm.hsv(self.clusters.Color[cl]), lw=4)
plt.ylim(ylim)
plt.title("Cluster " + str(cl))
def PlotAll(self, invert=False, show_labels=False, ax=None,
max_show=200000, fontsize=16, **kwargs):
"""
Plots all the spikes currently stored in the class, in (x, y) space.
If clustering has been performed, each spike is coloured according to
the cluster it belongs to.
Arguments:
invert -- (boolean, optional) if True, flips x and y
show_labels -- (boolean, optional) if True, annotates each cluster
centre with its cluster ID.
ax -- a matplotlib axes object where to draw. Defaults to current axis.
max_show -- maximum number of spikes to show
fontsize -- font size for annotations
**kwargs -- additional arguments are passed to pyplot.scatter
"""
if ax is None:
ax = plt.gca()
x, y = self.spikes.x, self.spikes.y
if invert:
x, y = y, x
if self.spikes.shape[0] > max_show:
inds = np.random.choice(
self.spikes.shape[0], max_show, replace=False)
print('We have ' + str(self.spikes.shape[0]) +
' spikes, only showing ' + str(max_show))
else:
inds = np.arange(self.spikes.shape[0])
c = plt.cm.hsv(self.clusters.Color[self.spikes.cl])
ax.scatter(x[inds], y[inds], c=c[inds], **kwargs)
if show_labels and self.IsClustered:
ctr_x, ctr_y = self.clusters.ctr_x, self.clusters.ctr_y
if invert:
ctr_x, ctr_y = ctr_y, ctr_x
for cl in range(self.NClusters): # TODO why is this here
if ~np.isnan(ctr_y[cl]): # hack, why NaN positions in DBScan?
ax.annotate(
str(cl), [ctr_x[cl], ctr_y[cl]], fontsize=fontsize)
# seems this is a problem when zooming with x/ylim
return ax
def PlotNeighbourhood(self, cl, radius=1, show_cluster_numbers=True,
max_spikes=10000, alpha=0.4, show_unclustered=False,
max_shapes=1000, figsize=(8, 6)):
"""
Plot all units and spikes in the neighbourhood of cluster cl.
Arguments:
cl -- number of te cluster to be shown
radius -- spikes are shown for units this far away from cluster centre
"""
plt.figure(figsize=figsize)
cx, cy = self.clusters['ctr_x'][cl], self.clusters['ctr_y'][cl]
dists = np.sqrt(
(cx - self.clusters['ctr_x'])**2 + (cy - self.clusters['ctr_y'])**2)
clInds = np.where(dists < radius)[0]
ax = []
ax.append(plt.subplot2grid((len(clInds) + 1, 4), (0, 0),
rowspan=len(clInds) + 1,