UnitMatchPy 3.5.0__py3-none-any.whl → 3.6.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
@@ -386,6 +386,11 @@ def run_GUI():
386
386
  ).squeeze()
387
387
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
388
388
  option_a = matches_avg[tmp_idx_a[in_both], :].tolist()
389
+ if len(option_a) == 0:
390
+ # no cross-session matches above the threshold for this session pair -
391
+ # fall back to the first unit of each session so the GUI still opens
392
+ print(f"No matches found between session {session_a} and session {session_b} at the current threshold.")
393
+ option_a = [[session_switch[session_a - 1], session_switch[session_b - 1]]]
389
394
 
390
395
  entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
391
396
  entry_a.set(option_a[0][0])
@@ -417,6 +422,11 @@ def run_GUI():
417
422
  option_a = matches_GUI[CV_option][tmp_idx_a[in_both], :].tolist()
418
423
  if CV_option == 0:
419
424
  option_a = sorted(option_a)
425
+ if len(option_a) == 0:
426
+ # no cross-session matches above the threshold for this session pair -
427
+ # fall back to the first unit of each session so the GUI still opens
428
+ print(f"No matches found between session {session_a} and session {session_b} at the current threshold.")
429
+ option_a = [[session_switch[session_a - 1], session_switch[session_b - 1]]]
420
430
 
421
431
  entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
422
432
  entry_a.set(option_a[0][0])
@@ -1309,6 +1319,11 @@ def update_unit_entryA(event):
1309
1319
  ).squeeze()
1310
1320
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
1311
1321
  option_a = matches_avg[tmp_idx_a[in_both], :].tolist()
1322
+ if len(option_a) == 0:
1323
+ # no cross-session matches above the threshold for this session pair -
1324
+ # fall back to the first unit of each session so the GUI still opens
1325
+ print(f"No matches found between session {session_a} and session {session_b} at the current threshold.")
1326
+ option_a = [[session_switch[session_a - 1], session_switch[session_b - 1]]]
1312
1327
 
1313
1328
  entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1314
1329
  entry_a.set(option_a[0][0])
@@ -1339,6 +1354,11 @@ def update_unit_entryA(event):
1339
1354
  option_a = matches_GUI[cv_option][tmp_idx_a[in_both], :].tolist()
1340
1355
  if cv_option == 0:
1341
1356
  option_a = sorted(option_a)
1357
+ if len(option_a) == 0:
1358
+ # no cross-session matches above the threshold for this session pair -
1359
+ # fall back to the first unit of each session so the GUI still opens
1360
+ print(f"No matches found between session {session_a} and session {session_b} at the current threshold.")
1361
+ option_a = [[session_switch[session_a - 1], session_switch[session_b - 1]]]
1342
1362
 
1343
1363
  entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1344
1364
  entry_a.set(option_a[0][0])
@@ -2113,7 +2133,7 @@ def order_good_sites(good_sites, channel_pos, n_sessions):
2113
2133
  reordered_good_sites = good_sites[reordered_idx]
2114
2134
 
2115
2135
  # re-arange x-axis so it goes (smaller x, bigger x)
2116
- for i in range(9):
2136
+ for i in range(len(reordered_good_sites) // 2):
2117
2137
  a, b = channel_pos[n_sessions][reordered_good_sites[[2 * i, 2 * i + 1]], 1]
2118
2138
 
2119
2139
  if a > b:
@@ -632,6 +632,8 @@ def get_threshold(total_score, within_session, euclid_dist, param, is_first_pass
632
632
  score_vector = param["score_vector"]
633
633
  Bins = param["bins"]
634
634
 
635
+ all_same_score = np.all(total_score == total_score.flat[0])
636
+
635
637
  tmp = total_score.copy()
636
638
  tmp[euclid_dist > param["neighbour_dist"]] = np.nan
637
639
 
@@ -664,7 +666,15 @@ def get_threshold(total_score, within_session, euclid_dist, param, is_first_pass
664
666
  mask = (hd_s[:min_len] > hnd_s[:min_len]) & (score_vector_use > 0.6)
665
667
  crossing_idx = np.flatnonzero(mask)
666
668
  if crossing_idx.size == 0:
667
- thrs_opt = 0.6
669
+ # A genuinely undefined crossing (e.g. sparse/degenerate histograms)
670
+ # falls back to the default 0.6. But if total_score is literally
671
+ # constant everywhere (e.g. a spatial-only ablation's placeholder
672
+ # similarity score), there is no meaningful "match vs non-match" split
673
+ # to find at all -- 0.6 would be arbitrary here, so use 0 instead,
674
+ # which makes every candidate pair count towards n_expected_matches at
675
+ # the caller (see run_deep_unit_match_core's total_score_for_threshold
676
+ # docstring for why that matters).
677
+ thrs_opt = 0.0 if all_same_score else 0.6
668
678
  else:
669
679
  thrs_opt = float(score_vector_use[crossing_idx[0]])
670
680
  # if ThrsOpt.size == 0:
UnitMatchPy/overlord.py CHANGED
@@ -73,6 +73,7 @@ def extract_metric_scores(
73
73
  param,
74
74
  niter=2,
75
75
  to_use=None,
76
+ extra_scores=None,
76
77
  ):
77
78
  """
78
79
  This function runs all of the metric calculations and drift correction to calculate the probability
@@ -93,6 +94,14 @@ def extract_metric_scores(
93
94
  2 is one pass of drift correction, by default 2
94
95
  to_use : list, optional
95
96
  A list of scores to include in the total score calculation. If None (default), all scores are included.
97
+ extra_scores : dict, optional
98
+ Additional precomputed (n_units, n_units) score arrays to fold into
99
+ scores_to_include alongside the built-in metrics (e.g. an externally
100
+ computed DNN similarity score), by default None. Merged in before the
101
+ to_use filtering, so combine with to_use to make an extra score the
102
+ sole driver of total_score/candidate_pairs/drift-correction/the Bayes
103
+ predictors -- see run_umpy_core's model parameter in
104
+ run_deepunitmatch_batch_onMerged.py for an example.
96
105
 
97
106
  Returns
98
107
  -------
@@ -151,6 +160,8 @@ def extract_metric_scores(
151
160
  "waveform_score": waveform_score,
152
161
  "trajectory_score": trajectory_score,
153
162
  }
163
+ if extra_scores:
164
+ scores_to_include.update(extra_scores)
154
165
  if to_use is not None:
155
166
  to_exclude = [key for key in scores_to_include if key not in to_use]
156
167
  for key in to_exclude:
@@ -189,7 +189,7 @@ def decay_and_average_waveform(
189
189
  spike_width = param["spike_width"]
190
190
  n_channels = param["n_channels"]
191
191
  new_peak_loc = param["peak_loc"]
192
- waveidx = param["waveidx"]
192
+ waveidx = np.asarray(param["waveidx"])
193
193
  channel_radius = param["channel_radius"]
194
194
  maxfev = param.get("curve_fit_maxfev", 10000)
195
195
  session_id = clus_info["session_id"]
UnitMatchPy/save_utils.py CHANGED
@@ -1,7 +1,20 @@
1
1
  import os
2
+ import json
2
3
  import pickle
3
4
  import pandas as pd
4
5
  import numpy as np
6
+ from pathlib import Path
7
+
8
+ def save_auc_summary(save_dir, auc_summary):
9
+ """
10
+ Save the scalar AUC values computed for this output (one per functional
11
+ score) as a small standalone JSON file. Otherwise these numbers only ever
12
+ get printed to console/logs -- MatchTable.csv holds the raw per-pair
13
+ functional-score matrices, which let you recompute an AUC but don't store
14
+ the number itself anywhere discoverable alongside the rest of the output.
15
+ """
16
+ with open(os.path.join(save_dir, "AUC_summary.json"), "w") as f:
17
+ json.dump(auc_summary, f, indent=2)
5
18
 
6
19
 
7
20
  def make_match_table(
@@ -625,3 +638,119 @@ def save_prob_for_phy(probability, param, clus_info):
625
638
  matrix_prob = session_output
626
639
 
627
640
  np.save(save_file_tmp, matrix_prob)
641
+
642
+
643
+ def make_UnitMatch_folder_from_sorting_analyzers(analyzers, save_dir):
644
+ """
645
+ Creates a folder called `save_dir` for a single session,
646
+ which can be used to run UnitMatch.
647
+
648
+ The output folder has the structure
649
+
650
+ unitmatch_dir/
651
+ Session{i}/
652
+ # (num_units, 3) dimensional array of channel locations
653
+ channel_locations.npy
654
+
655
+ # List of curated labels, using BombCell
656
+ bombcell_labels.tsv
657
+
658
+ # (num_time_samples, num_channels, 2) array of average waveforms
659
+ # for each unit. Each file contains the average waveform for both
660
+ # the first half and the second half of the recording.
661
+ Unit0_RawSpikes.npy
662
+ Unit1_RawSpikes.npy
663
+ ...
664
+ UnitN_RawSpikes.npy
665
+
666
+ # waveform specific params, from si waveform extension
667
+ waveform_params.json
668
+ """
669
+
670
+ # only import spikeinterface here, so that non-si users don't need to have it in their env
671
+ import spikeinterface.full as si
672
+
673
+ save_dir = Path(save_dir)
674
+ save_dir.mkdir(exist_ok=True)
675
+
676
+ required_extensions = ['random_spikes', 'waveforms', 'templates', 'template_metrics', 'quality_metrics']
677
+
678
+ for session_index, analyzer in enumerate(analyzers):
679
+
680
+ missing_extensions = []
681
+ for extension in required_extensions:
682
+ if not analyzer.has_extension(extension):
683
+ missing_extensions.append(extension)
684
+ if len(missing_extensions) > 0:
685
+ raise ValueError(f"Analyzer must have {missing_extensions} extensions computed.\n" \
686
+ "Please compute them by running `sorting_analyzer.compute({missing_extensions})")
687
+
688
+ session_dir = save_dir / f'Session{session_index}'
689
+ session_dir.mkdir(exist_ok=True)
690
+
691
+ # TEMPLATES / RAWSPIKES
692
+
693
+ half_samples = analyzer.get_num_samples() // 2
694
+ waveforms = analyzer.get_extension('waveforms')
695
+ random_spikes = analyzer.get_extension('random_spikes')
696
+
697
+ for unit_id in analyzer.unit_ids:
698
+
699
+ both_halves_average_waveform_dense = np.zeros((np.shape(waveforms.get_data())[1], analyzer.get_num_channels(), 2))
700
+
701
+ unit_random_spikes = random_spikes.get_selected_indices_in_spike_train(unit_id = unit_id, segment_index=0)
702
+ first_half_mask = analyzer.sorting.get_unit_spike_train(unit_id = unit_id)[unit_random_spikes] < half_samples
703
+
704
+ first_half_waveforms = waveforms.get_waveforms_one_unit(unit_id = unit_id)[first_half_mask]
705
+ second_half_waveforms = waveforms.get_waveforms_one_unit(unit_id = unit_id)[~first_half_mask]
706
+
707
+ first_half_average_waveform_sparse = np.average(first_half_waveforms, axis=0)
708
+ second_half_average_waveform_sparse = np.average(second_half_waveforms, axis=0)
709
+
710
+ channel_indices = analyzer.sparsity.unit_id_to_channel_indices[unit_id]
711
+
712
+ both_halves_average_waveform_dense[:, channel_indices, 0] = first_half_average_waveform_sparse[:, :channel_indices.size]
713
+ both_halves_average_waveform_dense[:, channel_indices, 1] = second_half_average_waveform_sparse[:, :channel_indices.size]
714
+
715
+ np.save(session_dir / f"Unit{unit_id}_RawSpikes.npy", both_halves_average_waveform_dense)
716
+
717
+ # UNIT CURATION
718
+
719
+ bombcell_labels = si.bombcell_label_units(analyzer)
720
+ bombcell_labels.to_csv(session_dir / "bombcell_labels.tsv", sep='\t')
721
+
722
+ # CHANNEL POSITION
723
+
724
+ # UnitMatchPy's shank-partitioning code (get_probe_geometry, metric_functions.py)
725
+ # expects column 1 to be the X (shank) axis, matching the convention
726
+ # utils.paths_from_KS() uses for classic Kilosort-loaded positions: a
727
+ # placeholder column of 1's is inserted at position 0, giving [1, X, Y].
728
+ # Padding with a trailing Z=0 instead (giving [X, Y, 0]) shifts X to column 0,
729
+ # which silently breaks per-shank drift correction on multi-shank probes.
730
+ channel_locations = analyzer.get_channel_locations()
731
+ channel_locations_3D = np.insert(
732
+ channel_locations, 0, np.ones(channel_locations.shape[0]), axis=1
733
+ )
734
+
735
+ np.save(session_dir / "channel_locations.npy", channel_locations_3D)
736
+
737
+ # WAVEFORM PARAMS
738
+
739
+ ms_before = analyzer.get_extension('waveforms').params.get('ms_before')
740
+ ms_after = analyzer.get_extension('waveforms').params.get('ms_after')
741
+
742
+ spike_width = int( (ms_after + ms_before) * analyzer.sampling_frequency/1000 )
743
+ peak_loc = int( spike_width * ms_before / (ms_before + ms_after) )
744
+
745
+ waveidx = np.arange(peak_loc - 8, peak_loc + 15, dtype=int)
746
+ # make waveidx json serializable
747
+ waveidx = [int(idx) for idx in waveidx]
748
+
749
+ params_waveform = {
750
+ 'spike_width': spike_width,
751
+ 'peak_loc': peak_loc,
752
+ 'waveidx': waveidx
753
+ }
754
+
755
+ with open(session_dir / "waveform_params.json", "w") as f:
756
+ json.dump(params_waveform, f, indent=2)
UnitMatchPy/utils.py CHANGED
@@ -277,11 +277,11 @@ def load_good_waveforms(wave_paths, unit_label_paths, param, good_units_only=Tru
277
277
  f"Warning: loaded waveform spike_width ({actual_width}) does not match "
278
278
  f"param['spike_width'] ({param['spike_width']}). Updating to match data."
279
279
  )
280
- param["spike_width"] = actual_width
281
- param["peak_loc"] = int(np.floor(actual_width / 2))
282
- param["waveidx"] = np.arange(
283
- param["peak_loc"] - 8, param["peak_loc"] + 15, dtype=int
284
- )
280
+ param["spike_width"] = actual_width
281
+ param["peak_loc"] = int(np.floor(actual_width / 2))
282
+ param["waveidx"] = np.arange(
283
+ param["peak_loc"] - 8, param["peak_loc"] + 15, dtype=int
284
+ )
285
285
 
286
286
  return waveform, session_id, session_switch, within_session, good_units, param
287
287
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: UnitMatchPy
3
- Version: 3.5.0
3
+ Version: 3.6.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
@@ -54,7 +54,7 @@ This repository contains:
54
54
 
55
55
  ## Versions
56
56
 
57
- - **UnitMatchPy version:** `3.5.0` (from `pyproject.toml`)
57
+ - **UnitMatchPy version:** `3.6.1` (from `pyproject.toml`)
58
58
  - **DeepUnitMatch:** code lives under `DeepUnitMatch/` (see **DeepUnitMatch (DUM)** section)
59
59
 
60
60
  ## System requirements
@@ -74,6 +74,34 @@ conda create -n UMPy python=3.11 pip #(press y when prompted)
74
74
  conda activate UMPy
75
75
  ```
76
76
 
77
+ ### GPU (CUDA) users: install this first
78
+
79
+ Skip this if you're on macOS (no CUDA) or don't have an NVIDIA GPU -- Option A/B below
80
+ will just install the CPU build automatically, no extra steps needed.
81
+
82
+ If you do have an NVIDIA GPU (Windows/Linux) and want DeepUnitMatch to run on it, install
83
+ the CUDA-enabled PyTorch build **before** Option A or B below:
84
+
85
+ ```bash
86
+ pip install --extra-index-url https://download.pytorch.org/whl/cu126 torch
87
+ ```
88
+
89
+ (if you've cloned this repo, `pip install -r requirements-cuda.txt` from this folder does
90
+ the same thing). Do this first because plain `pip install UnitMatchPy` / `pip install -e .`
91
+ alone always installs the CPU-only build -- PyPI's default `torch` wheel is CPU-only, and
92
+ pip has no way to detect that a GPU is present. Once torch is already installed and
93
+ satisfies the version range Option A/B ask for, they'll leave it alone instead of
94
+ overwriting it with the CPU build.
95
+
96
+ Verify it worked:
97
+
98
+ ```bash
99
+ python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
100
+ ```
101
+
102
+ This should print a version ending in `+cuXXX` (not `+cpu`) and `True`. If it's not, see
103
+ `pyproject.toml`'s `torch` dependency comment, or check `nvidia-smi` shows a working driver.
104
+
77
105
  Then install using pip (options below). This step should take less than few minutes.
78
106
 
79
107
  ### Option A: Install the released package (PyPI)
@@ -1,4 +1,4 @@
1
- UnitMatchPy/GUI.py,sha256=14fPiOL1p5ea4eb_Q04LsePxDuYeRVn_WkfnseSQZBA,78172
1
+ UnitMatchPy/GUI.py,sha256=SvHLcMMT4Mrx8wodj86Ko7XJa5OWwKEYuN3QZr4ZF_M,79801
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=OZlVm0WMwJL3gKakC1UJ7qNRRk_1qIu6VViomHQ_d_w,268
@@ -6,12 +6,12 @@ UnitMatchPy/assign_unique_id.py,sha256=TqypaVJAMNp9WkxoBSQTimNGkOUDVR0JFR9_-YKtk
6
6
  UnitMatchPy/bayes_functions.py,sha256=D-AnLVrKvsR82ZjWY-wCEunMNdPxHe2xX3ZNA3i8NgI,4676
7
7
  UnitMatchPy/default_params.py,sha256=YltBBQsYq8Tl8XYx4QNptwAUrTxn2005OPhEuM-5U94,2512
8
8
  UnitMatchPy/extract_raw_data.py,sha256=vBakf4F9MZkaWkQ6tKCd9OFi8pHBNs0l454B7l_RDM4,10934
9
- UnitMatchPy/metric_functions.py,sha256=aFu5FRZ4XsCje3O9Qz5PHinakN6lRKqk0KZI1E-8Tvc,43937
10
- UnitMatchPy/overlord.py,sha256=6Q_GegMT7uqAw3gHbwvTq1Wc3o24Zb0OWwbMfSmk1eg,6914
11
- UnitMatchPy/param_functions.py,sha256=MINVXDr0YuShxC7NFwQKXPE8WN03OHs6Igucvcc5xlY,18237
9
+ UnitMatchPy/metric_functions.py,sha256=1lcydiyt11xsfs_NLmoq2hiyuYRCqk0zyamihn6TVrk,44608
10
+ UnitMatchPy/overlord.py,sha256=vQAq6C8IZrohDiYRktwHLUsUzCyampoCexyqwQVY2Ig,7553
11
+ UnitMatchPy/param_functions.py,sha256=SrLbg72hkLbALC1j0EpeIpwory6u3VkK2Re9VHAHtXU,18249
12
12
  UnitMatchPy/run.py,sha256=hu5U0sKLrP1Wi4aQCjasqK3ZpJuDcabX4XmGNjPxM8s,5973
13
- UnitMatchPy/save_utils.py,sha256=D0sm_Bum2QTaCLDHf-SrOygfc9lQ8bQi3SWh-tmeI5k,20856
14
- UnitMatchPy/utils.py,sha256=H3snFIqRv_wwmyUuQ6aMEtVodmHJ4B8K_RiZVYPMkLw,45463
13
+ UnitMatchPy/save_utils.py,sha256=GSrXc5PVRPncBqOic21ibK9Ar_jqBQ9cd0cfGHUIsuA,26481
14
+ UnitMatchPy/utils.py,sha256=1dfIx-Be5_UbkiGPwqJnRnr5heLHnCfLpJTxu8REvRc,45483
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.5.0.dist-info/licenses/LICENSE,sha256=WAMqgXMZUjcGirAtQplIvDIz2OaFjRud39xH47vD2Ec,20844
283
- unitmatchpy-3.5.0.dist-info/METADATA,sha256=lEvAA84xUUqwW7XDX87xkJ-LXO-D-PRjRL5TiU8I6uk,5444
284
- unitmatchpy-3.5.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
285
- unitmatchpy-3.5.0.dist-info/top_level.txt,sha256=EjaC3TLtFxUHy5xVS71T_IrmNpDUVUlXf-7GO32tuDI,12
286
- unitmatchpy-3.5.0.dist-info/RECORD,,
282
+ unitmatchpy-3.6.1.dist-info/licenses/LICENSE,sha256=WAMqgXMZUjcGirAtQplIvDIz2OaFjRud39xH47vD2Ec,20844
283
+ unitmatchpy-3.6.1.dist-info/METADATA,sha256=wdmgnT_ZZe5j9sLxPDasUq-NoJE_7CcSgGGIXRnnMqw,6653
284
+ unitmatchpy-3.6.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
285
+ unitmatchpy-3.6.1.dist-info/top_level.txt,sha256=EjaC3TLtFxUHy5xVS71T_IrmNpDUVUlXf-7GO32tuDI,12
286
+ unitmatchpy-3.6.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (83.0.0)
2
+ Generator: setuptools (84.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5