UnitMatchPy 3.2.9__py3-none-any.whl → 3.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- UnitMatchPy/GUI.py +1 -1
- UnitMatchPy/default_params.py +1 -0
- UnitMatchPy/metric_functions.py +293 -29
- UnitMatchPy/overlord.py +4 -8
- UnitMatchPy/utils.py +103 -96
- unitmatchpy-3.3.1.dist-info/METADATA +137 -0
- {unitmatchpy-3.2.9.dist-info → unitmatchpy-3.3.1.dist-info}/RECORD +10 -10
- {unitmatchpy-3.2.9.dist-info → unitmatchpy-3.3.1.dist-info}/WHEEL +1 -1
- unitmatchpy-3.2.9.dist-info/METADATA +0 -69
- {unitmatchpy-3.2.9.dist-info → unitmatchpy-3.3.1.dist-info}/licenses/LICENSE +0 -0
- {unitmatchpy-3.2.9.dist-info → unitmatchpy-3.3.1.dist-info}/top_level.txt +0 -0
UnitMatchPy/GUI.py
CHANGED
|
@@ -1792,7 +1792,7 @@ def plot_raw_waveforms(unit_a, unit_b, CV):
|
|
|
1792
1792
|
good_channels = nearest_channels(max_site, max_site_mean, channel_pos, clus_info, unit_a, CV[0])
|
|
1793
1793
|
|
|
1794
1794
|
min_x, min_y = channel_pos[session_no_a][good_channels[-2],[1,2]].squeeze()
|
|
1795
|
-
max_x,
|
|
1795
|
+
max_x, maxy = channel_pos[session_no_a][good_channels[1],[1,2]].squeeze()
|
|
1796
1796
|
delta_x = (max_x - min_x) / 2
|
|
1797
1797
|
delta_y = (maxy - min_y) / 18
|
|
1798
1798
|
#may want to change so it find this for both units and selects the most extreme arguments
|
UnitMatchPy/default_params.py
CHANGED
|
@@ -27,6 +27,7 @@ def get_default_param(param = None):
|
|
|
27
27
|
'units_per_shank_thrs' : 15, # threshold for doing per shank drift correction
|
|
28
28
|
'match_threshold' : 0.5, # probability threshold to consider as a match
|
|
29
29
|
'curve_fit_maxfev' : 10000, # max evaluations for decay curve fitting
|
|
30
|
+
'chunk_size' : 500, # row-chunk size for pairwise metric computation
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
tmp['score_vector'] = np.arange(tmp['stepsz']/2 ,1 ,tmp['stepsz'])
|
UnitMatchPy/metric_functions.py
CHANGED
|
@@ -118,7 +118,7 @@ def get_waveforms_mse(avg_waveform, param):
|
|
|
118
118
|
waveform_mse = re_scale(raw_wave_mse_norm)
|
|
119
119
|
return waveform_mse
|
|
120
120
|
|
|
121
|
-
def flip_dim(avg_waveform_per_tp, param):
|
|
121
|
+
def flip_dim(avg_waveform_per_tp, param, n=None):
|
|
122
122
|
"""
|
|
123
123
|
Creates a version of the weighted average waveform per time point, where the x axis is flipped, due to the effect
|
|
124
124
|
where the average position tends to wards the center of the x coords when the wave is decaying
|
|
@@ -135,7 +135,10 @@ def flip_dim(avg_waveform_per_tp, param):
|
|
|
135
135
|
ndarray
|
|
136
136
|
The average waveform per time point with the x axis flipped and not flipped
|
|
137
137
|
"""
|
|
138
|
-
|
|
138
|
+
if n is not None:
|
|
139
|
+
n_units = n
|
|
140
|
+
else:
|
|
141
|
+
n_units = param['n_units']
|
|
139
142
|
spike_width = param['spike_width']
|
|
140
143
|
|
|
141
144
|
flip_dim = np.array((1,)) # BE CAREFUL HERE, Which dimension is the x-axis
|
|
@@ -152,7 +155,7 @@ def flip_dim(avg_waveform_per_tp, param):
|
|
|
152
155
|
|
|
153
156
|
return avg_waveform_per_tp_flip
|
|
154
157
|
|
|
155
|
-
def get_Euclidean_dist(avg_waveform_per_tp_flip,param):
|
|
158
|
+
def get_Euclidean_dist(avg_waveform_per_tp_flip,param, n=None):
|
|
156
159
|
"""
|
|
157
160
|
Calculated the Euclidean distance between the units at each time point and for the flipped axis case
|
|
158
161
|
|
|
@@ -170,7 +173,10 @@ def get_Euclidean_dist(avg_waveform_per_tp_flip,param):
|
|
|
170
173
|
"""
|
|
171
174
|
# Memory-efficient implementation using loops instead of massive tiling
|
|
172
175
|
waveidx = param['waveidx']
|
|
173
|
-
|
|
176
|
+
if n is not None:
|
|
177
|
+
n_units = n
|
|
178
|
+
else:
|
|
179
|
+
n_units = param['n_units']
|
|
174
180
|
|
|
175
181
|
# Extract the relevant slices once
|
|
176
182
|
data_cv0 = avg_waveform_per_tp_flip[:,:,waveidx,0,:] # (3, n_units, len(waveidx), n_flips)
|
|
@@ -186,13 +192,13 @@ def get_Euclidean_dist(avg_waveform_per_tp_flip,param):
|
|
|
186
192
|
unit_i_data = data_cv0[:, i, :, :] # (3, len(waveidx), n_flips)
|
|
187
193
|
unit_j_data = data_cv1[:, j, :, :] # (3, len(waveidx), n_flips)
|
|
188
194
|
|
|
189
|
-
# Check for NaN values
|
|
190
|
-
w = np.isnan(np.abs(unit_i_data[0,:,:] - unit_j_data[0,:,:]))
|
|
191
|
-
|
|
192
195
|
# Compute Euclidean distance between units i and j
|
|
193
196
|
diff = unit_i_data - unit_j_data # (3, len(waveidx), n_flips)
|
|
194
197
|
tmp_euclid = np.linalg.norm(diff, axis=0) # (len(waveidx), n_flips)
|
|
195
|
-
|
|
198
|
+
|
|
199
|
+
# Be explicit about NaNs across any spatial dimension
|
|
200
|
+
nan_mask = np.isnan(diff).any(axis=0)
|
|
201
|
+
tmp_euclid[nan_mask] = np.nan
|
|
196
202
|
|
|
197
203
|
# Store result
|
|
198
204
|
euclid_dist[i, :, :, j] = tmp_euclid
|
|
@@ -216,25 +222,185 @@ def centroid_metrics(euclid_dist, param):
|
|
|
216
222
|
An array (n_units, n_units) of scores for centroid distance and variance
|
|
217
223
|
"""
|
|
218
224
|
max_dist = param['max_dist']
|
|
219
|
-
waveidx = param['waveidx']
|
|
220
|
-
|
|
225
|
+
waveidx = np.asarray(param['waveidx'])
|
|
226
|
+
peak_loc = int(param['peak_loc'])
|
|
221
227
|
|
|
222
|
-
|
|
228
|
+
peak_matches = np.flatnonzero(waveidx == peak_loc)
|
|
229
|
+
if peak_matches.size == 0:
|
|
230
|
+
raise ValueError("param['peak_loc'] must be present in param['waveidx'].")
|
|
231
|
+
peak_idx = int(peak_matches[0])
|
|
223
232
|
|
|
233
|
+
# euclid_dist: (n_units, n_waveidx, n_flips, n_units)
|
|
234
|
+
centroid_dist = np.nanmin(euclid_dist[:, peak_idx, :, :], axis=1)
|
|
224
235
|
|
|
225
|
-
|
|
226
|
-
|
|
236
|
+
min_centroid_dist = np.nanmin(centroid_dist)
|
|
237
|
+
denom = max_dist - min_centroid_dist
|
|
238
|
+
if not np.isfinite(denom) or denom <= 0:
|
|
239
|
+
centroid_dist = np.zeros_like(centroid_dist)
|
|
240
|
+
else:
|
|
241
|
+
centroid_dist = 1 - ((centroid_dist - min_centroid_dist) / denom)
|
|
242
|
+
centroid_dist = np.clip(centroid_dist, 0, 1)
|
|
227
243
|
centroid_dist[np.isnan(centroid_dist)] = 0
|
|
228
244
|
|
|
229
245
|
#Centroid Var
|
|
230
246
|
# need ddof = 1 to match with ML
|
|
231
|
-
|
|
247
|
+
ddof = 1 if euclid_dist.shape[1] > 1 else 0
|
|
248
|
+
centroid_var = np.nanmin(np.nanvar(euclid_dist, axis=1, ddof=ddof), axis=1)
|
|
232
249
|
centroid_var = np.sqrt(centroid_var)
|
|
233
250
|
centroid_var = re_scale(centroid_var)
|
|
234
251
|
centroid_var[np.isnan(centroid_var)] = 0
|
|
235
252
|
|
|
236
253
|
return centroid_dist, centroid_var
|
|
237
254
|
|
|
255
|
+
def get_euclidean_metrics_chunked(avg_waveform_per_tp_flip, param):
|
|
256
|
+
"""
|
|
257
|
+
Memory-efficient computation of Euclidean centroid metrics.
|
|
258
|
+
|
|
259
|
+
Fuses get_Euclidean_dist + centroid_metrics + peak-slice reduction into a single
|
|
260
|
+
pass that processes units in row-chunks, avoiding the full (N, waveidx, flips, N)
|
|
261
|
+
intermediate array. Produces identical results to the original three-step pipeline.
|
|
262
|
+
|
|
263
|
+
Parameters
|
|
264
|
+
----------
|
|
265
|
+
avg_waveform_per_tp_flip : ndarray (3, n_units, spike_width, 2, n_flips)
|
|
266
|
+
The average waveform per time point with the x axis flipped and not flipped
|
|
267
|
+
param : dict
|
|
268
|
+
The param dictionary. Uses 'chunk_size' (default 500) to control the
|
|
269
|
+
number of rows processed per iteration.
|
|
270
|
+
|
|
271
|
+
Returns
|
|
272
|
+
-------
|
|
273
|
+
centroid_dist : ndarray (n_units, n_units)
|
|
274
|
+
Rescaled centroid distance score at peak timepoint
|
|
275
|
+
centroid_var : ndarray (n_units, n_units)
|
|
276
|
+
Rescaled centroid variance score across timepoints
|
|
277
|
+
euclid_dist : ndarray (n_units, n_units)
|
|
278
|
+
Raw (unscaled) Euclidean distance at peak timepoint, minimized over flips.
|
|
279
|
+
Used downstream for distance-based pair filtering.
|
|
280
|
+
"""
|
|
281
|
+
waveidx = param['waveidx']
|
|
282
|
+
n_units = param['n_units']
|
|
283
|
+
max_dist = param['max_dist']
|
|
284
|
+
chunk_size = max(1, param.get('chunk_size', 500))
|
|
285
|
+
|
|
286
|
+
waveidx_arr = np.asarray(waveidx)
|
|
287
|
+
peak_loc = int(param['peak_loc'])
|
|
288
|
+
peak_matches = np.flatnonzero(waveidx_arr == peak_loc)
|
|
289
|
+
if peak_matches.size == 0:
|
|
290
|
+
raise ValueError("param['peak_loc'] must be present in param['waveidx'].")
|
|
291
|
+
peak_idx = int(peak_matches[0])
|
|
292
|
+
|
|
293
|
+
n_waveidx = len(waveidx)
|
|
294
|
+
ddof = 1 if n_waveidx > 1 else 0
|
|
295
|
+
|
|
296
|
+
# Extract relevant slices: (3, N, len_waveidx, n_flips)
|
|
297
|
+
data_cv0 = avg_waveform_per_tp_flip[:, :, waveidx, 0, :]
|
|
298
|
+
data_cv1 = avg_waveform_per_tp_flip[:, :, waveidx, 1, :]
|
|
299
|
+
|
|
300
|
+
# Preallocate (N, N) outputs
|
|
301
|
+
raw_centroid_dist = np.full((n_units, n_units), np.nan)
|
|
302
|
+
raw_centroid_var = np.full((n_units, n_units), np.nan)
|
|
303
|
+
|
|
304
|
+
for i_start in range(0, n_units, chunk_size):
|
|
305
|
+
i_end = min(i_start + chunk_size, n_units)
|
|
306
|
+
# (3, chunk, 1, waveidx, flips) - (3, 1, N, waveidx, flips) = (3, chunk, N, waveidx, flips)
|
|
307
|
+
diff = (data_cv0[:, i_start:i_end, np.newaxis, :, :]
|
|
308
|
+
- data_cv1[:, np.newaxis, :, :, :])
|
|
309
|
+
# Euclidean norm over spatial dims -> (chunk, N, waveidx, flips)
|
|
310
|
+
ed = np.linalg.norm(diff, axis=0)
|
|
311
|
+
del diff
|
|
312
|
+
|
|
313
|
+
# centroid_dist: distance at peak, min over flips
|
|
314
|
+
raw_centroid_dist[i_start:i_end, :] = np.nanmin(ed[:, :, peak_idx, :], axis=-1)
|
|
315
|
+
|
|
316
|
+
# centroid_var: variance over waveidx, min over flips
|
|
317
|
+
raw_centroid_var[i_start:i_end, :] = np.nanmin(
|
|
318
|
+
np.nanvar(ed, axis=2, ddof=ddof), axis=-1)
|
|
319
|
+
del ed
|
|
320
|
+
|
|
321
|
+
# euclid_dist is the raw centroid distance (before rescaling)
|
|
322
|
+
euclid_dist = raw_centroid_dist.copy()
|
|
323
|
+
|
|
324
|
+
# Rescale centroid_dist using max_dist (same as centroid_metrics)
|
|
325
|
+
min_cd = np.nanmin(raw_centroid_dist)
|
|
326
|
+
denom = max_dist - min_cd
|
|
327
|
+
if not np.isfinite(denom) or denom <= 0:
|
|
328
|
+
centroid_dist = np.zeros_like(raw_centroid_dist)
|
|
329
|
+
else:
|
|
330
|
+
centroid_dist = 1 - ((raw_centroid_dist - min_cd) / denom)
|
|
331
|
+
centroid_dist = np.clip(centroid_dist, 0, 1)
|
|
332
|
+
centroid_dist[np.isnan(centroid_dist)] = 0
|
|
333
|
+
|
|
334
|
+
# Rescale centroid_var (same as centroid_metrics)
|
|
335
|
+
centroid_var = np.sqrt(raw_centroid_var)
|
|
336
|
+
centroid_var = re_scale(centroid_var)
|
|
337
|
+
centroid_var[np.isnan(centroid_var)] = 0
|
|
338
|
+
|
|
339
|
+
return centroid_dist, centroid_var, euclid_dist
|
|
340
|
+
|
|
341
|
+
def get_recentered_metrics_chunked(avg_waveform_per_tp_flip, avg_centroid, param):
|
|
342
|
+
"""
|
|
343
|
+
Memory-efficient computation of recentered centroid distance metric.
|
|
344
|
+
|
|
345
|
+
Fuses get_recentered_euclidean_dist + recentered_metrics into a single pass.
|
|
346
|
+
First subtracts each unit's average centroid position from its per-timepoint
|
|
347
|
+
waveform trajectory, then computes pairwise Euclidean distances in row-chunks
|
|
348
|
+
to avoid the full (N, waveidx, flips, N) intermediate array.
|
|
349
|
+
|
|
350
|
+
Parameters
|
|
351
|
+
----------
|
|
352
|
+
avg_waveform_per_tp_flip : ndarray (3, n_units, spike_width, 2, n_flips)
|
|
353
|
+
The average waveform per time point with the x axis flipped and not flipped
|
|
354
|
+
avg_centroid : ndarray (3, n_units, 2)
|
|
355
|
+
The average spatial location for each unit, subtracted before distance
|
|
356
|
+
computation to isolate trajectory shape from absolute position.
|
|
357
|
+
param : dict
|
|
358
|
+
The param dictionary. Uses 'chunk_size' (default 500) to control the
|
|
359
|
+
number of rows processed per iteration.
|
|
360
|
+
|
|
361
|
+
Returns
|
|
362
|
+
-------
|
|
363
|
+
centroid_dist_recentered : ndarray (n_units, n_units)
|
|
364
|
+
Rescaled recentered centroid distance score
|
|
365
|
+
"""
|
|
366
|
+
waveidx = param['waveidx']
|
|
367
|
+
n_units = param['n_units']
|
|
368
|
+
spike_width = param['spike_width']
|
|
369
|
+
chunk_size = max(1, param.get('chunk_size', 500))
|
|
370
|
+
|
|
371
|
+
# Recenter: subtract avg_centroid from each timepoint (per-unit, no N×N)
|
|
372
|
+
avg_centroid_broadcast = np.tile(
|
|
373
|
+
np.expand_dims(avg_centroid, axis=(3, 4)), (1, 1, 1, spike_width, 2))
|
|
374
|
+
recentered = np.swapaxes(
|
|
375
|
+
np.swapaxes(avg_waveform_per_tp_flip, 2, 3) - avg_centroid_broadcast, 2, 3)
|
|
376
|
+
del avg_centroid_broadcast
|
|
377
|
+
|
|
378
|
+
# Extract CV halves at waveidx: (3, N, len_waveidx, n_flips)
|
|
379
|
+
rc_cv0 = recentered[:, :, waveidx, 0, :]
|
|
380
|
+
rc_cv1 = recentered[:, :, waveidx, 1, :]
|
|
381
|
+
del recentered
|
|
382
|
+
|
|
383
|
+
raw_result = np.full((n_units, n_units), np.nan)
|
|
384
|
+
|
|
385
|
+
for i_start in range(0, n_units, chunk_size):
|
|
386
|
+
i_end = min(i_start + chunk_size, n_units)
|
|
387
|
+
# (3, chunk, 1, waveidx, flips) - (3, 1, N, waveidx, flips) = (3, chunk, N, waveidx, flips)
|
|
388
|
+
diff = (rc_cv0[:, i_start:i_end, np.newaxis, :, :]
|
|
389
|
+
- rc_cv1[:, np.newaxis, :, :, :])
|
|
390
|
+
# Euclidean norm over spatial dims -> (chunk, N, waveidx, flips)
|
|
391
|
+
ed = np.linalg.norm(diff, axis=0)
|
|
392
|
+
del diff
|
|
393
|
+
|
|
394
|
+
# recentered_metrics: mean over waveidx, then min over flips
|
|
395
|
+
raw_result[i_start:i_end, :] = np.nanmin(
|
|
396
|
+
np.nanmean(ed, axis=2), axis=-1)
|
|
397
|
+
del ed
|
|
398
|
+
|
|
399
|
+
centroid_dist_recentered = re_scale(raw_result)
|
|
400
|
+
centroid_dist_recentered[np.isnan(centroid_dist_recentered)] = 0
|
|
401
|
+
|
|
402
|
+
return centroid_dist_recentered
|
|
403
|
+
|
|
238
404
|
def get_recentered_euclidean_dist(avg_waveform_per_tp_flip, avg_centroid, param):
|
|
239
405
|
"""
|
|
240
406
|
Find a Euclidean distance where the location per time has been centered around the average position
|
|
@@ -401,17 +567,39 @@ def get_threshold(total_score, within_session, euclid_dist, param, is_first_pass
|
|
|
401
567
|
tmp[within_session == 1] = np.nan
|
|
402
568
|
|
|
403
569
|
hd, __ = np.histogram(np.diag(tmp), Bins)
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
570
|
+
n_units = int(param['n_units'])
|
|
571
|
+
hd = hd / max(n_units, 1)
|
|
572
|
+
|
|
573
|
+
off_diag = tmp - tmp * np.eye(n_units)
|
|
574
|
+
hnd, __ = np.histogram(off_diag, Bins)
|
|
575
|
+
hnd_denom = np.nansum(off_diag)
|
|
576
|
+
if (not np.isfinite(hnd_denom)) or hnd_denom == 0:
|
|
577
|
+
hnd = np.zeros_like(hnd, dtype=float)
|
|
578
|
+
else:
|
|
579
|
+
hnd = hnd / hnd_denom
|
|
407
580
|
hp, __ = np.histogram(tmp, Bins)
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
581
|
+
hp_denom = np.nansum(tmp)
|
|
582
|
+
if (not np.isfinite(hp_denom)) or hp_denom == 0:
|
|
583
|
+
hp = np.zeros_like(hp, dtype=float)
|
|
584
|
+
else:
|
|
585
|
+
hp = hp / hp_denom
|
|
586
|
+
|
|
587
|
+
hd_s = pf.smooth(hd, 3)
|
|
588
|
+
hnd_s = pf.smooth(hnd, 3)
|
|
589
|
+
|
|
590
|
+
# Guard against edge cases where the histograms (or their normalisations) yield no crossing.
|
|
591
|
+
min_len = min(score_vector.shape[0], hd_s.shape[0], hnd_s.shape[0])
|
|
592
|
+
score_vector_use = score_vector[:min_len]
|
|
593
|
+
mask = (hd_s[:min_len] > hnd_s[:min_len]) & (score_vector_use > 0.6)
|
|
594
|
+
crossing_idx = np.flatnonzero(mask)
|
|
595
|
+
if crossing_idx.size == 0:
|
|
596
|
+
thrs_opt = 0.6
|
|
597
|
+
else:
|
|
598
|
+
thrs_opt = float(score_vector_use[crossing_idx[0]])
|
|
411
599
|
# if ThrsOpt.size == 0:
|
|
412
600
|
# ThrsOpt = 0.6 # give default threshold if above doestn return value
|
|
413
601
|
# fit tmp to a normal ditn
|
|
414
|
-
fit = tmp[
|
|
602
|
+
fit = tmp[(~np.isnan(tmp)) & (tmp < thrs_opt)]
|
|
415
603
|
muw = np.mean(fit)
|
|
416
604
|
stdw = np.std(fit)
|
|
417
605
|
|
|
@@ -425,8 +613,12 @@ def get_threshold(total_score, within_session, euclid_dist, param, is_first_pass
|
|
|
425
613
|
tmp[within_session == 0] = np.nan
|
|
426
614
|
|
|
427
615
|
ha, __ = np.histogram(tmp, Bins)
|
|
428
|
-
|
|
429
|
-
|
|
616
|
+
ha_denom = np.nansum(tmp)
|
|
617
|
+
if (not np.isfinite(ha_denom)) or ha_denom == 0:
|
|
618
|
+
ha = np.zeros_like(ha, dtype=float)
|
|
619
|
+
else:
|
|
620
|
+
ha = ha / ha_denom
|
|
621
|
+
fit = tmp[(~np.isnan(tmp)) & (tmp < thrs_opt)]
|
|
430
622
|
mua = np.mean(fit)
|
|
431
623
|
stda = np.std(fit)
|
|
432
624
|
|
|
@@ -434,7 +626,7 @@ def get_threshold(total_score, within_session, euclid_dist, param, is_first_pass
|
|
|
434
626
|
# for first pass only (i.e before drift correction)
|
|
435
627
|
#This is to decrease the threshold for the first pass so that the threshold is lowered
|
|
436
628
|
# as without drift correction even matches should have a lower total score
|
|
437
|
-
if
|
|
629
|
+
if np.isfinite(mua) and np.isfinite(muw) and (mua < muw):
|
|
438
630
|
thrs_opt = thrs_opt - np.abs(muw - mua)
|
|
439
631
|
|
|
440
632
|
return thrs_opt
|
|
@@ -696,6 +888,14 @@ def test_matches_per_shank(pairs, avg_centroid, sid, param):
|
|
|
696
888
|
Will return True if there is enough units per shank to do per shank drift correction
|
|
697
889
|
"""
|
|
698
890
|
|
|
891
|
+
pairs = np.asarray(pairs)
|
|
892
|
+
if pairs.size == 0:
|
|
893
|
+
return False
|
|
894
|
+
if pairs.ndim == 1:
|
|
895
|
+
pairs = np.expand_dims(pairs, axis=0)
|
|
896
|
+
if pairs.ndim != 2 or pairs.shape[1] != 2:
|
|
897
|
+
raise ValueError("pairs must have shape (n_pairs, 2).")
|
|
898
|
+
|
|
699
899
|
do_per_shank_correction = True
|
|
700
900
|
|
|
701
901
|
centroid_a = np.nanmean( avg_centroid[:,pairs[:,0],:], axis = 2)
|
|
@@ -718,10 +918,10 @@ def test_matches_per_shank(pairs, avg_centroid, sid, param):
|
|
|
718
918
|
|
|
719
919
|
if np.all(correct_shank_a == correct_shank_b) != True:
|
|
720
920
|
#delete pairs which are on different shanks
|
|
721
|
-
bad_idx = np.
|
|
921
|
+
bad_idx = np.flatnonzero(correct_shank_a != correct_shank_b)
|
|
722
922
|
print(f'These pairs may be bad {bad_idx}, so are excluded from drift correction')
|
|
723
|
-
correct_shank_a[bad_idx]=False
|
|
724
|
-
correct_shank_b[bad_idx]=False
|
|
923
|
+
correct_shank_a[bad_idx] = False
|
|
924
|
+
correct_shank_b[bad_idx] = False
|
|
725
925
|
|
|
726
926
|
shank_id_tmp[correct_shank_a] = i
|
|
727
927
|
|
|
@@ -771,8 +971,10 @@ def drift_n_sessions(candidate_pairs, session_switch, avg_centroid, avg_waveform
|
|
|
771
971
|
n_sessions = param['n_sessions']
|
|
772
972
|
best_pairs = np.argwhere(candidate_pairs == 1)
|
|
773
973
|
|
|
774
|
-
#
|
|
775
|
-
best_pairs
|
|
974
|
+
# Ensure each pair is ordered (small idx, large idx) regardless of matrix orientation
|
|
975
|
+
best_pairs = np.sort(best_pairs, axis=1)
|
|
976
|
+
if best_pairs.size > 0:
|
|
977
|
+
best_pairs = np.unique(best_pairs, axis=0)
|
|
776
978
|
|
|
777
979
|
drifts = np.zeros( (n_sessions - 1, 3))
|
|
778
980
|
|
|
@@ -799,6 +1001,68 @@ def drift_n_sessions(candidate_pairs, session_switch, avg_centroid, avg_waveform
|
|
|
799
1001
|
return drifts, avg_centroid, avg_waveform_per_tp
|
|
800
1002
|
|
|
801
1003
|
|
|
1004
|
+
def drift_correct_session_pair(candidate_pairs, session_switch, avg_centroid, avg_waveform_per_tp, did, param):
|
|
1005
|
+
"""
|
|
1006
|
+
This function applies drift correction between n_sessions, currently this is done by aligning session 2 to session 1,
|
|
1007
|
+
then session 3 to session 2 etc.
|
|
1008
|
+
This function, calls another function to apply the drift correction, to be able to apply different type of drift correction
|
|
1009
|
+
easily.
|
|
1010
|
+
|
|
1011
|
+
Parameters
|
|
1012
|
+
----------
|
|
1013
|
+
candidate_pairs : ndarray
|
|
1014
|
+
An array of likely matches
|
|
1015
|
+
session_switch : ndarray
|
|
1016
|
+
What units does the session switch
|
|
1017
|
+
avg_centroid : ndarray
|
|
1018
|
+
The average centroid for each unit
|
|
1019
|
+
avg_waveform_per_tp : ndarray
|
|
1020
|
+
The average waveform per time point for each unit
|
|
1021
|
+
did : int
|
|
1022
|
+
The session id
|
|
1023
|
+
param : dict
|
|
1024
|
+
The param dictionary
|
|
1025
|
+
|
|
1026
|
+
Returns
|
|
1027
|
+
-------
|
|
1028
|
+
ndarray
|
|
1029
|
+
avg_waveform_per_tp arrays drift corrected
|
|
1030
|
+
"""
|
|
1031
|
+
session_switch = np.asarray(session_switch).astype(int)
|
|
1032
|
+
n_units = avg_centroid.shape[1]
|
|
1033
|
+
if candidate_pairs.shape != (n_units, n_units):
|
|
1034
|
+
raise ValueError("candidate_pairs must have shape (n_units, n_units) matching avg_centroid/avg_waveform_per_tp.")
|
|
1035
|
+
if session_switch.ndim != 1 or session_switch.size < 3:
|
|
1036
|
+
raise ValueError("session_switch must be a 1D array with at least 3 entries (start, boundary, end).")
|
|
1037
|
+
if session_switch[0] != 0 or session_switch[-1] != n_units:
|
|
1038
|
+
raise ValueError("session_switch must be relative to the provided arrays (session_switch[0]==0 and session_switch[-1]==n_units).")
|
|
1039
|
+
if did < 0 or (did + 2) >= session_switch.size:
|
|
1040
|
+
raise IndexError("did out of range for session_switch.")
|
|
1041
|
+
|
|
1042
|
+
best_pairs = np.argwhere(candidate_pairs == 1)
|
|
1043
|
+
|
|
1044
|
+
# Ensure each pair is ordered (small idx, large idx) regardless of matrix orientation
|
|
1045
|
+
best_pairs = np.sort(best_pairs, axis=1)
|
|
1046
|
+
if best_pairs.size > 0:
|
|
1047
|
+
best_pairs = np.unique(best_pairs, axis=0)
|
|
1048
|
+
|
|
1049
|
+
idx = np.argwhere( ( (best_pairs[:,0] >= session_switch[did]) * (best_pairs[:,0] < session_switch[did + 1]) *
|
|
1050
|
+
(best_pairs[:,1] >= session_switch[did + 1]) * (best_pairs[:,1] < session_switch[did + 2]) ) == True)
|
|
1051
|
+
|
|
1052
|
+
pairs = best_pairs[idx,:].squeeze()
|
|
1053
|
+
if pairs.ndim == 1:
|
|
1054
|
+
pairs = np.expand_dims(pairs, axis = 0)
|
|
1055
|
+
|
|
1056
|
+
#Test to see if there are enough matches to do drift correction per shank
|
|
1057
|
+
if test_matches_per_shank(pairs, avg_centroid, did, param) == True:
|
|
1058
|
+
_, avg_waveform_per_tp,_ = apply_drift_correction_per_shank(pairs, did, session_switch, avg_centroid, avg_waveform_per_tp, param)
|
|
1059
|
+
print(f'Done drift correction per shank for session pair {did+1} and {did+2}')
|
|
1060
|
+
elif len(pairs)>0: #if there exist pairs across sessions:
|
|
1061
|
+
_, avg_waveform_per_tp,_ = apply_drift_correction_basic(pairs, did, session_switch, avg_centroid, avg_waveform_per_tp)
|
|
1062
|
+
elif len(pairs)==0:
|
|
1063
|
+
print('No pairs across sessions to perform drift correction.')
|
|
1064
|
+
return avg_waveform_per_tp
|
|
1065
|
+
|
|
802
1066
|
|
|
803
1067
|
def get_total_score(scores_to_include, param):
|
|
804
1068
|
"""
|
UnitMatchPy/overlord.py
CHANGED
|
@@ -83,19 +83,15 @@ def extract_metric_scores(extracted_wave_properties, session_switch, within_sess
|
|
|
83
83
|
#effected by drift
|
|
84
84
|
for i in range(niter):
|
|
85
85
|
avg_waveform_per_tp_flip = mf.flip_dim(avg_waveform_per_tp, param)
|
|
86
|
-
euclid_dist = mf.get_Euclidean_dist(avg_waveform_per_tp_flip, param)
|
|
87
86
|
|
|
88
|
-
centroid_dist, centroid_var = mf.
|
|
87
|
+
centroid_dist, centroid_var, euclid_dist = mf.get_euclidean_metrics_chunked(
|
|
88
|
+
avg_waveform_per_tp_flip, param)
|
|
89
89
|
|
|
90
|
-
|
|
90
|
+
centroid_dist_recentered = mf.get_recentered_metrics_chunked(
|
|
91
|
+
avg_waveform_per_tp_flip, avg_centroid, param)
|
|
91
92
|
|
|
92
|
-
centroid_dist_recentered = mf.recentered_metrics(euclid_dist_rc)
|
|
93
93
|
traj_angle_score, traj_dist_score = mf.dist_angle(avg_waveform_per_tp_flip, param)
|
|
94
94
|
|
|
95
|
-
|
|
96
|
-
# Average Euc Dist
|
|
97
|
-
euclid_dist = np.nanmin(euclid_dist[:,param['peak_loc'] - param['waveidx'] == 0, :,:].squeeze(), axis = 1 )
|
|
98
|
-
|
|
99
95
|
# TotalScore
|
|
100
96
|
include_these_pairs = np.argwhere( euclid_dist < param['max_dist']) #array indices of pairs to include
|
|
101
97
|
include_these_pairs_idx = np.zeros_like(euclid_dist)
|
UnitMatchPy/utils.py
CHANGED
|
@@ -125,8 +125,11 @@ def load_good_waveforms(wave_paths, unit_label_paths, param, good_units_only=Tru
|
|
|
125
125
|
all_units.append(unit_label[:, 0])
|
|
126
126
|
|
|
127
127
|
waveforms = []
|
|
128
|
+
successful_sessions = []
|
|
128
129
|
if good_units_only:
|
|
129
130
|
for ls in range(len(wave_paths)):
|
|
131
|
+
tmp_waveform = None
|
|
132
|
+
tmp = None
|
|
130
133
|
try:
|
|
131
134
|
p_file = os.path.join(wave_paths[ls], f'Unit{int(good_units[ls][0].squeeze())}_RawSpikes.npy')
|
|
132
135
|
tmp = np.load(p_file)
|
|
@@ -136,6 +139,7 @@ def load_good_waveforms(wave_paths, unit_label_paths, param, good_units_only=Tru
|
|
|
136
139
|
p_file_good = os.path.join(wave_paths[ls], f'Unit{int(good_units[ls][i].squeeze())}_RawSpikes.npy')
|
|
137
140
|
tmp_waveform[i] = np.load(p_file_good)
|
|
138
141
|
waveforms.append(tmp_waveform)
|
|
142
|
+
successful_sessions.append(ls)
|
|
139
143
|
except Exception as e:
|
|
140
144
|
print(f'Error loading waveform for session {ls}: {e}')
|
|
141
145
|
finally:
|
|
@@ -143,6 +147,8 @@ def load_good_waveforms(wave_paths, unit_label_paths, param, good_units_only=Tru
|
|
|
143
147
|
del tmp
|
|
144
148
|
else:
|
|
145
149
|
for ls in range(len(wave_paths)):
|
|
150
|
+
tmp_waveform = None
|
|
151
|
+
tmp = None
|
|
146
152
|
try:
|
|
147
153
|
p_file = os.path.join(wave_paths[ls], f'Unit0_RawSpikes.npy')
|
|
148
154
|
tmp = np.load(p_file)
|
|
@@ -152,6 +158,7 @@ def load_good_waveforms(wave_paths, unit_label_paths, param, good_units_only=Tru
|
|
|
152
158
|
p_file_good = os.path.join(wave_paths[ls], f'Unit{i}_RawSpikes.npy')
|
|
153
159
|
tmp_waveform[i] = np.load(p_file_good)
|
|
154
160
|
waveforms.append(tmp_waveform)
|
|
161
|
+
successful_sessions.append(ls)
|
|
155
162
|
print(f'UnitMatch is treating all the units as good and including all units from {wave_paths[ls]}, we recommended using curated data!')
|
|
156
163
|
except Exception as e:
|
|
157
164
|
print(f'Error loading waveform for session {ls}: {e}')
|
|
@@ -159,6 +166,13 @@ def load_good_waveforms(wave_paths, unit_label_paths, param, good_units_only=Tru
|
|
|
159
166
|
del tmp_waveform
|
|
160
167
|
del tmp
|
|
161
168
|
|
|
169
|
+
if len(successful_sessions) < n_sessions:
|
|
170
|
+
failed = [i for i in range(n_sessions) if i not in successful_sessions]
|
|
171
|
+
print(f'Warning: failed to load waveforms for {len(failed)} session(s): {failed}. Excluding from analysis.')
|
|
172
|
+
good_units = [good_units[i] for i in successful_sessions]
|
|
173
|
+
n_units_per_session_all = [n_units_per_session_all[i] for i in successful_sessions]
|
|
174
|
+
n_sessions = len(successful_sessions)
|
|
175
|
+
|
|
162
176
|
n_units_per_session = np.zeros(n_sessions, dtype='int')
|
|
163
177
|
waveform = np.array([])
|
|
164
178
|
|
|
@@ -385,119 +399,112 @@ def isin_2d(test_arr, parent_arr):
|
|
|
385
399
|
|
|
386
400
|
def fill_missing_pos(KS_dir, n_channels):
|
|
387
401
|
"""
|
|
388
|
-
KiloSort
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
402
|
+
KiloSort may not include channel positions for inactive channels (e.g. channels
|
|
403
|
+
outside the brain). UnitMatch requires the full channel_pos array, so this
|
|
404
|
+
function reconstructs positions for the missing hardware channels.
|
|
405
|
+
|
|
406
|
+
Strategy: channel_map.npy maps the N_active entries in channel_positions.npy to
|
|
407
|
+
their hardware-channel indices (0 … n_channels-1). For each x-column found in
|
|
408
|
+
the known positions a linear model y = slope * hw_channel_index + intercept is
|
|
409
|
+
fit using the known (hw_index, y) pairs. Missing channels are then assigned to
|
|
410
|
+
the column given by hw_index % n_cols and their y is predicted by that model.
|
|
411
|
+
This correctly handles any number of missing channels, from a single gap to the
|
|
412
|
+
majority of the probe being outside the brain.
|
|
392
413
|
|
|
393
414
|
Parameters
|
|
394
415
|
----------
|
|
395
416
|
KS_dir : str
|
|
396
|
-
|
|
417
|
+
Path to the KiloSort output directory.
|
|
397
418
|
n_channels : int
|
|
398
|
-
|
|
419
|
+
Total number of hardware channels (waveform array dimension).
|
|
399
420
|
|
|
400
421
|
Returns
|
|
401
422
|
-------
|
|
402
|
-
ndarray
|
|
403
|
-
|
|
423
|
+
ndarray, shape (n_channels, 2)
|
|
424
|
+
Full channel_pos array; known positions are preserved exactly.
|
|
404
425
|
"""
|
|
405
|
-
print('The channel_positions.npy file does not match with the raw waveforms
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
pos = np.load(path_tmp)
|
|
409
|
-
|
|
410
|
-
path_tmp = os.path.join(KS_dir, 'channel_map.npy')
|
|
411
|
-
channel_map = np.load(path_tmp).squeeze()
|
|
412
|
-
|
|
413
|
-
channel_pos = np.full((n_channels,2), np.nan)
|
|
414
|
-
channel_pos[channel_map,:] = pos
|
|
415
|
-
|
|
416
|
-
channel_pos_new = []
|
|
417
|
-
#get the unique x positions
|
|
418
|
-
x_unique = np.unique(channel_pos[:,0])
|
|
419
|
-
x_unique = x_unique[~np.isnan(x_unique)]
|
|
420
|
-
|
|
421
|
-
#go through each column
|
|
422
|
-
for x in x_unique:
|
|
423
|
-
#get the known y-values for that column
|
|
424
|
-
y_column = channel_pos[np.argwhere(channel_pos[:,0] == x), 1].squeeze()
|
|
425
|
-
|
|
426
|
-
#test to see if any other columns have the same set of y positions
|
|
427
|
-
same_x_pattern = np.unique(channel_pos[np.in1d(channel_pos[:,1], y_column), 0])
|
|
428
|
-
same_y_pattern = channel_pos[np.in1d(channel_pos[:,0], same_x_pattern), 1]
|
|
426
|
+
print('The channel_positions.npy file does not match with the raw waveforms. '
|
|
427
|
+
'Attempting to fill in missing positions using probe geometry inference. '
|
|
428
|
+
'Please verify channel_positions and RawWaveforms shapes afterwards.')
|
|
429
429
|
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
y_steps = y_steps[np.argmax(y_step_counts)].astype(int)
|
|
430
|
+
pos = np.load(os.path.join(KS_dir, 'channel_positions.npy'))
|
|
431
|
+
channel_map = np.load(os.path.join(KS_dir, 'channel_map.npy')).squeeze()
|
|
433
432
|
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
ypos = np.arange(ymin, ymax+y_steps, y_steps)
|
|
433
|
+
# Place known positions at their correct hardware-channel indices.
|
|
434
|
+
channel_pos = np.full((n_channels, 2), np.nan)
|
|
435
|
+
channel_pos[channel_map, :] = pos
|
|
438
436
|
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
if pos.shape[0] == n_channels - 1:
|
|
437
|
+
nan_mask = np.isnan(channel_pos[:, 0])
|
|
438
|
+
if not np.any(nan_mask):
|
|
443
439
|
print('Likely to be correctly filled')
|
|
444
|
-
missed_pos_idx = np.argwhere(isin_2d(np.vstack(channel_pos_new), pos) == False)
|
|
445
|
-
channel_pos[np.isnan(channel_pos)[:,0],:] = np.vstack(channel_pos_new)[missed_pos_idx]
|
|
446
440
|
return channel_pos
|
|
447
441
|
|
|
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
|
-
|
|
442
|
+
# --- Geometry inference via per-column linear regression ---
|
|
443
|
+
# Assumes channels fill x-columns in round-robin order (ch % n_cols → column),
|
|
444
|
+
# which holds for all Neuropixels probes. For probes with a different layout the
|
|
445
|
+
# validation step below will detect the mismatch and fall back to off-probe
|
|
446
|
+
# placeholders rather than silently returning wrong positions.
|
|
447
|
+
x_unique = np.unique(pos[:, 0])
|
|
448
|
+
n_cols = len(x_unique)
|
|
449
|
+
|
|
450
|
+
# Estimate a global y-step as a fallback for columns with only one known channel.
|
|
451
|
+
all_y_diffs = []
|
|
452
|
+
for x in x_unique:
|
|
453
|
+
yj = np.sort(pos[pos[:, 0] == x, 1])
|
|
454
|
+
if len(yj) > 1:
|
|
455
|
+
all_y_diffs.extend(np.diff(yj).tolist())
|
|
456
|
+
y_step_global = float(np.median(all_y_diffs)) if all_y_diffs else 20.0
|
|
457
|
+
|
|
458
|
+
col_models = {} # col_index -> (slope, intercept)
|
|
459
|
+
for col_i, x in enumerate(x_unique):
|
|
460
|
+
col_mask = pos[:, 0] == x
|
|
461
|
+
ch_indices = channel_map[col_mask].astype(float)
|
|
462
|
+
y_vals = pos[col_mask, 1].astype(float)
|
|
463
|
+
if len(ch_indices) >= 2:
|
|
464
|
+
slope, intercept = np.polyfit(ch_indices, y_vals, 1)
|
|
465
|
+
# Validate: max residual must be well below one y-step.
|
|
466
|
+
residuals = np.abs(np.polyval([slope, intercept], ch_indices) - y_vals)
|
|
467
|
+
if np.max(residuals) > 0.4 * y_step_global:
|
|
468
|
+
# Column assignment by ch % n_cols is inconsistent with the known
|
|
469
|
+
# positions — this probe does not use round-robin column ordering.
|
|
470
|
+
print('Warning: probe geometry does not follow a round-robin column '
|
|
471
|
+
'pattern (max fit residual {:.1f} µm). Cannot infer positions '
|
|
472
|
+
'for inactive channels; off-probe placeholders will be used. '
|
|
473
|
+
'Supply the full channel_positions manually if needed.'.format(
|
|
474
|
+
float(np.max(residuals))))
|
|
475
|
+
x_fill = float(np.nanmedian(channel_pos[:, 0]))
|
|
476
|
+
y_fill = float(np.nanmin(channel_pos[:, 1])) - 10000.0
|
|
477
|
+
channel_pos[nan_mask] = [x_fill, y_fill]
|
|
478
|
+
return channel_pos
|
|
479
|
+
else:
|
|
480
|
+
# Single known channel: use global y-step scaled by column stride.
|
|
481
|
+
slope = y_step_global / n_cols
|
|
482
|
+
intercept = y_vals[0] - slope * ch_indices[0]
|
|
483
|
+
col_models[col_i] = (slope, intercept)
|
|
484
|
+
|
|
485
|
+
# Assign each inactive hardware channel to its column (ch % n_cols) and
|
|
486
|
+
# predict its y position from the column's linear model.
|
|
487
|
+
for ch_idx in np.where(nan_mask)[0]:
|
|
488
|
+
col_i = ch_idx % n_cols
|
|
489
|
+
slope, intercept = col_models[col_i]
|
|
490
|
+
channel_pos[ch_idx] = [x_unique[col_i], slope * ch_idx + intercept]
|
|
491
|
+
|
|
492
|
+
# Safety net: if any positions are still NaN (unexpected column layout),
|
|
493
|
+
# place them well off-probe so they do not interfere with active channels.
|
|
494
|
+
still_nan = np.isnan(channel_pos[:, 0])
|
|
495
|
+
if np.any(still_nan):
|
|
496
|
+
x_fill = float(np.nanmedian(channel_pos[:, 0]))
|
|
497
|
+
y_fill = float(np.nanmin(channel_pos[:, 1])) - 10000.0
|
|
498
|
+
channel_pos[still_nan] = [x_fill, y_fill]
|
|
499
|
+
print('Warning: could not infer positions for {:d} inactive channels; '
|
|
500
|
+
'off-probe placeholder used.'.format(int(np.sum(still_nan))))
|
|
501
|
+
|
|
502
|
+
if np.allclose(channel_pos[channel_map], pos):
|
|
495
503
|
print('Likely to be correctly filled')
|
|
496
|
-
return channel_pos_fill
|
|
497
504
|
else:
|
|
498
|
-
print('Error in filling channel positions, please fill in manually \n
|
|
499
|
-
|
|
500
|
-
|
|
505
|
+
print('Error in filling channel positions, please fill in manually \n'
|
|
506
|
+
' Have returned the known channel positions and NaN')
|
|
507
|
+
return channel_pos
|
|
501
508
|
|
|
502
509
|
def paths_from_KS(KS_dirs, custom_raw_waveform_paths=None, custom_bombcell_paths=None):
|
|
503
510
|
"""
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: UnitMatchPy
|
|
3
|
+
Version: 3.3.1
|
|
4
|
+
Summary: Automatic matching of neurons across sessions
|
|
5
|
+
Author: Enny van Beest, Célian Bimbard, Suyash Agarwal, Wentao Qiu
|
|
6
|
+
License: CC BY-NC-SA 4.0 International
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: <3.13,>=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: numpy<2.0,>=1.21
|
|
17
|
+
Requires-Dist: scipy<2.0,>=1.9
|
|
18
|
+
Requires-Dist: pandas<3.0,>=1.5
|
|
19
|
+
Requires-Dist: matplotlib<4.0,>=3.6
|
|
20
|
+
Requires-Dist: joblib<2.0,>=1.2
|
|
21
|
+
Requires-Dist: tqdm<5.0,>=4.64
|
|
22
|
+
Requires-Dist: h5py<4.0,>=3.8
|
|
23
|
+
Requires-Dist: scikit-learn<2.0,>=1.2
|
|
24
|
+
Requires-Dist: mtscomp
|
|
25
|
+
Requires-Dist: torch<3.0,>=2.1
|
|
26
|
+
Provides-Extra: full
|
|
27
|
+
Requires-Dist: mat73<1.0,>=0.62; extra == "full"
|
|
28
|
+
Requires-Dist: spikeinterface<0.120,>=0.100; extra == "full"
|
|
29
|
+
Provides-Extra: notebooks
|
|
30
|
+
Requires-Dist: ipykernel<7,>=6; extra == "notebooks"
|
|
31
|
+
Provides-Extra: dev
|
|
32
|
+
Requires-Dist: pytest; extra == "dev"
|
|
33
|
+
Requires-Dist: ruff; extra == "dev"
|
|
34
|
+
Requires-Dist: mypy; extra == "dev"
|
|
35
|
+
Requires-Dist: build; extra == "dev"
|
|
36
|
+
Requires-Dist: twine; extra == "dev"
|
|
37
|
+
Dynamic: license-file
|
|
38
|
+
|
|
39
|
+
# UnitMatchPy and DeepUnitMatch
|
|
40
|
+
|
|
41
|
+
This repository contains:
|
|
42
|
+
- **UnitMatchPy**: automatic matching of neurons across sessions (Python package).
|
|
43
|
+
- **DeepUnitMatch**: DeepUnitMatch pipeline and demos (see preprint below).
|
|
44
|
+
|
|
45
|
+
## References
|
|
46
|
+
|
|
47
|
+
- **UnitMatch:** https://www.nature.com/articles/s41592-024-02440-1
|
|
48
|
+
- **DeepUnitMatch preprint:** https://www.biorxiv.org/content/10.64898/2026.01.30.702777v1
|
|
49
|
+
|
|
50
|
+
## Versions
|
|
51
|
+
|
|
52
|
+
- **UnitMatchPy version:** `3.3.1` (from `pyproject.toml`)
|
|
53
|
+
- **DeepUnitMatch:** code lives under `DeepUnitMatch/` (see **DeepUnitMatch (DUM)** section)
|
|
54
|
+
|
|
55
|
+
## System requirements
|
|
56
|
+
|
|
57
|
+
Both UnitMatchPy and DeepUnitMatch can be ran on a standard computer, with sufficient RAM (>32GB for large datasets).
|
|
58
|
+
This software is supported for Windows and macOS, and has been tested on Windows 11.
|
|
59
|
+
|
|
60
|
+
## Installation
|
|
61
|
+
|
|
62
|
+
`pip install` (including `pip install -e .`) installs into whatever Python environment your `pip` points to (system Python, a conda env, or a virtualenv). `pip` does **not** create or name environments.
|
|
63
|
+
|
|
64
|
+
We recommend using Anaconda/Miniconda (conda) to create an isolated environment first:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# Create a new environment (pick any name you like; example: UMPy)
|
|
68
|
+
conda create -n UMPy python=3.11 pip #(press y when prompted)
|
|
69
|
+
conda activate UMPy
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Then install using pip (options below). This step should take less than few minutes.
|
|
73
|
+
|
|
74
|
+
### Option A: Install the released package (PyPI)
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pip install UnitMatchPy
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Optional extras (heavier dependencies used by some notebooks and integration with SpikeInterface):
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
pip install "UnitMatchPy[full,notebooks]"
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Option B: Install a local, editable copy (for development / modified code)
|
|
87
|
+
|
|
88
|
+
First, open a terminal and navigate to this folder (the one containing `pyproject.toml`). The `pip install -e` command must be run from here:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
# Windows (PowerShell) - note; you may have to give writing access to the specific CONDA environment via Windows Security → Virus & threat protection → Ransomware protection → Manage ransomware protection. For example, if the below steps result in "could not create 'UnitMatchPy.egg-info'"
|
|
92
|
+
|
|
93
|
+
Look at Controlled folder access:
|
|
94
|
+
cd $HOME\Documents\GitHub\UnitMatch\UnitMatchPy
|
|
95
|
+
|
|
96
|
+
# macOS / Linux
|
|
97
|
+
cd ~/Documents/GitHub/UnitMatch/UnitMatchPy
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
pip install -e .
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Optional extras (e.g. if you'd like to run the notebooks or integrate with SpikeInterface):
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
pip install -e ".[full,notebooks]"
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Demo notebooks
|
|
111
|
+
|
|
112
|
+
All demo notebooks are in `Demo Notebooks/`.
|
|
113
|
+
|
|
114
|
+
### Run UnitMatchPy
|
|
115
|
+
|
|
116
|
+
To run UnitMatchPy, standard spike sorting data is needed (channel positions and extracted raw waveforms for each unit). Waveforms can be extracted externally (e.g. [BombCell](https://github.com/Julie-Fabre/bombcell)) or using the demo notebooks:
|
|
117
|
+
- `Demo Notebooks/extract_raw_data_demo.ipynb` (compressed `.cbin`/`.ch` or raw)
|
|
118
|
+
- `Demo Notebooks/extract_raw_data_demo_open_ephys.ipynb` (Open Ephys)
|
|
119
|
+
- `Demo Notebooks/UMPy_spike_interface_demo.ipynb` ([SpikeInterface](https://spikeinterface.readthedocs.io/en/latest/) workflow)
|
|
120
|
+
|
|
121
|
+
Example notebooks:
|
|
122
|
+
- `Demo Notebooks/UMPy_example.ipynb` (recommended starting point)
|
|
123
|
+
- `Demo Notebooks/UMPy_example_detailed.ipynb` (more modular / advanced)
|
|
124
|
+
|
|
125
|
+
The GUI is an optional step to curate and explore UnitMatch outputs; see `Demo Notebooks/GUI_Reference_Guide.md` for usage tips and shortcuts.
|
|
126
|
+
|
|
127
|
+
### Run DeepUnitMatch
|
|
128
|
+
|
|
129
|
+
To try the DeepUnitMatch version, start with:
|
|
130
|
+
- `Demo Notebooks/DeepUnitMatch.ipynb`
|
|
131
|
+
|
|
132
|
+
It should take just a few minutes to run on a standard PC.
|
|
133
|
+
|
|
134
|
+
If you want to train / fine-tune a model on your own data, see:
|
|
135
|
+
- `Demo Notebooks/DUM_training.ipynb`
|
|
136
|
+
|
|
137
|
+
Important note: DeepUnitMatch current trained model is for Npix 2.0 4-shank only. You will need to train a new model with your own data if you have any other type of probe. (For example, Mouse2 from the figshare data is a Npix 1 dataset, you'll notice the trained model won't give good results on this mouse for that reason.)
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
UnitMatchPy/GUI.py,sha256=
|
|
1
|
+
UnitMatchPy/GUI.py,sha256=TENEtgPKOUZZm0PhXGGJYSp-NN75LvGFtMJld1qfykE,72500
|
|
2
2
|
UnitMatchPy/GUI_icon.png,sha256=hryy3e7itPSMu_aqRJ_EgGsrNU0tl6lP2RBA0FKkckY,1968
|
|
3
3
|
UnitMatchPy/UM Logo.ico,sha256=slwTUp3OGJzWtb0HkEu1xugU_CMeNv3ZrxrfnzKK4Pw,14872
|
|
4
4
|
UnitMatchPy/__init__.py,sha256=k7uCoTM8FbOhi1TV3tIgBUtuUwhRxh_pl5bebKAHwiM,268
|
|
5
5
|
UnitMatchPy/assign_unique_id.py,sha256=sBsjfamkuy6yY9GxHQ7oQJSvpUSxXk2uoVYNpxMF83k,8413
|
|
6
6
|
UnitMatchPy/bayes_functions.py,sha256=3sP-4cWcTTRtuE7HjKJHwN1iFDBY3Y-cmufetCgUZ_A,4511
|
|
7
|
-
UnitMatchPy/default_params.py,sha256=
|
|
7
|
+
UnitMatchPy/default_params.py,sha256=9mDQrnlFgNpw8mi3-aXsrrGzPndFLF0KPmDG2eNC2rg,1820
|
|
8
8
|
UnitMatchPy/extract_raw_data.py,sha256=BaPT5sSj3mVxHJomnlJWELbxDgwbC-VnUbako9JwFAk,10767
|
|
9
|
-
UnitMatchPy/metric_functions.py,sha256=
|
|
10
|
-
UnitMatchPy/overlord.py,sha256
|
|
9
|
+
UnitMatchPy/metric_functions.py,sha256=oCINKcyr8qccaqvXnla_h54_dYK2s0WPisL3QzxcwZM,42371
|
|
10
|
+
UnitMatchPy/overlord.py,sha256=-TJi1ZnDWYdNlI-b27MW4-9BmzO94P9m0K6WC9yRKfY,6371
|
|
11
11
|
UnitMatchPy/param_functions.py,sha256=rOWhzccSVHgbtumKvy5_h0aBvocwwjUpVonA_C6_rAg,16713
|
|
12
12
|
UnitMatchPy/run.py,sha256=pA0lQntiEQt8jTuxfC1eoIdESCkWttyBw3eheuk5hMA,5350
|
|
13
13
|
UnitMatchPy/save_utils.py,sha256=ZPlI60JYKt5cmZPiTYI2sPeA1OeKdgcWjeAT5yG4QyA,18672
|
|
14
|
-
UnitMatchPy/utils.py,sha256=
|
|
14
|
+
UnitMatchPy/utils.py,sha256=btHAvIbWs5BLLfWmGlnI3yTRCvVTNFfrbGxdzhMbtmg,40937
|
|
15
15
|
UnitMatchPy/TkinterTheme/awthemes-10.4.0/LICENSE,sha256=QLti2X2WgO5MQ5_zSH1BpTVF2KHSCliQa9HG1s4skQk,2215
|
|
16
16
|
UnitMatchPy/TkinterTheme/awthemes-10.4.0/README.txt,sha256=OszYA8mn7QelmAYtz0bHi6sf9YOvrXLGgmuCx3bRoJ4,15419
|
|
17
17
|
UnitMatchPy/TkinterTheme/awthemes-10.4.0/awdark.tcl,sha256=bGeLj0wiuOkXQR3R7lP9FpkdE1-mAJruUATnxdCmy0c,2024
|
|
@@ -279,8 +279,8 @@ UnitMatchPy/TkinterTheme/awthemes-10.4.0/i/awthemes/treeview/solid/tree-arrow-do
|
|
|
279
279
|
UnitMatchPy/TkinterTheme/awthemes-10.4.0/i/awthemes/treeview/solid/tree-arrow-right-n-base.svg,sha256=rhgTHm-xIGRkRz9sCSwNNZ3uKfDrK78lroyYbBJAZsk,2386
|
|
280
280
|
UnitMatchPy/TkinterTheme/awthemes-10.4.0/i/awthemes/treeview/solid/tree-arrow-right-n.svg,sha256=8x1rGSDH8eyFeQDJ-glAc63K1hl-UveaJTNBkDmP6vA,2497
|
|
281
281
|
UnitMatchPy/TkinterTheme/awthemes-10.4.0/i/awthemes/treeview/solid/tree-arrow-right-sn.svg,sha256=8x1rGSDH8eyFeQDJ-glAc63K1hl-UveaJTNBkDmP6vA,2497
|
|
282
|
-
unitmatchpy-3.
|
|
283
|
-
unitmatchpy-3.
|
|
284
|
-
unitmatchpy-3.
|
|
285
|
-
unitmatchpy-3.
|
|
286
|
-
unitmatchpy-3.
|
|
282
|
+
unitmatchpy-3.3.1.dist-info/licenses/LICENSE,sha256=WAMqgXMZUjcGirAtQplIvDIz2OaFjRud39xH47vD2Ec,20844
|
|
283
|
+
unitmatchpy-3.3.1.dist-info/METADATA,sha256=gT3RTnZHaWZOIS4-Xam2Myxq1suxO8KfWVciaooXSaE,5315
|
|
284
|
+
unitmatchpy-3.3.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
285
|
+
unitmatchpy-3.3.1.dist-info/top_level.txt,sha256=EjaC3TLtFxUHy5xVS71T_IrmNpDUVUlXf-7GO32tuDI,12
|
|
286
|
+
unitmatchpy-3.3.1.dist-info/RECORD,,
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: UnitMatchPy
|
|
3
|
-
Version: 3.2.9
|
|
4
|
-
Summary: Automatic matching of neurons across sessions
|
|
5
|
-
Author: Enny van Beest, Célian Bimbard, Suyash Agarwal, Wentao Qiu
|
|
6
|
-
License: CC BY-NC-SA 4.0 International
|
|
7
|
-
Classifier: Programming Language :: Python :: 3
|
|
8
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
9
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
-
Classifier: Operating System :: OS Independent
|
|
13
|
-
Requires-Python: >=3.9
|
|
14
|
-
Description-Content-Type: text/markdown
|
|
15
|
-
License-File: LICENSE
|
|
16
|
-
Requires-Dist: numpy<2.0,>=1.21
|
|
17
|
-
Requires-Dist: scipy<2.0,>=1.9
|
|
18
|
-
Requires-Dist: pandas<3.0,>=1.5
|
|
19
|
-
Requires-Dist: matplotlib<4.0,>=3.6
|
|
20
|
-
Requires-Dist: joblib<2.0,>=1.2
|
|
21
|
-
Requires-Dist: tqdm<5.0,>=4.64
|
|
22
|
-
Requires-Dist: h5py<4.0,>=3.8
|
|
23
|
-
Requires-Dist: scikit-learn<2.0,>=1.2
|
|
24
|
-
Requires-Dist: mtscomp
|
|
25
|
-
Requires-Dist: torch<3.0,>=2.1
|
|
26
|
-
Provides-Extra: full
|
|
27
|
-
Requires-Dist: mat73<1.0,>=0.62; extra == "full"
|
|
28
|
-
Requires-Dist: spikeinterface<0.120,>=0.100; extra == "full"
|
|
29
|
-
Provides-Extra: notebooks
|
|
30
|
-
Requires-Dist: ipykernel<7,>=6; extra == "notebooks"
|
|
31
|
-
Provides-Extra: dev
|
|
32
|
-
Requires-Dist: pytest; extra == "dev"
|
|
33
|
-
Requires-Dist: ruff; extra == "dev"
|
|
34
|
-
Requires-Dist: mypy; extra == "dev"
|
|
35
|
-
Requires-Dist: build; extra == "dev"
|
|
36
|
-
Requires-Dist: twine; extra == "dev"
|
|
37
|
-
Dynamic: license-file
|
|
38
|
-
|
|
39
|
-
# Unit Match - Python
|
|
40
|
-
|
|
41
|
-
## Run UMPy
|
|
42
|
-
|
|
43
|
-
To run UMPy standard spike sorting data is needed; channel positions and 2 extracted raw waveforms for each unit. This can be calculated externally [BombCell](https://github.com/Julie-Fabre/bombcell) or using *extract_raw_demo.ipynb* to extract these waveforms from compressed data (.cbin and .ch) or raw data. There is also a [Spike Interface](https://spikeinterface.readthedocs.io/en/latest/) integrated notebook *UMPy_spike_interface_demo.ipynb* which uses spike interface to get this data.
|
|
44
|
-
Be careful not to mix and match the different ways of extracting raw waveforms, as there are difference between the methods.
|
|
45
|
-
|
|
46
|
-
There are to example notebooks for running UMPy *UMPy_example.ipynb* and *UMPy_example_detailed.ipynb*. These notebooks will guide you through running Unit Match all you need to supply is paths to the data. *UMPy_example.ipynb* is recommended to use first as it is simpler, however *UMPy_example_detailed.ipynb* may be useful in unique cases as it is more modular.
|
|
47
|
-
|
|
48
|
-
The GUI is a optional step to curated and investigate the information Unit Match has calculated; for efficient usage of the GUI please look at *GUI_Reference_Guide.md* in the Demo Notebooks folder.
|
|
49
|
-
|
|
50
|
-
## Dependencies
|
|
51
|
-
|
|
52
|
-
This version relies on many core python packages: [numpy](https://numpy.org/), [scipy](https://scipy.org/), [JobLib](https://joblib.readthedocs.io/en/stable/), [pandas](https://pandas.pydata.org/), [tkinter](https://docs.python.org/3/library/tkinter.html) and [matplotlib](https://matplotlib.org/). All of these libaries come with a [Anaconda](https://www.anaconda.com/download/) version of python.
|
|
53
|
-
For extracting raw data, the library [mtscomp](https://github.com/int-brain-lab/mtscomp) is needed, and can be installed by `pip install mtscomp`.
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
## Installation
|
|
57
|
-
|
|
58
|
-
After creating an python environment
|
|
59
|
-
|
|
60
|
-
```
|
|
61
|
-
conda create --name UnitMatch python==3.9
|
|
62
|
-
conda activate UnitMatch
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
You can install UnitMatchPy with pip. It will automatically install all the dependencies.
|
|
66
|
-
|
|
67
|
-
```
|
|
68
|
-
pip install UnitMatchPy
|
|
69
|
-
```
|
|
File without changes
|
|
File without changes
|