UnitMatchPy 3.3.0__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 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, sub_max_y = channel_pos[session_no_a][good_channels[1],[1,2]].squeeze()
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
@@ -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'])
@@ -252,6 +252,155 @@ def centroid_metrics(euclid_dist, param):
252
252
 
253
253
  return centroid_dist, centroid_var
254
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
+
255
404
  def get_recentered_euclidean_dist(avg_waveform_per_tp_flip, avg_centroid, param):
256
405
  """
257
406
  Find a Euclidean distance where the location per time has been centered around the average position
@@ -418,17 +567,39 @@ def get_threshold(total_score, within_session, euclid_dist, param, is_first_pass
418
567
  tmp[within_session == 1] = np.nan
419
568
 
420
569
  hd, __ = np.histogram(np.diag(tmp), Bins)
421
- hd = hd / param['n_units']
422
- hnd, __ = np.histogram( (tmp - tmp *np.eye(param['n_units'])), Bins)
423
- hnd = hnd / np.nansum( (tmp - tmp *np.eye(param['n_units'])) )
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
424
580
  hp, __ = np.histogram(tmp, Bins)
425
- hp = hp / np.nansum(tmp)
426
-
427
- thrs_opt = score_vector[np.argwhere( (pf.smooth(hd,3) > pf.smooth(hnd,3) ) * (score_vector > 0.6) == True)][0]
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]])
428
599
  # if ThrsOpt.size == 0:
429
600
  # ThrsOpt = 0.6 # give default threshold if above doestn return value
430
601
  # fit tmp to a normal ditn
431
- fit = tmp[ ~np.isnan(tmp) * (tmp < thrs_opt)]
602
+ fit = tmp[(~np.isnan(tmp)) & (tmp < thrs_opt)]
432
603
  muw = np.mean(fit)
433
604
  stdw = np.std(fit)
434
605
 
@@ -442,8 +613,12 @@ def get_threshold(total_score, within_session, euclid_dist, param, is_first_pass
442
613
  tmp[within_session == 0] = np.nan
443
614
 
444
615
  ha, __ = np.histogram(tmp, Bins)
445
- ha = ha / np.nansum(tmp)
446
- fit = tmp[ ~np.isnan(tmp) * (tmp < thrs_opt)]
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)]
447
622
  mua = np.mean(fit)
448
623
  stda = np.std(fit)
449
624
 
@@ -451,7 +626,7 @@ def get_threshold(total_score, within_session, euclid_dist, param, is_first_pass
451
626
  # for first pass only (i.e before drift correction)
452
627
  #This is to decrease the threshold for the first pass so that the threshold is lowered
453
628
  # as without drift correction even matches should have a lower total score
454
- if (~np.isnan(mua) and mua<muw):
629
+ if np.isfinite(mua) and np.isfinite(muw) and (mua < muw):
455
630
  thrs_opt = thrs_opt - np.abs(muw - mua)
456
631
 
457
632
  return thrs_opt
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.centroid_metrics(euclid_dist, param)
87
+ centroid_dist, centroid_var, euclid_dist = mf.get_euclidean_metrics_chunked(
88
+ avg_waveform_per_tp_flip, param)
89
89
 
90
- euclid_dist_rc = mf.get_recentered_euclidean_dist(avg_waveform_per_tp_flip, avg_centroid, param)
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 (especially in 4.0) may not include channel positions for inactive channels,
389
- as UnitMatch require the full channel_pos array this function will extrapolate it from the given channel positions.
390
- If there is only one missing positions will fill that in else it will go through each found missing position
391
- and attempt to fill them in iteratively, finally it will attempt to find a pattern in the x-coord and fill in positions that way
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
- The path to the KiloSort directory
417
+ Path to the KiloSort output directory.
397
418
  n_channels : int
398
- The number of channels
419
+ Total number of hardware channels (waveform array dimension).
399
420
 
400
421
  Returns
401
422
  -------
402
- ndarray
403
- The full channel_pos array
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 \n \
406
- we have attempted to fill in the missing positions, please check the attempt worked and examine the channel_positions and RawWaveforms shape')
407
- path_tmp = os.path.join(KS_dir, 'channel_positions.npy')
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
- #find the mode difference, i.e the steps between y-positions
431
- y_steps, y_step_counts = np.unique(np.diff(np.unique(same_y_pattern)), return_counts= True)
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
- #find the min/max y-positions to fill in all positions for the column
435
- ymin = np.min(same_y_pattern).astype(int)
436
- ymax = np.max(same_y_pattern).astype(int)
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
- channel_pos_column = np.stack((np.full_like(ypos,x), ypos)).T
440
- channel_pos_new.append(channel_pos_column)
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
- channel_pos_fill = channel_pos.copy()
449
- #find all the positions not in the original channel_positions
450
- missed_pos_idxs = np.argwhere(isin_2d(np.vstack(channel_pos_new), pos) == False)
451
- #find all the empty channel positions indexs
452
- empty_idx = np.unique(np.argwhere(np.isnan(channel_pos))[:,0])
453
-
454
- #check to see if there are the same amount of empty positions as found positions
455
- if missed_pos_idx.shape[0] == empty_idx.shape[0]:
456
- #go through each estimated missing positions
457
- for idx in missed_pos_idxs:
458
- missed_pos = np.vstack(channel_pos_new)[idx].squeeze()
459
- #find the index of the nearest channel to the estimated missing positions
460
- distance_to_pos = np.sqrt(np.sum((channel_pos - missed_pos)**2, axis = 1) )
461
- nearest_idx = np.nanargmin(distance_to_pos)
462
- #assume that the nearest missing index to the nearest positions is the correct index!
463
- estimated_missing_idx = empty_idx[np.argmin(np.abs(empty_idx - nearest_idx))]
464
- #fill in this index
465
- channel_pos_fill[estimated_missing_idx,:] = missed_pos
466
- #delete this index from the empty idx_list
467
- empty_idx = np.delete(empty_idx, np.argmin(np.abs(empty_idx - nearest_idx)))
468
-
469
- #If all of the original positions are correct
470
- if np.sum(channel_pos == channel_pos_fill) //2 == pos.shape[0]:
471
- print('Likely to be correctly filled')
472
- return channel_pos_fill
473
-
474
- n_unique_x = x_unique.shape[0]
475
- channel_pos_fill = np.zeros_like(channel_pos)
476
- test_points = []
477
- starts = []
478
- x_points = []
479
- #Often the channel positions is filled in in a periodic fashion in x coord
480
- for i, x in enumerate(x_unique):
481
- #find which sequence of positions this x-column fills
482
- x_point = np.argwhere(channel_pos[:,0] == x).squeeze()[0]
483
- start = x_point % n_unique_x
484
- points = np.arange(start, n_channels, n_unique_x)
485
- #fill in the positions for this column
486
- for j, point in enumerate(points):
487
- channel_pos_fill[point,:] = channel_pos_new[i][j,:]
488
-
489
- test_points.append(points)
490
- starts.append(start)
491
- x_points.append(x_point)
492
-
493
- #If all of the original positions are correct
494
- if np.sum(channel_pos == channel_pos_fill) //2 == pos.shape[0]:
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
- Have returned the known channel positions and NaN')
500
- return channel_pos
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
  """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: UnitMatchPy
3
- Version: 3.3.0
3
+ Version: 3.3.1
4
4
  Summary: Automatic matching of neurons across sessions
5
5
  Author: Enny van Beest, Célian Bimbard, Suyash Agarwal, Wentao Qiu
6
6
  License: CC BY-NC-SA 4.0 International
@@ -36,22 +36,27 @@ Requires-Dist: build; extra == "dev"
36
36
  Requires-Dist: twine; extra == "dev"
37
37
  Dynamic: license-file
38
38
 
39
- # UnitMatchPy (UMPy) and DeepUnitMatch (DUM)
39
+ # UnitMatchPy and DeepUnitMatch
40
40
 
41
41
  This repository contains:
42
- - **UnitMatchPy (UMPy)**: automatic matching of neurons across sessions (Python package).
43
- - **DeepUnitMatch (DUM)**: DeepUnitMatch pipeline and demos (see preprint below).
42
+ - **UnitMatchPy**: automatic matching of neurons across sessions (Python package).
43
+ - **DeepUnitMatch**: DeepUnitMatch pipeline and demos (see preprint below).
44
44
 
45
45
  ## References
46
46
 
47
- - **UnitMatch (UMPy):** https://www.nature.com/articles/s41592-024-02440-1
48
- - **DeepUnitMatch (DUM) preprint:** https://www.biorxiv.org/content/10.64898/2026.01.30.702777v1
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
49
 
50
50
  ## Versions
51
51
 
52
- - **UnitMatchPy version:** `3.2.9` (from `pyproject.toml`)
52
+ - **UnitMatchPy version:** `3.3.1` (from `pyproject.toml`)
53
53
  - **DeepUnitMatch:** code lives under `DeepUnitMatch/` (see **DeepUnitMatch (DUM)** section)
54
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
+
55
60
  ## Installation
56
61
 
57
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.
@@ -64,7 +69,7 @@ conda create -n UMPy python=3.11 pip #(press y when prompted)
64
69
  conda activate UMPy
65
70
  ```
66
71
 
67
- Then install using pip (options below).
72
+ Then install using pip (options below). This step should take less than few minutes.
68
73
 
69
74
  ### Option A: Install the released package (PyPI)
70
75
 
@@ -83,11 +88,13 @@ pip install "UnitMatchPy[full,notebooks]"
83
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:
84
89
 
85
90
  ```bash
86
- # Windows (PowerShell)
87
- cd $HOME\Documents\GitHub\DeepUnitMatch\UnitMatchPy
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
88
95
 
89
96
  # macOS / Linux
90
- cd ~/Documents/GitHub/DeepUnitMatch/UnitMatchPy
97
+ cd ~/Documents/GitHub/UnitMatch/UnitMatchPy
91
98
  ```
92
99
 
93
100
  ```bash
@@ -104,9 +111,9 @@ pip install -e ".[full,notebooks]"
104
111
 
105
112
  All demo notebooks are in `Demo Notebooks/`.
106
113
 
107
- ### Run UnitMatchPy (UMPy)
114
+ ### Run UnitMatchPy
108
115
 
109
- To run UMPy, 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:
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:
110
117
  - `Demo Notebooks/extract_raw_data_demo.ipynb` (compressed `.cbin`/`.ch` or raw)
111
118
  - `Demo Notebooks/extract_raw_data_demo_open_ephys.ipynb` (Open Ephys)
112
119
  - `Demo Notebooks/UMPy_spike_interface_demo.ipynb` ([SpikeInterface](https://spikeinterface.readthedocs.io/en/latest/) workflow)
@@ -117,11 +124,13 @@ Example notebooks:
117
124
 
118
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.
119
126
 
120
- ## DeepUnitMatch (DUM)
127
+ ### Run DeepUnitMatch
121
128
 
122
129
  To try the DeepUnitMatch version, start with:
123
130
  - `Demo Notebooks/DeepUnitMatch.ipynb`
124
131
 
132
+ It should take just a few minutes to run on a standard PC.
133
+
125
134
  If you want to train / fine-tune a model on your own data, see:
126
135
  - `Demo Notebooks/DUM_training.ipynb`
127
136
 
@@ -1,17 +1,17 @@
1
- UnitMatchPy/GUI.py,sha256=Oe75QpMorFzKNt-SxE2y9zth8RHg0nXzhWR4adMvfbM,72505
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=2Hl6F7cQHce3bYreBg3gLF7tk8fqOgeHYAhzbVUxB0o,1739
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=Mplybp1MxvzbdNuD6AuvKz4dctHZIvHRDSxe7VLXj7Q,35277
10
- UnitMatchPy/overlord.py,sha256=CeQk2OkpHHKOeCazhaOejyzxj_ZLrja4xY5dy92uxsc,6590
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=p_rBsIZ3CFEi6joHgdqNvIC2nkbArE98MWt9F8BI_Mc,40174
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.3.0.dist-info/licenses/LICENSE,sha256=WAMqgXMZUjcGirAtQplIvDIz2OaFjRud39xH47vD2Ec,20844
283
- unitmatchpy-3.3.0.dist-info/METADATA,sha256=wAbpGkphqdOjDc9KF68Rjlx2VWw9qogqXqWeF1tdcyM,4718
284
- unitmatchpy-3.3.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
285
- unitmatchpy-3.3.0.dist-info/top_level.txt,sha256=EjaC3TLtFxUHy5xVS71T_IrmNpDUVUlXf-7GO32tuDI,12
286
- unitmatchpy-3.3.0.dist-info/RECORD,,
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,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.0)
2
+ Generator: setuptools (82.0.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5