-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWaveformPlugin.py
316 lines (251 loc) · 11.9 KB
/
WaveformPlugin.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
import numpy as np
from phy import IPlugin, connect
from phy.cluster.views import ManualClusteringView # Base class for phy views
from phy.plot.plot import PlotCanvas
from phy.plot.visuals import PlotVisual
from phy.utils import emit, connect, unconnect, Bunch
class SingleWaveformView(ManualClusteringView):
plot_canvas_class = PlotCanvas
def __init__(self, controller):
super(SingleWaveformView, self).__init__()
self.controller = controller
self.waveform = None
self.n_waveform = 300
self.channel_id = None
self.color = (0.03, 0.57, 0.98, .75)
self.data_bounds = None
self.canvas.set_layout('stacked', n_plots=1)
self.visual = PlotVisual()
self.canvas.add_visual(self.visual)
self.line_x = np.zeros(2)
self.line_y = np.zeros(2)
self.count_points = 0
def on_select(self, cluster_ids, **kwargs):
# We don't display anything if no clusters are selected.
if not cluster_ids:
return
self.visual.reset_batch()
self.cluster_ids = cluster_ids
spike_ids = self.controller.selector(self.n_waveform, [self.cluster_ids[0]])
data = self.controller.model.get_waveforms(spike_ids, None) # n_spikes, n_samples, n_channels
if data is not None:
data = data - np.median(data, axis=1)[:, np.newaxis, :]
# Filter the waveforms.
if data is not None:
data = self.controller.raw_data_filter.apply(data, axis=1)
assert data.ndim == 3 # n_spikes, n_samples, n_channels
self.waveform = Bunch(
data=data,
channel_ids=np.arange(np.size(data, 2)),
)
# self.channel_id = self.controller.get_best_channel(self.cluster_ids[0])
# Select the channel id with largest amplitude instead of using the API's method (sometimes API is wrong)
mean_waveform = np.mean(self.waveform.data, axis=0)
amplitude = [np.max(mean_waveform[:,k])-np.min(mean_waveform[:,k]) for k in range(np.size(mean_waveform, 1))]
self.channel_id = np.argmax(amplitude)
y = self.waveform.data[:, :, self.waveform.channel_ids == self.channel_id]
y = np.squeeze(y).transpose()
x = np.arange(np.size(y, 0))
self.data_bounds = (x[0], y.min(axis=(0, 1)), x[-1], y.max(axis=(0, 1)))
for k in range(np.min((self.n_waveform, np.size(y, 1)))):
self.visual.add_batch_data(
x=x, y=y[:, k], color=self.color, data_bounds=self.data_bounds, box_index=0)
self.canvas.update_visual(self.visual)
self.canvas.update()
def on_select_channel(self, waveformView=None, channel_id=None, key=None, button=None):
if channel_id is None or not self.waveform:
return
self.visual.reset_batch()
self.channel_id = channel_id
y = self.waveform.data[:, :, self.waveform.channel_ids == self.channel_id]
y = np.squeeze(y).transpose()
x = np.arange(np.size(y, 0))
self.data_bounds = (x[0], y.min(axis=(0, 1)), x[-1], y.max(axis=(0, 1)))
for k in range(np.min((self.n_waveform, np.size(y, 1)))):
self.visual.add_batch_data(
x=x, y=y[:, k], color=self.color, data_bounds=self.data_bounds, box_index=0)
self.canvas.update_visual(self.visual)
self.canvas.update()
def on_mouse_click(self, e):
if not self.data_bounds:
return
if 'Control' in e.modifiers:
layout = getattr(self.canvas, 'layout', None)
box_size_x, box_size_y = layout.box_size
box, pos = layout.box_map(e.pos)
x = pos[0] * box_size_x * (self.data_bounds[2] - self.data_bounds[0]) / 2 + (
self.data_bounds[0] + self.data_bounds[2]) / 2
y = pos[1] * box_size_y * (self.data_bounds[3] - self.data_bounds[1]) / (1 + box_size_y) + (
self.data_bounds[3] - self.data_bounds[1]) / (1 + box_size_y) + self.data_bounds[1]
if self.count_points == 0:
self.count_points = 1
self.line_x[0] = x
self.line_y[0] = y
elif self.count_points == 1:
self.count_points = 0
self.line_x[1] = x
self.line_y[1] = y
self.draw_line()
elif self.count_points >= 2:
self.count_points = 1
self.line_x[0] = x
self.line_y[0] = y
def draw_line(self):
color = [1, 1, 1, 1]
data = np.squeeze(self.waveform.data[:, :, self.waveform.channel_ids == self.channel_id])
labels = np.zeros(np.size(data, 0))
x_start = min(self.line_x)
x_end = max(self.line_x)
range_start = np.max([0, np.int64(np.floor(x_start))])
range_end = np.min([np.size(data, 1) - 1, np.int64(np.ceil(x_end))])
for k in range(np.size(data, 0)):
if np.max(self.line_y)<np.min(data[k,range_start:range_end+1]) or np.min(self.line_y)>np.max(data[k,range_start:range_end+1]):
continue
for j in range(range_start, range_end):
if self.is_intersect(
np.array([self.line_x[0], self.line_y[0]]),
np.array([self.line_x[1], self.line_y[1]]),
np.array([j, data[k, j]]),
np.array([j + 1, data[k, j + 1]])
):
labels[k] = 1
continue
self.visual.reset_batch()
y = self.waveform.data[:, :, self.waveform.channel_ids == self.channel_id]
y = np.squeeze(y).transpose()
x = np.arange(np.size(y, 0))
self.data_bounds = (x[0], y.min(axis=(0, 1)), x[-1], y.max(axis=(0, 1)))
self.visual.add_batch_data(
x=self.line_x, y=self.line_y, color=color, data_bounds=self.data_bounds, box_index=0)
for k in range(np.min((self.n_waveform, np.size(y, 1)))):
if labels[k] == 0:
self.visual.add_batch_data(
x=x, y=y[:, k], color=self.color, data_bounds=self.data_bounds, box_index=0)
else:
self.visual.add_batch_data(
x=x, y=y[:, k], color=color, data_bounds=self.data_bounds, box_index=0)
self.canvas.update_visual(self.visual)
self.canvas.update()
def is_intersect(self, P1, P2, Q1, Q2):
if max(P1[0], P2[0]) < min(Q1[0], Q2[0]) \
or max(Q1[0], Q2[0]) < min(P1[0], P2[0]) \
or max(P1[1], P2[1]) < min(Q1[1], Q2[1]) \
or max(Q1[1], Q2[1]) < min(P1[1], P2[1]):
return False
P1Q1 = np.zeros(3)
P1P2 = np.zeros(3)
P1Q2 = np.zeros(3)
P1Q1[:2] = Q1 - P1
P1P2[:2] = P2 - P1
P1Q2[:2] = Q2 - P1
P1Q1[2] = 0
P1P2[2] = 0
P1Q2[2] = 0
a1 = np.cross(P1Q1, P1P2)
a2 = np.cross(P1Q2, P1P2)
if np.sign(a1[2] * a2[2]) >= 0:
return False
# swap P and Q, repeat the procedures
temp = P1
P1 = Q1
Q1 = temp
temp = P2
P2 = Q2
Q2 = temp
P1Q1[:2] = Q1 - P1
P1P2[:2] = P2 - P1
P1Q2[:2] = Q2 - P1
P1Q1[2] = 0
P1P2[2] = 0
P1Q2[2] = 0
a1 = np.cross(P1Q1, P1P2)
a2 = np.cross(P1Q2, P1P2)
if np.sign(a1[2] * a2[2]) >= 0:
return False
return True
def get_split_spike_ids(self):
spike_ids = self.controller.get_spike_ids(self.cluster_ids[0])
data = self.controller.model.get_waveforms(spike_ids, [self.channel_id]) # n_spikes, n_samples, n_channels
# Load the waveforms, either from the raw data directly, or from the _phy_spikes* files.
if data is not None:
data = data - np.median(data, axis=1)[:, np.newaxis, :]
# Filter the waveforms.
if data is not None:
data = self.controller.raw_data_filter.apply(data, axis=1)
data = np.squeeze(data)
ind = []
x_start = min(self.line_x)
x_end = max(self.line_x)
range_start = np.max([0, np.int64(np.floor(x_start))])
range_end = np.min([np.size(data, 1) - 1, np.int64(np.ceil(x_end))])
for k in range(np.size(data, 0)):
if np.max(self.line_y)<np.min(data[k,range_start:range_end+1]) or np.min(self.line_y)>np.max(data[k,range_start:range_end+1]):
continue
for j in range(range_start, range_end):
if self.is_intersect(
np.array([self.line_x[0], self.line_y[0]]),
np.array([self.line_x[1], self.line_y[1]]),
np.array([j, data[k, j]]),
np.array([j + 1, data[k, j + 1]])
):
ind.append(k)
continue
return spike_ids[ind]
def on_request_split(self, sender=None):
return np.unique(self.get_split_spike_ids())
def split_noise(self):
spike_ids = self.get_split_spike_ids()
if len(spike_ids) == 0:
print('No spike selected!')
return None
return self.controller.supervisor.split(spike_ids)
class SingleWaveformViewPlugin(IPlugin):
def attach_to_controller(self, controller):
def create_single_waveform_view():
"""A function that creates and returns a view."""
view = SingleWaveformView(controller)
connect(view.on_request_split)
connect(view.on_select_channel)
@connect(sender=view)
def on_view_attached(view_, gui):
# NOTE: this callback function is called in SingleWaveformView.attach().
@view.actions.add(prompt=True, prompt_default=lambda: str(view.n_waveform))
def change_n_waveforms(n_waveform):
"""Change the number of spikes displayed in the SingleWaveformView."""
view.n_waveform = n_waveform
view.on_select(view.channel_id)
@view.actions.add(prompt=True, prompt_default=lambda: str(view.channel_id), alias='ch')
def change_channel_id(channel_id):
"""Change the channel id displayed in the SingleWaveformView."""
view.on_select_channel(channel_id=channel_id)
view.actions.separator()
@connect
def on_split_noise(sender):
up = view.split_noise()
if not up:
return
idx0_count = np.sum(up.spike_clusters == up.added[0])
idx1_count = np.sum(up.spike_clusters == up.added[1])
old_cluster_id = up.deleted[0]
noise_cluster_id = up.added[np.argmin([idx0_count, idx1_count])]
good_cluster_id = up.added[np.argmax([idx0_count, idx1_count])]
controller.supervisor.label('group', 'noise', cluster_ids=[noise_cluster_id])
# controller.supervisor.cluster_meta.set('group', [noise_cluster_id], 'noise') # this code does not save history for undo action
controller.supervisor.select(good_cluster_id)
if good_cluster_id == old_cluster_id:
view.on_select(good_cluster_id)
@connect(sender=view)
def on_close_view(view, gui):
unconnect(view.on_select_channel)
unconnect(view.on_request_split)
unconnect(on_split_noise)
return view
controller.view_creator['SingleWaveformView'] = create_single_waveform_view
@connect(sender=controller)
def on_gui_ready(sender, gui):
"""This is called when the GUI and all objects are fully loaded.
This is to make sure that controller.supervisor is properly defined.
"""
@controller.supervisor.actions.add(shortcut='s')
def split_noise():
emit('split_noise', controller)