UnitMatchPy 3.4.1__py3-none-any.whl → 3.6.0__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
@@ -1,18 +1,19 @@
1
1
  from tkinter import *
2
2
  from tkinter import ttk
3
- import matplotlib.pyplot as plt
4
- from matplotlib.figure import Figure
5
- from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
3
+ from matplotlib.figure import Figure
4
+ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
6
5
  import numpy as np
7
6
  from matplotlib import rcParams
8
7
  import os
9
8
  import pickle
10
9
 
11
10
 
12
- def precalculate_all_acgs(clus_info, param, save_path=None, bin_size=0.001, max_lag=0.05):
11
+ def precalculate_all_acgs(
12
+ clus_info, param, save_path=None, bin_size=0.001, max_lag=0.05
13
+ ):
13
14
  """
14
15
  Pre-calculate and save autocorrelograms for all units to speed up GUI loading
15
-
16
+
16
17
  Parameters
17
18
  ----------
18
19
  clus_info : dict
@@ -25,54 +26,56 @@ def precalculate_all_acgs(clus_info, param, save_path=None, bin_size=0.001, max_
25
26
  Bin size in seconds (default 1ms)
26
27
  max_lag : float
27
28
  Maximum lag in seconds (default 50ms)
28
-
29
+
29
30
  Returns
30
31
  -------
31
32
  acg_cache : dict
32
33
  Dictionary mapping unit_id to (autocorr, bin_centers) tuples
33
34
  """
34
35
  print("Pre-calculating autocorrelograms for all units...")
35
-
36
+
36
37
  if save_path is None:
37
- save_path = 'acg_cache.pkl'
38
-
38
+ save_path = "acg_cache.pkl"
39
+
39
40
  acg_cache = {}
40
- n_units = len(clus_info.get('session_id', []))
41
-
41
+ n_units = len(clus_info.get("session_id", []))
42
+
42
43
  for unit_id in range(n_units):
43
44
  try:
44
45
  # Get spike times for this unit
45
46
  spike_times = get_spike_times_for_unit_precalc(unit_id, clus_info, param)
46
-
47
+
47
48
  if len(spike_times) > 1:
48
49
  # Compute ACG
49
- autocorr, bin_centers = compute_acg_precalc(spike_times, bin_size, max_lag)
50
+ autocorr, bin_centers = compute_acg_precalc(
51
+ spike_times, bin_size, max_lag
52
+ )
50
53
  acg_cache[unit_id] = (autocorr, bin_centers)
51
-
54
+
52
55
  if (unit_id + 1) % 50 == 0: # Progress update every 50 units
53
56
  print(f"Processed {unit_id + 1}/{n_units} units")
54
57
  else:
55
58
  acg_cache[unit_id] = (np.array([]), np.array([]))
56
-
59
+
57
60
  except Exception as e:
58
61
  print(f"Error computing ACG for unit {unit_id}: {e}")
59
62
  acg_cache[unit_id] = (np.array([]), np.array([]))
60
-
63
+
61
64
  # Save to file
62
65
  try:
63
- with open(save_path, 'wb') as f:
66
+ with open(save_path, "wb") as f:
64
67
  pickle.dump(acg_cache, f)
65
68
  print(f"ACG cache saved to {save_path}")
66
69
  except Exception as e:
67
70
  print(f"Error saving ACG cache: {e}")
68
-
71
+
69
72
  return acg_cache
70
73
 
71
74
 
72
75
  def get_spike_times_for_unit_precalc(unit_id, clus_info, param):
73
76
  """
74
77
  Get spike times for a specific unit (used in pre-calculation)
75
-
78
+
76
79
  Parameters
77
80
  ----------
78
81
  unit_id : int
@@ -81,7 +84,7 @@ def get_spike_times_for_unit_precalc(unit_id, clus_info, param):
81
84
  Cluster information dictionary
82
85
  param : dict
83
86
  Parameters dictionary
84
-
87
+
85
88
  Returns
86
89
  -------
87
90
  spike_times : array
@@ -89,56 +92,58 @@ def get_spike_times_for_unit_precalc(unit_id, clus_info, param):
89
92
  """
90
93
  try:
91
94
  # Get session information for this unit
92
- session_id = clus_info['session_id'][unit_id]
93
- original_id = clus_info['original_ids'][unit_id]
94
-
95
+ session_id = clus_info["session_id"][unit_id]
96
+ original_id = clus_info["original_ids"][unit_id]
97
+
95
98
  # Get the Kilosort directory for this session
96
- if 'KS_dirs' in param:
97
- ks_dir = param['KS_dirs'][session_id]
99
+ if "KS_dirs" in param:
100
+ ks_dir = param["KS_dirs"][session_id]
98
101
  else:
99
102
  return np.array([])
100
-
103
+
101
104
  # Load Kilosort spike times and cluster assignments
102
- spike_times_path = os.path.join(ks_dir, 'spike_times.npy')
103
- spike_clusters_path = os.path.join(ks_dir, 'spike_clusters.npy')
104
-
105
+ spike_times_path = os.path.join(ks_dir, "spike_times.npy")
106
+ spike_clusters_path = os.path.join(ks_dir, "spike_clusters.npy")
107
+
105
108
  if os.path.exists(spike_times_path) and os.path.exists(spike_clusters_path):
106
109
  # Load spike times (in samples) and cluster assignments
107
110
  spike_times_samples = np.load(spike_times_path).flatten()
108
111
  spike_clusters = np.load(spike_clusters_path).flatten()
109
-
112
+
110
113
  # Get sampling rate - try to load from params.py or use default
111
114
  try:
112
- params_path = os.path.join(ks_dir, 'params.py')
115
+ params_path = os.path.join(ks_dir, "params.py")
113
116
  sample_rate = 30000 # Default sample rate
114
117
  if os.path.exists(params_path):
115
118
  # Parse params.py for sample_rate
116
- with open(params_path, 'r') as f:
119
+ with open(params_path, "r") as f:
117
120
  params_content = f.read()
118
121
  # Extract sample_rate
119
- for line in params_content.split('\n'):
120
- if 'sample_rate' in line and '=' in line:
121
- sample_rate = float(line.split('=')[1].strip())
122
+ for line in params_content.split("\n"):
123
+ if "sample_rate" in line and "=" in line:
124
+ sample_rate = float(line.split("=")[1].strip())
122
125
  break
123
126
  except:
124
127
  sample_rate = 30000 # Fallback
125
-
128
+
126
129
  # Get spike times for this specific unit
127
130
  unit_mask = spike_clusters == original_id
128
- unit_spike_times = spike_times_samples[unit_mask] / sample_rate # Convert to seconds
129
-
131
+ unit_spike_times = (
132
+ spike_times_samples[unit_mask] / sample_rate
133
+ ) # Convert to seconds
134
+
130
135
  return unit_spike_times
131
136
  else:
132
137
  return np.array([])
133
-
134
- except Exception as e:
138
+
139
+ except Exception:
135
140
  return np.array([])
136
141
 
137
142
 
138
143
  def compute_acg_precalc(spike_times, bin_size=0.001, max_lag=0.05):
139
144
  """
140
145
  Compute autocorrelogram for a unit (used in pre-calculation)
141
-
146
+
142
147
  Parameters
143
148
  ----------
144
149
  spike_times : array
@@ -147,7 +152,7 @@ def compute_acg_precalc(spike_times, bin_size=0.001, max_lag=0.05):
147
152
  Bin size in seconds (default 1ms)
148
153
  max_lag : float
149
154
  Maximum lag in seconds (default 50ms)
150
-
155
+
151
156
  Returns
152
157
  -------
153
158
  autocorr : array
@@ -157,48 +162,48 @@ def compute_acg_precalc(spike_times, bin_size=0.001, max_lag=0.05):
157
162
  """
158
163
  if len(spike_times) < 2:
159
164
  return np.array([]), np.array([])
160
-
165
+
161
166
  # Create bins centered around 0
162
167
  bins = np.arange(-max_lag, max_lag + bin_size, bin_size)
163
- bin_centers = bins[:-1] + bin_size/2
164
-
168
+ bin_centers = bins[:-1] + bin_size / 2
169
+
165
170
  # Calculate autocorrelogram
166
171
  autocorr = np.zeros(len(bin_centers))
167
-
172
+
168
173
  # For each spike, find all other spikes within max_lag
169
174
  for i, spike_time in enumerate(spike_times):
170
175
  # Find spikes within the lag window
171
176
  time_diffs = spike_times - spike_time
172
177
  valid_diffs = time_diffs[(np.abs(time_diffs) <= max_lag) & (time_diffs != 0)]
173
-
178
+
174
179
  # Bin the time differences
175
180
  hist, _ = np.histogram(valid_diffs, bins)
176
181
  autocorr += hist
177
-
182
+
178
183
  # Convert to firing rate (Hz)
179
184
  total_time = spike_times[-1] - spike_times[0] if len(spike_times) > 1 else 1
180
185
  n_spikes = len(spike_times)
181
186
  autocorr = autocorr / (bin_size * n_spikes * total_time)
182
-
187
+
183
188
  return autocorr, bin_centers
184
189
 
185
190
 
186
- def load_acg_cache(cache_path='acg_cache.pkl'):
191
+ def load_acg_cache(cache_path="acg_cache.pkl"):
187
192
  """
188
193
  Load pre-calculated ACG cache from file
189
-
194
+
190
195
  Parameters
191
196
  ----------
192
197
  cache_path : str
193
198
  Path to the ACG cache file
194
-
199
+
195
200
  Returns
196
201
  -------
197
202
  acg_cache : dict or None
198
203
  Dictionary mapping unit_id to (autocorr, bin_centers) tuples, or None if loading failed
199
204
  """
200
205
  try:
201
- with open(cache_path, 'rb') as f:
206
+ with open(cache_path, "rb") as f:
202
207
  acg_cache = pickle.load(f)
203
208
  print(f"ACG cache loaded from {cache_path}")
204
209
  return acg_cache
@@ -247,16 +252,15 @@ def run_GUI():
247
252
  # Try to load pre-calculated ACG cache
248
253
  acg_cache = load_acg_cache()
249
254
 
250
- rcParams.update({'figure.autolayout': True})
251
- rcParams.update({'font.size': 14})
252
- rcParams.update({'font.family': 'DejaVu Sans'})
253
- color = 'white'
254
- rcParams['text.color'] = color
255
- rcParams['axes.labelcolor'] = color
256
- rcParams['xtick.color'] = color
257
- rcParams['ytick.color'] = color
255
+ rcParams.update({"figure.autolayout": True})
256
+ rcParams.update({"font.size": 14})
257
+ rcParams.update({"font.family": "DejaVu Sans"})
258
+ color = "white"
259
+ rcParams["text.color"] = color
260
+ rcParams["axes.labelcolor"] = color
261
+ rcParams["xtick.color"] = color
262
+ rcParams["ytick.color"] = color
258
263
 
259
-
260
264
  np.set_printoptions(suppress=True)
261
265
  is_match = []
262
266
  not_match = []
@@ -269,7 +273,7 @@ def run_GUI():
269
273
  window_width = screen_width - 100
270
274
  window_height = screen_height - 100
271
275
  root.geometry(f"{window_width}x{window_height}+50+50")
272
-
276
+
273
277
  # Configure column weights to prevent plot squashing
274
278
  for i in range(7): # Configure columns 0-6
275
279
  root.columnconfigure(i, weight=1)
@@ -278,29 +282,31 @@ def run_GUI():
278
282
  root.rowconfigure(i, weight=1)
279
283
 
280
284
  # downloaded theme from https://sourceforge.net/projects/tcl-awthemes/
281
- theme_path_rel = os.path.join('TkinterTheme', 'awthemes-10.4.0')
282
- theme_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), theme_path_rel)
285
+ theme_path_rel = os.path.join("TkinterTheme", "awthemes-10.4.0")
286
+ theme_path = os.path.join(
287
+ os.path.dirname(os.path.abspath(__file__)), theme_path_rel
288
+ )
283
289
 
284
- root.tk.call('lappend', 'auto_path', theme_path)
285
- root.tk.call('package', 'require', 'awdark')
290
+ root.tk.call("lappend", "auto_path", theme_path)
291
+ root.tk.call("package", "require", "awdark")
286
292
  s = ttk.Style(root)
287
- s.theme_use('awdark')
288
-
293
+ s.theme_use("awdark")
294
+
289
295
  # Configure fonts for all TTK widgets to use DejaVu Sans
290
- s.configure('.', font=('DejaVu Sans', 12))
291
- s.configure('TLabel', font=('DejaVu Sans', 12))
292
- s.configure('TButton', font=('DejaVu Sans', 12))
293
- s.configure('TEntry', font=('DejaVu Sans', 10))
294
- s.configure('TCombobox', font=('DejaVu Sans', 10))
295
- s.configure('TCheckbutton', font=('DejaVu Sans', 12))
296
- s.configure('TRadiobutton', font=('DejaVu Sans', 12))
297
- s.configure('TLabelFrame.Label', font=('DejaVu Sans', 12, 'bold'))
298
-
299
- root.title('UMPy - Manual Curation')
300
- #root.geometry('800x800')
296
+ s.configure(".", font=("DejaVu Sans", 12))
297
+ s.configure("TLabel", font=("DejaVu Sans", 12))
298
+ s.configure("TButton", font=("DejaVu Sans", 12))
299
+ s.configure("TEntry", font=("DejaVu Sans", 10))
300
+ s.configure("TCombobox", font=("DejaVu Sans", 10))
301
+ s.configure("TCheckbutton", font=("DejaVu Sans", 12))
302
+ s.configure("TRadiobutton", font=("DejaVu Sans", 12))
303
+ s.configure("TLabelFrame.Label", font=("DejaVu Sans", 12, "bold"))
304
+
305
+ root.title("UMPy - Manual Curation")
306
+ # root.geometry('800x800')
301
307
 
302
308
  # Construct the file path to the icon
303
- icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'GUI_icon.png')
309
+ icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "GUI_icon.png")
304
310
 
305
311
  # Debugging print statements
306
312
  print(f"Icon path: {icon_path}")
@@ -314,98 +320,143 @@ def run_GUI():
314
320
  except Exception as e:
315
321
  print(f"Error loading icon: {e}")
316
322
 
317
-
318
323
  background = ttk.Frame(root)
319
324
  background.place(x=0, y=0, relwidth=1.0, relheight=1.0)
320
325
 
321
326
  frame_table = ttk.LabelFrame(root)
322
327
  score_table = ttk.LabelFrame(root)
323
- avg_waveform_plot = Canvas(root)
328
+ avg_waveform_plot = Canvas(root)
324
329
  trajectory_plot = Canvas(root)
325
330
  bayes_label = ttk.Label(root)
326
331
  original_id_label = ttk.Label(root)
327
332
  raw_waveform_plot = Canvas(root)
328
333
  hist_plot = Canvas(root)
329
334
 
330
- #Unit entry
335
+ # Unit entry
331
336
  ######################################################################################
332
- #Will have Unit A - color green and unit B- color Blue
333
- entry_frame = ttk.LabelFrame(root, text = 'Select Units')
334
- label_a = ttk.Label(entry_frame, text = 'Unit A')
335
- label_a.configure(foreground='green')
336
- label_b = ttk.Label(entry_frame, text = 'Unit B')
337
- label_b.configure(foreground='blue')
338
-
339
- #select the session
340
- sessions_list = np.arange(1,param['n_sessions']+1).tolist()
341
- session_entry_a = ttk.Combobox(entry_frame, value = sessions_list, width = 2)
342
- session_entry_b = ttk.Combobox(entry_frame, value = sessions_list, width = 2)
343
- session_entry_a.set(1) #Start wiht session 1,2 if more than 1 session given
337
+ # Will have Unit A - color green and unit B- color Blue
338
+ entry_frame = ttk.LabelFrame(root, text="Select Units")
339
+ label_a = ttk.Label(entry_frame, text="Unit A")
340
+ label_a.configure(foreground="green")
341
+ label_b = ttk.Label(entry_frame, text="Unit B")
342
+ label_b.configure(foreground="blue")
343
+
344
+ # select the session
345
+ sessions_list = np.arange(1, param["n_sessions"] + 1).tolist()
346
+ session_entry_a = ttk.Combobox(entry_frame, value=sessions_list, width=2)
347
+ session_entry_b = ttk.Combobox(entry_frame, value=sessions_list, width=2)
348
+ session_entry_a.set(1) # Start wiht session 1,2 if more than 1 session given
344
349
  if len(sessions_list) == 1:
345
350
  session_entry_b.set(1)
346
351
  else:
347
352
  session_entry_b.set(2)
348
- label_session_a = ttk.Label(entry_frame, text = 'Session No.')
349
- label_session_b = ttk.Label(entry_frame, text = 'Session No.')
350
-
353
+ label_session_a = ttk.Label(entry_frame, text="Session No.")
354
+ label_session_b = ttk.Label(entry_frame, text="Session No.")
351
355
 
352
- #select CV
353
- CV_options = [('Avg', 0), ('(1,2)', 1), ('(2,1)',2)]
356
+ # select CV
357
+ CV_options = [("Avg", 0), ("(1,2)", 1), ("(2,1)", 2)]
354
358
  CV_tkinter = IntVar()
355
359
  CV_tkinter.set(0)
356
- label_cv = ttk.Label(entry_frame, text = 'Select the cv option')
360
+ label_cv = ttk.Label(entry_frame, text="Select the cv option")
357
361
  for i, option in enumerate(CV_options):
358
- RadioCV = ttk.Radiobutton(entry_frame, text = option[0], value =option[1], variable = CV_tkinter, command = update_unit_cv).grid(row = i+1, column = 0)
359
-
360
- #selecting the unit
362
+ RadioCV = ttk.Radiobutton(
363
+ entry_frame,
364
+ text=option[0],
365
+ value=option[1],
366
+ variable=CV_tkinter,
367
+ command=update_unit_cv,
368
+ ).grid(row=i + 1, column=0)
369
+
370
+ # selecting the unit
361
371
  session_a = int(session_entry_a.get())
362
- session_b = int(session_entry_b.get())
372
+ session_b = int(session_entry_b.get())
363
373
  CV = get_cv_option()
364
- CV_option = CV_tkinter.get() - 1 #want 0 for cv (1,2) , want 1 for cv (2,1)
365
- if CV == 'Avg':
366
- #Use average CV values
367
- tmp_idx_a = np.argwhere((session_switch[session_a -1] <= matches_avg[:,0]) * (matches_avg[:,0] < session_switch[session_a]) == True ).squeeze()
368
- tmp_idx_b = np.argwhere((session_switch[session_b -1] <= matches_avg[:,1]) * (matches_avg[:,1] < session_switch[session_b]) == True).squeeze()
374
+ CV_option = CV_tkinter.get() - 1 # want 0 for cv (1,2) , want 1 for cv (2,1)
375
+ if CV == "Avg":
376
+ # Use average CV values
377
+ tmp_idx_a = np.argwhere(
378
+ (session_switch[session_a - 1] <= matches_avg[:, 0])
379
+ * (matches_avg[:, 0] < session_switch[session_a])
380
+ == True
381
+ ).squeeze()
382
+ tmp_idx_b = np.argwhere(
383
+ (session_switch[session_b - 1] <= matches_avg[:, 1])
384
+ * (matches_avg[:, 1] < session_switch[session_b])
385
+ == True
386
+ ).squeeze()
369
387
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
370
- option_a = matches_avg[tmp_idx_a[in_both],:].tolist()
371
-
372
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
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]]]
394
+
395
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
373
396
  entry_a.set(option_a[0][0])
374
397
 
375
- option_b = np.flip(np.argsort(output_avg[int(entry_a.get()),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
398
+ option_b = np.flip(
399
+ np.argsort(
400
+ output_avg[
401
+ int(entry_a.get()),
402
+ session_switch[session_b - 1] : session_switch[session_b],
403
+ ]
404
+ )
405
+ + session_switch[session_b - 1]
406
+ )
376
407
  option_b = option_b.tolist()
377
408
 
378
- else :
379
- tmp_idx_a = np.argwhere((session_switch[session_a -1] <= matches_GUI[CV_option][:,0]) * ( matches_GUI[CV_option][:,0] < session_switch[session_a]) == True ).squeeze()
380
- tmp_idx_b = np.argwhere((session_switch[session_b -1] <= matches_GUI[CV_option][:,1]) * ( matches_GUI[CV_option][:,1] < session_switch[session_b]) == True).squeeze()
409
+ else:
410
+ tmp_idx_a = np.argwhere(
411
+ (session_switch[session_a - 1] <= matches_GUI[CV_option][:, 0])
412
+ * (matches_GUI[CV_option][:, 0] < session_switch[session_a])
413
+ == True
414
+ ).squeeze()
415
+ tmp_idx_b = np.argwhere(
416
+ (session_switch[session_b - 1] <= matches_GUI[CV_option][:, 1])
417
+ * (matches_GUI[CV_option][:, 1] < session_switch[session_b])
418
+ == True
419
+ ).squeeze()
381
420
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
382
421
 
383
- option_a = matches_GUI[CV_option][tmp_idx_a[in_both],:].tolist()
422
+ option_a = matches_GUI[CV_option][tmp_idx_a[in_both], :].tolist()
384
423
  if CV_option == 0:
385
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]]]
386
430
 
387
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
431
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
388
432
  entry_a.set(option_a[0][0])
389
433
 
390
-
391
- option_b = np.flip(np.argsort(output_GUI[CV_option][int(entry_a.get()),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
434
+ option_b = np.flip(
435
+ np.argsort(
436
+ output_GUI[CV_option][
437
+ int(entry_a.get()),
438
+ session_switch[session_b - 1] : session_switch[session_b],
439
+ ]
440
+ )
441
+ + session_switch[session_b - 1]
442
+ )
392
443
  option_b = option_b.tolist()
393
444
 
394
445
  ##################
395
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
446
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
396
447
  entry_b.set(option_b[0])
397
- entry_a.bind('<<ComboboxSelected>>', update_units)
398
- entry_b.bind('<<ComboboxSelected>>', update)
448
+ entry_a.bind("<<ComboboxSelected>>", update_units)
449
+ entry_b.bind("<<ComboboxSelected>>", update)
399
450
 
400
- session_entry_a.bind('<<ComboboxSelected>>', update_unit_entryA)
401
- session_entry_b.bind('<<ComboboxSelected>>', update_unit_entryB)
451
+ session_entry_a.bind("<<ComboboxSelected>>", update_unit_entryA)
452
+ session_entry_b.bind("<<ComboboxSelected>>", update_unit_entryB)
402
453
 
403
- #adding a button which swaps unit A and B
404
- swap_button = ttk.Button(entry_frame, text = 'Swap Units', command = swap_units)
454
+ # adding a button which swaps unit A and B
455
+ swap_button = ttk.Button(entry_frame, text="Swap Units", command=swap_units)
405
456
 
406
- #Calculate the score histograms
407
- #for each CV pair
408
- #make global variable so the functions can access the histograms.
457
+ # Calculate the score histograms
458
+ # for each CV pair
459
+ # make global variable so the functions can access the histograms.
409
460
  global hist_names_avg
410
461
  global hist_names_12
411
462
  global hist_names_21
@@ -416,31 +467,35 @@ def run_GUI():
416
467
  global hist_matches_12
417
468
  global hist_matches_21
418
469
 
419
- hist_names_avg, hist_avg, hist_matches_avg = get_score_histograms(scores_to_include_avg, (output_avg > match_threshold))
420
- hist_names_12, hist_12, hist_matches_12 = get_score_histograms(scores_to_include_GUI[0], (output_GUI[0] > match_threshold))
421
- hist_names_21, hist_21, hist_matches_21 = get_score_histograms(scores_to_include_GUI[1], (output_GUI[1] > match_threshold))
422
-
423
-
424
- #place the widgets on the EntryFrame
425
- label_cv.grid(row = 0, column = 0)
426
- label_a.grid(row = 0, column = 1)
427
- label_b.grid(row = 0, column = 3)
428
- label_session_a.grid(row = 1, column = 1)
429
- session_entry_a.grid(row = 1, column = 2, padx = 15)
430
- label_session_b.grid(row = 1, column = 3)
431
- session_entry_b.grid(row = 1, column = 4, padx = 15)
432
- entry_a.grid(row = 2, column = 1, columnspan = 2, stick = 'WE', padx = 5)
433
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
434
- swap_button.grid(row = 3, column = 2, columnspan = 2, sticky = 'WE')
470
+ hist_names_avg, hist_avg, hist_matches_avg = get_score_histograms(
471
+ scores_to_include_avg, (output_avg > match_threshold)
472
+ )
473
+ hist_names_12, hist_12, hist_matches_12 = get_score_histograms(
474
+ scores_to_include_GUI[0], (output_GUI[0] > match_threshold)
475
+ )
476
+ hist_names_21, hist_21, hist_matches_21 = get_score_histograms(
477
+ scores_to_include_GUI[1], (output_GUI[1] > match_threshold)
478
+ )
479
+
480
+ # place the widgets on the EntryFrame
481
+ label_cv.grid(row=0, column=0)
482
+ label_a.grid(row=0, column=1)
483
+ label_b.grid(row=0, column=3)
484
+ label_session_a.grid(row=1, column=1)
485
+ session_entry_a.grid(row=1, column=2, padx=15)
486
+ label_session_b.grid(row=1, column=3)
487
+ session_entry_b.grid(row=1, column=4, padx=15)
488
+ entry_a.grid(row=2, column=1, columnspan=2, stick="WE", padx=5)
489
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
490
+ swap_button.grid(row=3, column=2, columnspan=2, sticky="WE")
435
491
  ######################################################################################
436
492
 
437
-
438
- #MatchButtons
493
+ # MatchButtons
439
494
  ######################################################################################
440
- match_button = ttk.Button(root, text = 'Set as Match', command = set_match)
441
- non_match_button = ttk.Button(root, text='Set as Non Match', command = set_not_match)
495
+ match_button = ttk.Button(root, text="Set as Match", command=set_match)
496
+ non_match_button = ttk.Button(root, text="Set as Non Match", command=set_not_match)
442
497
 
443
- #Toggle Plots
498
+ # Toggle Plots
444
499
  ######################################################################################
445
500
  toggle_raw_val = BooleanVar()
446
501
  toggle_UM_score_val = BooleanVar()
@@ -448,40 +503,44 @@ def run_GUI():
448
503
  toggle_raw_val.set(False)
449
504
  toggle_UM_score_val.set(False)
450
505
  toggle_acg_val.set(True) # Default to hiding ACGs
451
- toggle_raw_plot = ttk.Checkbutton(root, text ='Hide Raw Data', variable = toggle_raw_val)
452
- toggle_UM_score_plot = ttk.Checkbutton(root, text ='Hide UM Score Histograms', variable = toggle_UM_score_val)
453
- toggle_acg_plot = ttk.Checkbutton(root, text ='Hide Autocorrelograms (ACGs)', variable = toggle_acg_val)
454
-
455
-
506
+ toggle_raw_plot = ttk.Checkbutton(
507
+ root, text="Hide Raw Data", variable=toggle_raw_val
508
+ )
509
+ toggle_UM_score_plot = ttk.Checkbutton(
510
+ root, text="Hide UM Score Histograms", variable=toggle_UM_score_val
511
+ )
512
+ toggle_acg_plot = ttk.Checkbutton(
513
+ root, text="Hide Autocorrelograms (ACGs)", variable=toggle_acg_val
514
+ )
456
515
 
457
516
  # Set up Key-Board shortcuts
458
- root.bind_all('u', update)
459
- root.bind_all('<Return>', update)
460
- root.bind_all('<Right>', next_pair)
461
- root.bind_all('<Left>', previous_pair)
462
- root.bind_all('<Up>', up_options_b_list)
463
- root.bind_all('<Down>', down_options_b_list)
464
- root.bind_all('q', set_match)
465
- root.bind_all('m', set_match)
466
- root.bind_all('e', set_not_match)
467
- root.bind_all('n', set_not_match)
468
-
469
- #Grid the units
470
- entry_frame.grid(row = 2, column = 0, pady=5, padx = 5)
471
- match_button.grid(row = 1, column = 0, sticky = 'W', padx = 10, pady = 5)
472
- non_match_button.grid(row = 1, column = 1, sticky = 'W', padx = 10, pady = 5)
473
- toggle_UM_score_plot.grid(row = 1, column = 2, sticky = 'W', padx = 10, pady = 5)
474
- toggle_raw_plot.grid(row = 1, column = 3, sticky = 'W', padx = 10, pady = 5)
475
- toggle_acg_plot.grid(row = 1, column = 4, sticky = 'W', padx = 10, pady = 5)
476
-
517
+ root.bind_all("u", update)
518
+ root.bind_all("<Return>", update)
519
+ root.bind_all("<Right>", next_pair)
520
+ root.bind_all("<Left>", previous_pair)
521
+ root.bind_all("<Up>", up_options_b_list)
522
+ root.bind_all("<Down>", down_options_b_list)
523
+ root.bind_all("q", set_match)
524
+ root.bind_all("m", set_match)
525
+ root.bind_all("e", set_not_match)
526
+ root.bind_all("n", set_not_match)
527
+
528
+ # Grid the units
529
+ entry_frame.grid(row=2, column=0, pady=5, padx=5)
530
+ match_button.grid(row=1, column=0, sticky="W", padx=10, pady=5)
531
+ non_match_button.grid(row=1, column=1, sticky="W", padx=10, pady=5)
532
+ toggle_UM_score_plot.grid(row=1, column=2, sticky="W", padx=10, pady=5)
533
+ toggle_raw_plot.grid(row=1, column=3, sticky="W", padx=10, pady=5)
534
+ toggle_acg_plot.grid(row=1, column=4, sticky="W", padx=10, pady=5)
535
+
477
536
  # Create visual legend plots outside plots
478
537
  global unit_legend_plot
479
538
  global hist_legend_plot
480
539
  create_unit_legend()
481
540
  create_hist_legend()
482
-
483
- unit_legend_plot.grid(row = 0, column = 1, columnspan = 2, sticky = 'W', padx = 10, pady = 5)
484
- hist_legend_plot.grid(row = 0, column = 3, columnspan = 4, sticky = 'W', padx = 10, pady = 5)
541
+
542
+ unit_legend_plot.grid(row=0, column=1, columnspan=2, sticky="W", padx=10, pady=5)
543
+ hist_legend_plot.grid(row=0, column=3, columnspan=4, sticky="W", padx=10, pady=5)
485
544
 
486
545
  # Configure grid weights to auto-adjust subpanels
487
546
  root.grid_rowconfigure(0, weight=1)
@@ -494,18 +553,35 @@ def run_GUI():
494
553
 
495
554
  root.mainloop()
496
555
 
497
- #set default plot color back to black
498
- color = 'black'
499
- rcParams['text.color'] = color
500
- rcParams['axes.labelcolor'] = color
501
- rcParams['xtick.color'] = color
502
- rcParams['ytick.color'] = color
556
+ # set default plot color back to black
557
+ color = "black"
558
+ rcParams["text.color"] = color
559
+ rcParams["axes.labelcolor"] = color
560
+ rcParams["xtick.color"] = color
561
+ rcParams["ytick.color"] = color
503
562
 
504
563
  return is_match, not_match, matches_GUI
505
564
 
506
- def process_info_for_GUI(output, match_threshold_in, scores_to_include, total_score, amplitude_in, spatial_decay_in,
507
- avg_centroid_in, avg_waveform_in, avg_waveform_per_tp_in, wave_idx_in, max_site_in, max_site_mean_in,
508
- waveform_in, within_session_in, channel_pos_in, clus_info_in, param_in):
565
+
566
+ def process_info_for_GUI(
567
+ output,
568
+ match_threshold_in,
569
+ scores_to_include,
570
+ total_score,
571
+ amplitude_in,
572
+ spatial_decay_in,
573
+ avg_centroid_in,
574
+ avg_waveform_in,
575
+ avg_waveform_per_tp_in,
576
+ wave_idx_in,
577
+ max_site_in,
578
+ max_site_mean_in,
579
+ waveform_in,
580
+ within_session_in,
581
+ channel_pos_in,
582
+ clus_info_in,
583
+ param_in,
584
+ ):
509
585
  """
510
586
  This function:
511
587
  1 - passes data to the GUI
@@ -548,7 +624,7 @@ def process_info_for_GUI(output, match_threshold_in, scores_to_include, total_sc
548
624
  max_site_mean = max_site_mean_in
549
625
  waveform = waveform_in
550
626
  clus_info = clus_info_in
551
- session_switch = clus_info['session_switch']
627
+ session_switch = clus_info["session_switch"]
552
628
  param = param_in
553
629
  match_threshold = match_threshold_in
554
630
  within_session = within_session_in
@@ -557,19 +633,23 @@ def process_info_for_GUI(output, match_threshold_in, scores_to_include, total_sc
557
633
  output_threshold = np.zeros_like(output)
558
634
  output_threshold[output > match_threshold] = 1
559
635
 
560
- matches = np.argwhere(output_threshold == 1) # need all matches including same session for GUI
561
-
636
+ matches = np.argwhere(
637
+ output_threshold == 1
638
+ ) # need all matches including same session for GUI
562
639
 
563
- #for the code it is helpful for matches to contain both (session 1, session 2) and (session 2, session 1)
640
+ # for the code it is helpful for matches to contain both (session 1, session 2) and (session 2, session 1)
564
641
  # so when changing Unit A/B session it can find matches for all permutations
565
- matches_12_part_1 = np.argwhere(np.tril(output) > match_threshold)
642
+ matches_12_part_1 = np.argwhere(np.tril(output) > match_threshold)
566
643
  matches_12_part_2 = np.argwhere(np.tril(output).T > match_threshold)
567
- matches_12 = np.unique(np.concatenate((matches_12_part_1,matches_12_part_2)), axis = 0)
644
+ matches_12 = np.unique(
645
+ np.concatenate((matches_12_part_1, matches_12_part_2)), axis=0
646
+ )
568
647
 
569
-
570
- matches_21_part_1 = np.argwhere(np.triu(output) > match_threshold)
648
+ matches_21_part_1 = np.argwhere(np.triu(output) > match_threshold)
571
649
  matches_21_part_2 = np.argwhere(np.triu(output).T > match_threshold)
572
- matches_21 = np.unique(np.concatenate((matches_21_part_1,matches_21_part_2)), axis = 0)
650
+ matches_21 = np.unique(
651
+ np.concatenate((matches_21_part_1, matches_21_part_2)), axis=0
652
+ )
573
653
 
574
654
  matches_GUI = [matches_12, matches_21]
575
655
 
@@ -597,15 +677,14 @@ def process_info_for_GUI(output, match_threshold_in, scores_to_include, total_sc
597
677
  tmp4 = np.triu(value).T
598
678
  np.fill_diagonal(tmp4, 0)
599
679
 
600
- scores_to_include_12[key] = tmp1 + tmp2
601
- scores_to_include_21[key] = tmp3 + tmp4
680
+ scores_to_include_12[key] = tmp1 + tmp2
681
+ scores_to_include_21[key] = tmp3 + tmp4
602
682
 
603
683
  scores_to_include_GUI = [scores_to_include_12, scores_to_include_21]
604
684
 
605
-
606
- #getting avg CV data
685
+ # getting avg CV data
607
686
  # for the Scores where can do (X + X.T)/2 and take upper triangular part
608
- total_score_avg = np.triu( (total_score + total_score.T) / 2)
687
+ total_score_avg = np.triu((total_score + total_score.T) / 2)
609
688
 
610
689
  scores_to_include_avg = {}
611
690
  for key, value in scores_to_include.items():
@@ -613,74 +692,79 @@ def process_info_for_GUI(output, match_threshold_in, scores_to_include, total_sc
613
692
 
614
693
  output_avg = (output_GUI[0] + output_GUI[1]) / 2
615
694
 
616
- matches_avg_part_1 = np.argwhere( output_avg > match_threshold )
617
- matches_avg_part_2 = np.argwhere( output_avg.T > match_threshold )
618
- matches_avg = np.unique(np.concatenate((matches_avg_part_1,matches_avg_part_2)), axis = 0)
695
+ matches_avg_part_1 = np.argwhere(output_avg > match_threshold)
696
+ matches_avg_part_2 = np.argwhere(output_avg.T > match_threshold)
697
+ matches_avg = np.unique(
698
+ np.concatenate((matches_avg_part_1, matches_avg_part_2)), axis=0
699
+ )
619
700
 
620
701
  # or an simply average over both CV
621
- amplitude_avg = np.mean(amplitude, axis = -1)
622
- spatial_decay_avg = np.mean(spatial_decay, axis = -1)
623
- avg_centroid_avg = np.mean(avg_centroid, axis = -1)
624
- avg_waveform_avg = np.mean(avg_waveform, axis = -1)
625
- avg_waveform_per_tp_avg = np.mean(avg_waveform_per_tp, axis = -1)
702
+ amplitude_avg = np.mean(amplitude, axis=-1)
703
+ spatial_decay_avg = np.mean(spatial_decay, axis=-1)
704
+ avg_centroid_avg = np.mean(avg_centroid, axis=-1)
705
+ avg_waveform_avg = np.mean(avg_waveform, axis=-1)
706
+ avg_waveform_per_tp_avg = np.mean(avg_waveform_per_tp, axis=-1)
707
+
626
708
 
627
709
  def create_unit_legend():
628
710
  """Create visual legend for unit colors"""
629
711
  global unit_legend_plot
630
-
712
+
631
713
  fig = Figure(figsize=(6, 0.5), dpi=100)
632
- fig.patch.set_facecolor('#33393b')
633
-
714
+ fig.patch.set_facecolor("#33393b")
715
+
634
716
  ax = fig.add_subplot(111)
635
- ax.set_facecolor('#33393b')
636
-
717
+ ax.set_facecolor("#33393b")
718
+
637
719
  # Draw legend lines and text
638
- ax.plot([0, 0.15], [0.5, 0.5], 'g-', lw=3)
639
- ax.text(0.18, 0.5, 'Unit A', color='white', fontsize=12, va='center')
640
-
641
- ax.plot([0.6, 0.75], [0.5, 0.5], 'b-', lw=3)
642
- ax.text(0.78, 0.5, 'Unit B', color='white', fontsize=12, va='center')
643
-
720
+ ax.plot([0, 0.15], [0.5, 0.5], "g-", lw=3)
721
+ ax.text(0.18, 0.5, "Unit A", color="white", fontsize=12, va="center")
722
+
723
+ ax.plot([0.6, 0.75], [0.5, 0.5], "b-", lw=3)
724
+ ax.text(0.78, 0.5, "Unit B", color="white", fontsize=12, va="center")
725
+
644
726
  ax.set_xlim(0, 1.2)
645
727
  ax.set_ylim(0, 1)
646
- ax.axis('off')
647
-
728
+ ax.axis("off")
729
+
648
730
  unit_legend_plot = FigureCanvasTkAgg(fig, master=root)
649
731
  unit_legend_plot.draw()
650
732
  unit_legend_plot = unit_legend_plot.get_tk_widget()
651
733
 
734
+
652
735
  def create_hist_legend():
653
736
  """Create visual legend for histogram colors"""
654
737
  global hist_legend_plot
655
-
738
+
656
739
  fig = Figure(figsize=(8, 0.5), dpi=100)
657
- fig.patch.set_facecolor('#33393b')
658
-
740
+ fig.patch.set_facecolor("#33393b")
741
+
659
742
  ax = fig.add_subplot(111)
660
- ax.set_facecolor('#33393b')
661
-
743
+ ax.set_facecolor("#33393b")
744
+
662
745
  # Draw legend elements
663
- ax.plot([0, 0.1], [0.5, 0.5], 'orange', lw=3)
664
- ax.text(0.12, 0.5, 'All scores', color='white', fontsize=10, va='center')
665
-
666
- ax.plot([0.35, 0.45], [0.5, 0.5], 'magenta', lw=3)
667
- ax.text(0.47, 0.5, 'Expected matches', color='white', fontsize=10, va='center')
668
-
669
- ax.plot([0.75, 0.85], [0.5, 0.5], 'white', lw=2, linestyle='--')
670
- ax.text(0.87, 0.5, 'Current pair', color='white', fontsize=10, va='center')
671
-
746
+ ax.plot([0, 0.1], [0.5, 0.5], "orange", lw=3)
747
+ ax.text(0.12, 0.5, "All scores", color="white", fontsize=10, va="center")
748
+
749
+ ax.plot([0.35, 0.45], [0.5, 0.5], "magenta", lw=3)
750
+ ax.text(0.47, 0.5, "Expected matches", color="white", fontsize=10, va="center")
751
+
752
+ ax.plot([0.75, 0.85], [0.5, 0.5], "white", lw=2, linestyle="--")
753
+ ax.text(0.87, 0.5, "Current pair", color="white", fontsize=10, va="center")
754
+
672
755
  ax.set_xlim(0, 1.2)
673
756
  ax.set_ylim(0, 1)
674
- ax.axis('off')
675
-
757
+ ax.axis("off")
758
+
676
759
  hist_legend_plot = FigureCanvasTkAgg(fig, master=root)
677
760
  hist_legend_plot.draw()
678
761
  hist_legend_plot = hist_legend_plot.get_tk_widget()
679
762
 
763
+
680
764
  def compute_acg(spike_times, bin_size=0.001, max_lag=0.05):
681
765
  """
682
766
  Compute autocorrelogram for a unit
683
-
767
+
684
768
  Parameters
685
769
  ----------
686
770
  spike_times : array
@@ -689,7 +773,7 @@ def compute_acg(spike_times, bin_size=0.001, max_lag=0.05):
689
773
  Bin size in seconds (default 1ms)
690
774
  max_lag : float
691
775
  Maximum lag in seconds (default 50ms)
692
-
776
+
693
777
  Returns
694
778
  -------
695
779
  autocorr : array
@@ -699,59 +783,65 @@ def compute_acg(spike_times, bin_size=0.001, max_lag=0.05):
699
783
  """
700
784
  if len(spike_times) < 2:
701
785
  return np.array([]), np.array([])
702
-
786
+
703
787
  # Create bins centered around 0
704
788
  bins = np.arange(-max_lag, max_lag + bin_size, bin_size)
705
- bin_centers = bins[:-1] + bin_size/2
706
-
789
+ bin_centers = bins[:-1] + bin_size / 2
790
+
707
791
  # Calculate autocorrelogram
708
792
  autocorr = np.zeros(len(bin_centers))
709
-
793
+
710
794
  # For efficiency, subsample spikes if there are too many
711
795
  if len(spike_times) > 10000:
712
796
  indices = np.random.choice(len(spike_times), 10000, replace=False)
713
797
  spike_subset = spike_times[indices]
714
798
  else:
715
799
  spike_subset = spike_times
716
-
717
- # Calculate cross-correlation with itself
800
+
801
+ # Calculate cross-correlation with itself
718
802
  for i, spike_time in enumerate(spike_subset[::10]): # Subsample further for speed
719
803
  # Find spikes within max_lag of this spike
720
804
  time_diffs = spike_times - spike_time
721
805
  valid_diffs = time_diffs[(np.abs(time_diffs) <= max_lag) & (time_diffs != 0)]
722
-
806
+
723
807
  if len(valid_diffs) > 0:
724
808
  hist, _ = np.histogram(valid_diffs, bins=bins)
725
809
  autocorr += hist
726
-
810
+
727
811
  # Convert to firing rate (spikes/sec)
728
812
  if len(spike_subset) > 0:
729
- recording_duration = np.max(spike_times) - np.min(spike_times) if len(spike_times) > 0 else 1
730
- autocorr = autocorr / (len(spike_subset) * bin_size) if recording_duration > 0 else autocorr
731
-
813
+ recording_duration = (
814
+ np.max(spike_times) - np.min(spike_times) if len(spike_times) > 0 else 1
815
+ )
816
+ autocorr = (
817
+ autocorr / (len(spike_subset) * bin_size)
818
+ if recording_duration > 0
819
+ else autocorr
820
+ )
821
+
732
822
  return autocorr, bin_centers
733
823
 
824
+
734
825
  def plot_acgs(unit_a, unit_b):
735
826
  """Plot autocorrelograms for both units overlaid in single plot"""
736
827
  global acg_plot
737
828
  global clus_info
738
829
  global acg_cache
739
-
830
+
740
831
  # Destroy existing plot
741
- if 'acg_plot' in globals() and acg_plot.winfo_exists():
832
+ if "acg_plot" in globals() and acg_plot.winfo_exists():
742
833
  acg_plot.destroy()
743
-
744
-
834
+
745
835
  # Create figure for single overlaid ACG plot
746
836
  fig = Figure(figsize=(3, 3), dpi=100)
747
- fig.patch.set_facecolor('#33393b')
748
-
837
+ fig.patch.set_facecolor("#33393b")
838
+
749
839
  # Create single subplot for overlaid ACGs
750
840
  ax = fig.add_subplot(1, 1, 1)
751
- ax.set_facecolor('#2d2d2d')
752
-
841
+ ax.set_facecolor("#2d2d2d")
842
+
753
843
  max_rate = 0 # Track max rate for y-axis scaling
754
-
844
+
755
845
  # Try to get ACGs from cache first, otherwise compute them
756
846
  try:
757
847
  # Get ACG for Unit A
@@ -765,17 +855,25 @@ def plot_acgs(unit_a, unit_b):
765
855
  autocorr_a, bin_centers_a = compute_acg(spike_times_a)
766
856
  else:
767
857
  autocorr_a, bin_centers_a = np.array([]), np.array([])
768
-
858
+
769
859
  # Plot ACG for Unit A
770
860
  if len(autocorr_a) > 0:
771
861
  positive_mask = bin_centers_a >= 0
772
862
  positive_centers = bin_centers_a[positive_mask] * 1000 # Convert to ms
773
863
  positive_autocorr = autocorr_a[positive_mask]
774
-
775
- ax.plot(positive_centers, positive_autocorr, color='green',
776
- linewidth=2, alpha=0.8, label=f'Unit A ({unit_a})')
777
- max_rate = max(max_rate, np.max(positive_autocorr) if len(positive_autocorr) > 0 else 0)
778
-
864
+
865
+ ax.plot(
866
+ positive_centers,
867
+ positive_autocorr,
868
+ color="green",
869
+ linewidth=2,
870
+ alpha=0.8,
871
+ label=f"Unit A ({unit_a})",
872
+ )
873
+ max_rate = max(
874
+ max_rate, np.max(positive_autocorr) if len(positive_autocorr) > 0 else 0
875
+ )
876
+
779
877
  # Get ACG for Unit B
780
878
  if acg_cache is not None and unit_b in acg_cache:
781
879
  # Use cached ACG
@@ -787,64 +885,80 @@ def plot_acgs(unit_a, unit_b):
787
885
  autocorr_b, bin_centers_b = compute_acg(spike_times_b)
788
886
  else:
789
887
  autocorr_b, bin_centers_b = np.array([]), np.array([])
790
-
888
+
791
889
  # Plot ACG for Unit B
792
890
  if len(autocorr_b) > 0:
793
891
  positive_mask = bin_centers_b >= 0
794
892
  positive_centers = bin_centers_b[positive_mask] * 1000 # Convert to ms
795
893
  positive_autocorr = autocorr_b[positive_mask]
796
-
797
- ax.plot(positive_centers, positive_autocorr, color='blue',
798
- linewidth=2, alpha=0.8, label=f'Unit B ({unit_b})')
799
- max_rate = max(max_rate, np.max(positive_autocorr) if len(positive_autocorr) > 0 else 0)
800
-
894
+
895
+ ax.plot(
896
+ positive_centers,
897
+ positive_autocorr,
898
+ color="blue",
899
+ linewidth=2,
900
+ alpha=0.8,
901
+ label=f"Unit B ({unit_b})",
902
+ )
903
+ max_rate = max(
904
+ max_rate, np.max(positive_autocorr) if len(positive_autocorr) > 0 else 0
905
+ )
906
+
801
907
  # Set labels and title
802
- ax.set_xlabel('Time lag (ms)', fontsize=10, color='white')
803
- ax.set_ylabel('Rate (Hz)', fontsize=10, color='white')
804
- ax.set_title('Autocorrelograms', fontsize=12, color='white')
908
+ ax.set_xlabel("Time lag (ms)", fontsize=10, color="white")
909
+ ax.set_ylabel("Rate (Hz)", fontsize=10, color="white")
910
+ ax.set_title("Autocorrelograms", fontsize=12, color="white")
805
911
  ax.set_xlim(0, 50) # 50ms
806
912
  if max_rate > 0:
807
913
  ax.set_ylim(0, max_rate * 1.1)
808
-
914
+
809
915
  # Add legend
810
- legend = ax.legend(fontsize=8, loc='upper right')
811
- legend.get_frame().set_facecolor('#33393b')
916
+ legend = ax.legend(fontsize=8, loc="upper right")
917
+ legend.get_frame().set_facecolor("#33393b")
812
918
  legend.get_frame().set_alpha(0.8)
813
919
  for text in legend.get_texts():
814
- text.set_color('white')
815
-
920
+ text.set_color("white")
921
+
816
922
  # Style the plot
817
- ax.tick_params(colors='white', labelsize=8)
818
- ax.spines['bottom'].set_color('white')
819
- ax.spines['left'].set_color('white')
820
- ax.spines['top'].set_visible(False)
821
- ax.spines['right'].set_visible(False)
822
-
823
- except Exception as e:
923
+ ax.tick_params(colors="white", labelsize=8)
924
+ ax.spines["bottom"].set_color("white")
925
+ ax.spines["left"].set_color("white")
926
+ ax.spines["top"].set_visible(False)
927
+ ax.spines["right"].set_visible(False)
928
+
929
+ except Exception:
824
930
  # If spike times not available, show placeholder
825
931
  ax = fig.add_subplot(1, 1, 1)
826
- ax.set_facecolor('#2d2d2d')
827
- ax.text(0.5, 0.5, 'ACG data\nnot available', ha='center', va='center',
828
- color='white', fontsize=12)
932
+ ax.set_facecolor("#2d2d2d")
933
+ ax.text(
934
+ 0.5,
935
+ 0.5,
936
+ "ACG data\nnot available",
937
+ ha="center",
938
+ va="center",
939
+ color="white",
940
+ fontsize=12,
941
+ )
829
942
  ax.set_xlim(0, 1)
830
943
  ax.set_ylim(0, 1)
831
- ax.axis('off')
832
-
944
+ ax.axis("off")
945
+
833
946
  # Create canvas and position to the right of waveform plot
834
947
  acg_canvas = FigureCanvasTkAgg(fig, master=root)
835
948
  acg_canvas.draw()
836
949
  acg_plot = acg_canvas.get_tk_widget()
837
- acg_plot.grid(row=3, column=3, rowspan=2, padx=5, pady=5, sticky='nsew')
950
+ acg_plot.grid(row=3, column=3, rowspan=2, padx=5, pady=5, sticky="nsew")
951
+
838
952
 
839
953
  def get_spike_times_for_unit(unit_id):
840
954
  """
841
955
  Get spike times for a specific unit from Kilosort data
842
-
956
+
843
957
  Parameters
844
958
  ----------
845
959
  unit_id : int
846
960
  UnitMatch unit ID
847
-
961
+
848
962
  Returns
849
963
  -------
850
964
  spike_times : array
@@ -853,36 +967,36 @@ def get_spike_times_for_unit(unit_id):
853
967
  try:
854
968
  # Get session information for this unit
855
969
  global clus_info, param
856
- session_id = clus_info['session_id'][unit_id]
857
- original_id = clus_info['original_ids'][unit_id]
858
-
970
+ session_id = clus_info["session_id"][unit_id]
971
+ original_id = clus_info["original_ids"][unit_id]
972
+
859
973
  # Get the Kilosort directory for this session
860
- if 'KS_dirs' in param:
861
- ks_dir = param['KS_dirs'][session_id]
974
+ if "KS_dirs" in param:
975
+ ks_dir = param["KS_dirs"][session_id]
862
976
  else:
863
977
  # Try to infer from existing paths
864
978
  return np.array([])
865
-
979
+
866
980
  # Load Kilosort spike times and cluster assignments
867
- spike_times_path = os.path.join(ks_dir, 'spike_times.npy')
868
- spike_clusters_path = os.path.join(ks_dir, 'spike_clusters.npy')
869
-
981
+ spike_times_path = os.path.join(ks_dir, "spike_times.npy")
982
+ spike_clusters_path = os.path.join(ks_dir, "spike_clusters.npy")
983
+
870
984
  if os.path.exists(spike_times_path) and os.path.exists(spike_clusters_path):
871
985
  # Load spike times (in samples) and cluster assignments
872
986
  spike_times_samples = np.load(spike_times_path).flatten()
873
987
  spike_clusters = np.load(spike_clusters_path).flatten()
874
-
988
+
875
989
  # Get sampling rate - try to load from params.py or use default
876
990
  try:
877
- params_path = os.path.join(ks_dir, 'params.py')
991
+ params_path = os.path.join(ks_dir, "params.py")
878
992
  if os.path.exists(params_path):
879
993
  # Parse params.py for sample_rate
880
- with open(params_path, 'r') as f:
994
+ with open(params_path, "r") as f:
881
995
  params_content = f.read()
882
996
  # Extract sample_rate
883
- for line in params_content.split('\n'):
884
- if 'sample_rate' in line and '=' in line:
885
- sample_rate = float(line.split('=')[1].strip())
997
+ for line in params_content.split("\n"):
998
+ if "sample_rate" in line and "=" in line:
999
+ sample_rate = float(line.split("=")[1].strip())
886
1000
  break
887
1001
  else:
888
1002
  sample_rate = 30000.0 # Default Neuropixels sample rate
@@ -890,32 +1004,33 @@ def get_spike_times_for_unit(unit_id):
890
1004
  sample_rate = 30000.0 # Default
891
1005
  except:
892
1006
  sample_rate = 30000.0 # Default
893
-
1007
+
894
1008
  # Filter spikes for this unit
895
1009
  unit_mask = spike_clusters == int(original_id)
896
1010
  unit_spike_times = spike_times_samples[unit_mask]
897
-
1011
+
898
1012
  # Convert to seconds
899
1013
  unit_spike_times_sec = unit_spike_times / sample_rate
900
-
1014
+
901
1015
  return unit_spike_times_sec
902
1016
  else:
903
1017
  print(f"Could not find spike_times.npy or spike_clusters.npy in {ks_dir}")
904
1018
  return np.array([])
905
-
1019
+
906
1020
  except Exception as e:
907
1021
  print(f"Error loading spike times for unit {unit_id}: {e}")
908
1022
  return np.array([])
909
1023
 
1024
+
910
1025
  def update(event):
911
1026
  """
912
1027
  Updates the GUI.
913
1028
  """
914
-
1029
+
915
1030
  unit_a = int(entry_a.get())
916
1031
  unit_b = int(entry_b.get())
917
1032
 
918
- CV = get_cv_option() # CV = 'Avg', if AVG is selcted else it equal [0,1] or [1,0]
1033
+ CV = get_cv_option() # CV = 'Avg', if AVG is selcted else it equal [0,1] or [1,0]
919
1034
  CV_option = CV_tkinter.get() - 1
920
1035
 
921
1036
  table = get_table_data(unit_a, unit_b, CV)
@@ -937,27 +1052,48 @@ def update(event):
937
1052
  add_original_ID(unit_a, unit_b)
938
1053
 
939
1054
  if toggle_UM_score_val.get() is False:
940
- #plot histograms based of off the CV
1055
+ # plot histograms based of off the CV
941
1056
  if CV_option == -1:
942
- plot_histograms(hist_names_avg, hist_avg, hist_matches_avg, scores_to_include_avg, unit_a, unit_b)
1057
+ plot_histograms(
1058
+ hist_names_avg,
1059
+ hist_avg,
1060
+ hist_matches_avg,
1061
+ scores_to_include_avg,
1062
+ unit_a,
1063
+ unit_b,
1064
+ )
943
1065
  if CV_option == 0:
944
- plot_histograms(hist_names_12, hist_12, hist_matches_12, scores_to_include_GUI[CV_option], unit_a, unit_b)
1066
+ plot_histograms(
1067
+ hist_names_12,
1068
+ hist_12,
1069
+ hist_matches_12,
1070
+ scores_to_include_GUI[CV_option],
1071
+ unit_a,
1072
+ unit_b,
1073
+ )
945
1074
  if CV_option == 1:
946
- plot_histograms(hist_names_21, hist_21, hist_matches_21, scores_to_include_GUI[CV_option], unit_a, unit_b)
1075
+ plot_histograms(
1076
+ hist_names_21,
1077
+ hist_21,
1078
+ hist_matches_21,
1079
+ scores_to_include_GUI[CV_option],
1080
+ unit_a,
1081
+ unit_b,
1082
+ )
947
1083
  else:
948
1084
  if hist_plot.winfo_exists() == 1:
949
1085
  hist_plot.destroy()
950
-
1086
+
951
1087
  # Plot ACGs for both units if not hidden
952
1088
  if toggle_acg_val.get() is False:
953
1089
  plot_acgs(unit_a, unit_b)
954
1090
  else:
955
- if 'acg_plot' in globals() and acg_plot.winfo_exists() == 1:
1091
+ if "acg_plot" in globals() and acg_plot.winfo_exists() == 1:
956
1092
  acg_plot.destroy()
957
-
1093
+
958
1094
 
959
1095
  def up_options_b_list(event):
960
- """
1096
+ """
961
1097
  moves up the option B list, chose the unit with th next highest probabilty of being a match with unit A.
962
1098
  """
963
1099
  global entry_frame
@@ -971,26 +1107,26 @@ def up_options_b_list(event):
971
1107
  if current_idx == 0:
972
1108
  return
973
1109
  else:
974
- current_idx -=1
1110
+ current_idx -= 1
975
1111
  if entry_b.winfo_exists() == 1:
976
- entry_b.destroy()
1112
+ entry_b.destroy()
977
1113
 
978
1114
  new_entry_b = tmp_list[current_idx]
979
1115
 
980
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
981
- entry_b.set(new_entry_b )
982
- entry_b.bind('<<ComboboxSelected>>', update)
1116
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
1117
+ entry_b.set(new_entry_b)
1118
+ entry_b.bind("<<ComboboxSelected>>", update)
983
1119
 
984
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
1120
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
985
1121
 
986
1122
  update(event)
987
1123
 
988
1124
 
989
1125
  def down_options_b_list(event):
990
- """
1126
+ """
991
1127
  moves down the option B list, chose the unit with th next highest probabilty of being a match with unit A.
992
1128
  """
993
- global entry_frame
1129
+ global entry_frame
994
1130
  global option_b
995
1131
  global entry_b
996
1132
 
@@ -998,40 +1134,42 @@ def down_options_b_list(event):
998
1134
 
999
1135
  tmp_list = np.asarray(option_b)
1000
1136
  current_idx = int(np.argwhere(tmp_list == tmp_entry_b))
1001
- if current_idx == (len(tmp_list) -1):
1137
+ if current_idx == (len(tmp_list) - 1):
1002
1138
  return
1003
1139
  else:
1004
- current_idx +=1
1140
+ current_idx += 1
1005
1141
  if entry_b.winfo_exists() == 1:
1006
1142
  entry_b.destroy()
1007
1143
 
1008
1144
  new_entry_b = tmp_list[current_idx]
1009
1145
 
1010
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
1146
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
1011
1147
  entry_b.set(new_entry_b)
1012
- entry_b.bind('<<ComboboxSelected>>', update)
1148
+ entry_b.bind("<<ComboboxSelected>>", update)
1013
1149
 
1014
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
1150
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
1015
1151
 
1016
1152
  update(event)
1017
1153
 
1018
- #sort CV function as to be calleed as part of update
1154
+
1155
+ # sort CV function as to be calleed as part of update
1019
1156
  def get_cv_option():
1020
1157
  """
1021
1158
  Will read in the values of the radio button and assign an appropriate value to CV.
1022
- In general this is a list where itis [Unit A cv, UnitB cv], however it could be the string 'Avg'
1159
+ In general this is a list where itis [Unit A cv, UnitB cv], however it could be the string 'Avg'
1023
1160
  """
1024
1161
  global CV_tkinter
1025
1162
  ChosenOption = CV_tkinter.get()
1026
1163
  if ChosenOption == 0:
1027
- CV = 'Avg'
1164
+ CV = "Avg"
1028
1165
  elif ChosenOption == 1:
1029
1166
  CV = [0, 1]
1030
1167
  elif ChosenOption == 2:
1031
- CV = [1, 0]
1168
+ CV = [1, 0]
1032
1169
  return CV
1033
1170
 
1034
- #These are the function used to selct units, including how the CV selctition radio buttons, session selction, unitselection andmoving left and rigthfor next units
1171
+
1172
+ # These are the function used to selct units, including how the CV selctition radio buttons, session selction, unitselection andmoving left and rigthfor next units
1035
1173
  def update_unit_cv():
1036
1174
  """
1037
1175
  When updating the CV we need to do /not do the following:
@@ -1046,12 +1184,12 @@ def update_unit_cv():
1046
1184
  global session_entry_a
1047
1185
  global session_entry_b
1048
1186
  global match_idx
1049
-
1050
- #selecting the unit
1187
+
1188
+ # selecting the unit
1051
1189
  session_a = int(session_entry_a.get())
1052
- session_b = int(session_entry_b.get())
1190
+ session_b = int(session_entry_b.get())
1053
1191
 
1054
- #Keep track of the unit it was before as we dont want to change theunit viewed when changing the CV
1192
+ # Keep track of the unit it was before as we dont want to change theunit viewed when changing the CV
1055
1193
  entry_a_tmp = int(entry_a.get())
1056
1194
  entry_b_tmp = int(entry_b.get())
1057
1195
 
@@ -1061,46 +1199,77 @@ def update_unit_cv():
1061
1199
  entry_b.destroy()
1062
1200
 
1063
1201
  CV = get_cv_option()
1064
- CV_option = CV_tkinter.get() - 1 #want 0 for cv (1,2) , want 1 for cv (2,1)
1065
- if CV == 'Avg':
1066
- #Use average CV values
1067
- tmp_idx_a = np.argwhere((session_switch[session_a -1] <= matches_avg[:,0]) * (matches_avg[:,0] < session_switch[session_a]) == True ).squeeze()
1068
- tmp_idx_b = np.argwhere((session_switch[session_b -1] <= matches_avg[:,1]) * (matches_avg[:,1] < session_switch[session_b]) == True).squeeze()
1202
+ CV_option = CV_tkinter.get() - 1 # want 0 for cv (1,2) , want 1 for cv (2,1)
1203
+ if CV == "Avg":
1204
+ # Use average CV values
1205
+ tmp_idx_a = np.argwhere(
1206
+ (session_switch[session_a - 1] <= matches_avg[:, 0])
1207
+ * (matches_avg[:, 0] < session_switch[session_a])
1208
+ == True
1209
+ ).squeeze()
1210
+ tmp_idx_b = np.argwhere(
1211
+ (session_switch[session_b - 1] <= matches_avg[:, 1])
1212
+ * (matches_avg[:, 1] < session_switch[session_b])
1213
+ == True
1214
+ ).squeeze()
1069
1215
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
1070
- option_a = matches_avg[tmp_idx_a[in_both],:].tolist()
1216
+ option_a = matches_avg[tmp_idx_a[in_both], :].tolist()
1071
1217
 
1072
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
1218
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1073
1219
  entry_a.set(entry_a_tmp)
1074
1220
 
1075
- option_b = np.flip(np.argsort(output_avg[int(entry_a.get()),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1221
+ option_b = np.flip(
1222
+ np.argsort(
1223
+ output_avg[
1224
+ int(entry_a.get()),
1225
+ session_switch[session_b - 1] : session_switch[session_b],
1226
+ ]
1227
+ )
1228
+ + session_switch[session_b - 1]
1229
+ )
1076
1230
  option_b = option_b.tolist()
1077
1231
 
1078
- else :
1079
-
1080
- tmp_idx_a = np.argwhere((session_switch[session_a -1] <= matches_GUI[CV_option][:,0]) * ( matches_GUI[CV_option][:,0] < session_switch[session_a]) == True).squeeze()
1081
- tmp_idx_b = np.argwhere((session_switch[session_b -1] <= matches_GUI[CV_option][:,1]) * ( matches_GUI[CV_option][:,1] < session_switch[session_b]) == True).squeeze()
1232
+ else:
1233
+ tmp_idx_a = np.argwhere(
1234
+ (session_switch[session_a - 1] <= matches_GUI[CV_option][:, 0])
1235
+ * (matches_GUI[CV_option][:, 0] < session_switch[session_a])
1236
+ == True
1237
+ ).squeeze()
1238
+ tmp_idx_b = np.argwhere(
1239
+ (session_switch[session_b - 1] <= matches_GUI[CV_option][:, 1])
1240
+ * (matches_GUI[CV_option][:, 1] < session_switch[session_b])
1241
+ == True
1242
+ ).squeeze()
1082
1243
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
1083
1244
 
1084
- #So is orderby unit A
1085
- option_a = matches_GUI[CV_option][tmp_idx_a[in_both],:].tolist()
1245
+ # So is orderby unit A
1246
+ option_a = matches_GUI[CV_option][tmp_idx_a[in_both], :].tolist()
1086
1247
  if CV_option == 0:
1087
1248
  option_a = sorted(option_a)
1088
1249
 
1089
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
1250
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1090
1251
  entry_a.set(entry_a_tmp)
1091
1252
 
1092
1253
  ##NOT SORTED FOR CV
1093
- option_b = np.flip(np.argsort(output_GUI[CV_option][int(entry_a.get()),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1254
+ option_b = np.flip(
1255
+ np.argsort(
1256
+ output_GUI[CV_option][
1257
+ int(entry_a.get()),
1258
+ session_switch[session_b - 1] : session_switch[session_b],
1259
+ ]
1260
+ )
1261
+ + session_switch[session_b - 1]
1262
+ )
1094
1263
  option_b = option_b.tolist()
1095
1264
 
1096
1265
  ##################
1097
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
1266
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
1098
1267
  entry_b.set(entry_b_tmp)
1099
-
1100
- entry_a.bind('<<ComboboxSelected>>', update_units)
1101
- entry_b.bind('<<ComboboxSelected>>', update)
1102
- entry_a.grid(row = 2, column = 1, columnspan = 2, stick = 'WE', padx = 5)
1103
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
1268
+
1269
+ entry_a.bind("<<ComboboxSelected>>", update_units)
1270
+ entry_b.bind("<<ComboboxSelected>>", update)
1271
+ entry_a.grid(row=2, column=1, columnspan=2, stick="WE", padx=5)
1272
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
1104
1273
 
1105
1274
  tmp_list = [int(entry_a_tmp), int(entry_b_tmp)]
1106
1275
  if tmp_list in option_a:
@@ -1113,7 +1282,7 @@ def update_unit_entryA(event):
1113
1282
  """
1114
1283
  This will be called when the user changes the sesion A, and the following will happen:
1115
1284
  - Keep the same B unit
1116
- - Set A to the first match of the new session
1285
+ - Set A to the first match of the new session
1117
1286
  - Set the Match IDX at 0, for the new list of match pairs
1118
1287
  - update the options in list A
1119
1288
  - update the options for list B
@@ -1124,9 +1293,9 @@ def update_unit_entryA(event):
1124
1293
  global option_a
1125
1294
  global match_idx
1126
1295
  global session_entry_b
1127
-
1296
+
1128
1297
  session_a = int(session_entry_a.get())
1129
- session_b = int(session_entry_b.get())
1298
+ session_b = int(session_entry_b.get())
1130
1299
  EntryBtmp = int(entry_b.get())
1131
1300
 
1132
1301
  if entry_a.winfo_exists() == 1:
@@ -1135,53 +1304,95 @@ def update_unit_entryA(event):
1135
1304
  entry_b.destroy()
1136
1305
 
1137
1306
  CV = get_cv_option()
1138
- cv_option = CV_tkinter.get() - 1 #want 0 for cv (1,2) , want 1 for cv (2,1)
1139
- if CV == 'Avg':
1140
- #Use average CV values
1141
- tmp_idx_a = np.argwhere((session_switch[session_a -1] <= matches_avg[:,0]) * (matches_avg[:,0] < session_switch[session_a]) == True ).squeeze()
1142
- tmp_idx_b = np.argwhere((session_switch[session_b -1] <= matches_avg[:,1]) * (matches_avg[:,1] < session_switch[session_b]) == True).squeeze()
1307
+ cv_option = CV_tkinter.get() - 1 # want 0 for cv (1,2) , want 1 for cv (2,1)
1308
+ if CV == "Avg":
1309
+ # Use average CV values
1310
+ tmp_idx_a = np.argwhere(
1311
+ (session_switch[session_a - 1] <= matches_avg[:, 0])
1312
+ * (matches_avg[:, 0] < session_switch[session_a])
1313
+ == True
1314
+ ).squeeze()
1315
+ tmp_idx_b = np.argwhere(
1316
+ (session_switch[session_b - 1] <= matches_avg[:, 1])
1317
+ * (matches_avg[:, 1] < session_switch[session_b])
1318
+ == True
1319
+ ).squeeze()
1143
1320
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
1144
- option_a = matches_avg[tmp_idx_a[in_both],:].tolist()
1145
-
1146
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
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]]]
1327
+
1328
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1147
1329
  entry_a.set(option_a[0][0])
1148
1330
 
1149
- option_b = np.flip(np.argsort(output_avg[int(entry_a.get()),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1331
+ option_b = np.flip(
1332
+ np.argsort(
1333
+ output_avg[
1334
+ int(entry_a.get()),
1335
+ session_switch[session_b - 1] : session_switch[session_b],
1336
+ ]
1337
+ )
1338
+ + session_switch[session_b - 1]
1339
+ )
1150
1340
  option_b = option_b.tolist()
1151
1341
 
1152
- else :
1153
-
1154
- tmp_idx_a = np.argwhere((session_switch[session_a -1] <= matches_GUI[cv_option][:,0]) * ( matches_GUI[cv_option][:,0] < session_switch[session_a]) == True ).squeeze()
1155
- tmp_idx_b = np.argwhere((session_switch[session_b -1] <= matches_GUI[cv_option][:,1]) * ( matches_GUI[cv_option][:,1] < session_switch[session_b]) == True).squeeze()
1342
+ else:
1343
+ tmp_idx_a = np.argwhere(
1344
+ (session_switch[session_a - 1] <= matches_GUI[cv_option][:, 0])
1345
+ * (matches_GUI[cv_option][:, 0] < session_switch[session_a])
1346
+ == True
1347
+ ).squeeze()
1348
+ tmp_idx_b = np.argwhere(
1349
+ (session_switch[session_b - 1] <= matches_GUI[cv_option][:, 1])
1350
+ * (matches_GUI[cv_option][:, 1] < session_switch[session_b])
1351
+ == True
1352
+ ).squeeze()
1156
1353
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
1157
- option_a = matches_GUI[cv_option][tmp_idx_a[in_both],:].tolist()
1354
+ option_a = matches_GUI[cv_option][tmp_idx_a[in_both], :].tolist()
1158
1355
  if cv_option == 0:
1159
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]]]
1160
1362
 
1161
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
1363
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1162
1364
  entry_a.set(option_a[0][0])
1163
1365
 
1164
- option_b = np.flip(np.argsort(output_GUI[cv_option][int(entry_a.get()),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1366
+ option_b = np.flip(
1367
+ np.argsort(
1368
+ output_GUI[cv_option][
1369
+ int(entry_a.get()),
1370
+ session_switch[session_b - 1] : session_switch[session_b],
1371
+ ]
1372
+ )
1373
+ + session_switch[session_b - 1]
1374
+ )
1165
1375
  option_b = option_b.tolist()
1166
1376
  ##################
1167
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
1377
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
1168
1378
  entry_b.set(EntryBtmp)
1169
- entry_a.bind('<<ComboboxSelected>>', update_units)
1170
- entry_b.bind('<<ComboboxSelected>>', update)
1379
+ entry_a.bind("<<ComboboxSelected>>", update_units)
1380
+ entry_b.bind("<<ComboboxSelected>>", update)
1171
1381
 
1172
- entry_a.grid(row = 2, column = 1, columnspan = 2, stick = 'WE', padx = 5)
1173
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
1382
+ entry_a.grid(row=2, column=1, columnspan=2, stick="WE", padx=5)
1383
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
1174
1384
  match_idx = 0
1175
1385
 
1176
1386
  update(event)
1177
1387
 
1388
+
1178
1389
  def update_unit_entryB(event):
1179
1390
  """
1180
1391
  This will be called when the user changes the sesion B, and the following will happen:
1181
1392
  - Keep the same A unit
1182
1393
  - update the options in list A
1183
1394
  - update the options for list B
1184
- - Set B to the highest match of unit A for the new session B
1395
+ - Set B to the highest match of unit A for the new session B
1185
1396
  - Set the Match IDX at 0, for the new list of match pairs
1186
1397
  - update what is in the screen
1187
1398
  """
@@ -1190,9 +1401,9 @@ def update_unit_entryB(event):
1190
1401
  global option_a
1191
1402
  global match_idx
1192
1403
  global session_entry_a
1193
-
1404
+
1194
1405
  session_a = int(session_entry_a.get())
1195
- session_b = int(session_entry_b.get())
1406
+ session_b = int(session_entry_b.get())
1196
1407
  entry_a_tmp = int(entry_a.get())
1197
1408
 
1198
1409
  if entry_a.winfo_exists() == 1:
@@ -1201,49 +1412,81 @@ def update_unit_entryB(event):
1201
1412
  entry_b.destroy()
1202
1413
 
1203
1414
  CV = get_cv_option()
1204
- CV_option = CV_tkinter.get() - 1 #want 0 for cv (1,2) , want 1 for cv (2,1)
1205
- if CV == 'Avg':
1206
- #Use average CV values
1207
- tmp_idx_a = np.argwhere((session_switch[session_a -1] <= matches_avg[:,0]) * (matches_avg[:,0] < session_switch[session_a]) == True ).squeeze()
1208
- tmp_idx_b = np.argwhere((session_switch[session_b -1] <= matches_avg[:,1]) * (matches_avg[:,1] < session_switch[session_b]) == True).squeeze()
1415
+ CV_option = CV_tkinter.get() - 1 # want 0 for cv (1,2) , want 1 for cv (2,1)
1416
+ if CV == "Avg":
1417
+ # Use average CV values
1418
+ tmp_idx_a = np.argwhere(
1419
+ (session_switch[session_a - 1] <= matches_avg[:, 0])
1420
+ * (matches_avg[:, 0] < session_switch[session_a])
1421
+ == True
1422
+ ).squeeze()
1423
+ tmp_idx_b = np.argwhere(
1424
+ (session_switch[session_b - 1] <= matches_avg[:, 1])
1425
+ * (matches_avg[:, 1] < session_switch[session_b])
1426
+ == True
1427
+ ).squeeze()
1209
1428
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
1210
- option_a = matches_avg[tmp_idx_a[in_both],:].tolist()
1429
+ option_a = matches_avg[tmp_idx_a[in_both], :].tolist()
1211
1430
 
1212
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
1431
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1213
1432
  entry_a.set(entry_a_tmp)
1214
1433
 
1215
- option_b = np.flip(np.argsort(output_avg[int(entry_a.get()),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1434
+ option_b = np.flip(
1435
+ np.argsort(
1436
+ output_avg[
1437
+ int(entry_a.get()),
1438
+ session_switch[session_b - 1] : session_switch[session_b],
1439
+ ]
1440
+ )
1441
+ + session_switch[session_b - 1]
1442
+ )
1216
1443
  option_b = option_b.tolist()
1217
1444
 
1218
- else :
1219
-
1220
- tmp_idx_a = np.argwhere((session_switch[session_a -1] <= matches_GUI[CV_option][:,0]) * ( matches_GUI[CV_option][:,0] < session_switch[session_a]) == True ).squeeze()
1221
- tmp_idx_b = np.argwhere((session_switch[session_b -1] <= matches_GUI[CV_option][:,1]) * ( matches_GUI[CV_option][:,1] < session_switch[session_b]) == True).squeeze()
1445
+ else:
1446
+ tmp_idx_a = np.argwhere(
1447
+ (session_switch[session_a - 1] <= matches_GUI[CV_option][:, 0])
1448
+ * (matches_GUI[CV_option][:, 0] < session_switch[session_a])
1449
+ == True
1450
+ ).squeeze()
1451
+ tmp_idx_b = np.argwhere(
1452
+ (session_switch[session_b - 1] <= matches_GUI[CV_option][:, 1])
1453
+ * (matches_GUI[CV_option][:, 1] < session_switch[session_b])
1454
+ == True
1455
+ ).squeeze()
1222
1456
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
1223
- option_a = matches_GUI[CV_option][tmp_idx_a[in_both],:].tolist()
1457
+ option_a = matches_GUI[CV_option][tmp_idx_a[in_both], :].tolist()
1224
1458
  if CV_option == 0:
1225
1459
  option_a = sorted(option_a)
1226
1460
 
1227
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
1461
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1228
1462
  entry_a.set(entry_a_tmp)
1229
1463
 
1230
- option_b = np.flip(np.argsort(output_GUI[CV_option][int(entry_a_tmp),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1464
+ option_b = np.flip(
1465
+ np.argsort(
1466
+ output_GUI[CV_option][
1467
+ int(entry_a_tmp),
1468
+ session_switch[session_b - 1] : session_switch[session_b],
1469
+ ]
1470
+ )
1471
+ + session_switch[session_b - 1]
1472
+ )
1231
1473
  option_b = option_b.tolist()
1232
-
1474
+
1233
1475
  ##################
1234
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
1476
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
1235
1477
  entry_b.set(option_b[0])
1236
- entry_a.bind('<<ComboboxSelected>>', update_units)
1237
- entry_b.bind('<<ComboboxSelected>>', update)
1478
+ entry_a.bind("<<ComboboxSelected>>", update_units)
1479
+ entry_b.bind("<<ComboboxSelected>>", update)
1238
1480
 
1239
- entry_a.grid(row = 2, column = 1, columnspan = 2, stick = 'WE', padx = 5)
1240
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
1241
- match_idx = 0
1481
+ entry_a.grid(row=2, column=1, columnspan=2, stick="WE", padx=5)
1482
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
1483
+ match_idx = 0
1242
1484
 
1243
1485
  update(event)
1244
1486
 
1487
+
1245
1488
  def update_units(event):
1246
- """
1489
+ """
1247
1490
  This function is called when a option in the Unit A dropdown is selected (is a pair of units)
1248
1491
  - split the list of units into two pairs for unit labels for UnitA and UnitB
1249
1492
  - Update the unit B dropdown box to reflect matches for the new Unit A
@@ -1254,7 +1497,6 @@ def update_units(event):
1254
1497
  global entry_b
1255
1498
  global option_a
1256
1499
  global session_entry_b
1257
-
1258
1500
 
1259
1501
  session_b = int(session_entry_b.get())
1260
1502
  selected = entry_a.get()
@@ -1265,34 +1507,47 @@ def update_units(event):
1265
1507
  tmpA = selected.split()[0]
1266
1508
  tmpB = selected.split()[1]
1267
1509
  entry_a.set(tmpA)
1268
-
1269
1510
 
1270
- #need to make it so the list for B updates
1511
+ # need to make it so the list for B updates
1271
1512
  CV = get_cv_option()
1272
- CV_option = CV_tkinter.get() - 1 #want 0 for cv (1,2) , want 1 for cv (2,1)
1273
- if CV == 'Avg':
1274
- #Use average CV value
1275
- option_b = np.flip(np.argsort(output_avg[int(tmpA),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1513
+ CV_option = CV_tkinter.get() - 1 # want 0 for cv (1,2) , want 1 for cv (2,1)
1514
+ if CV == "Avg":
1515
+ # Use average CV value
1516
+ option_b = np.flip(
1517
+ np.argsort(
1518
+ output_avg[
1519
+ int(tmpA), session_switch[session_b - 1] : session_switch[session_b]
1520
+ ]
1521
+ )
1522
+ + session_switch[session_b - 1]
1523
+ )
1276
1524
  option_b = option_b.tolist()
1277
- else :
1278
- option_b = np.flip(np.argsort(output_GUI[CV_option][int(tmpA),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1525
+ else:
1526
+ option_b = np.flip(
1527
+ np.argsort(
1528
+ output_GUI[CV_option][
1529
+ int(tmpA), session_switch[session_b - 1] : session_switch[session_b]
1530
+ ]
1531
+ )
1532
+ + session_switch[session_b - 1]
1533
+ )
1279
1534
  option_b = option_b.tolist()
1280
-
1535
+
1281
1536
  ##################
1282
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
1537
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
1283
1538
  entry_b.set(tmpB)
1284
- entry_b.bind('<<ComboboxSelected>>', update)
1285
-
1286
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
1539
+ entry_b.bind("<<ComboboxSelected>>", update)
1287
1540
 
1541
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
1288
1542
 
1289
- #need to get list index of the selected postion
1543
+ # need to get list index of the selected postion
1290
1544
  tmp_list = [int(tmpA), int(tmpB)]
1291
1545
  match_idx = option_a.index(tmp_list)
1292
1546
  update(event)
1293
1547
 
1548
+
1294
1549
  def next_pair(event):
1295
- """
1550
+ """
1296
1551
  This function is called when moving to the next unit in the mathc list:
1297
1552
  - get the new unit idx for unit A and unit B
1298
1553
  - update the Units
@@ -1305,35 +1560,52 @@ def next_pair(event):
1305
1560
  global session_entry_b
1306
1561
 
1307
1562
  session_b = int(session_entry_b.get())
1308
- match_idx +=1
1563
+ match_idx += 1
1309
1564
  tmp_a, tmp_b = option_a[match_idx]
1310
1565
  entry_a.set(tmp_a)
1311
1566
 
1312
1567
  if entry_b.winfo_exists() == 1:
1313
1568
  entry_b.destroy()
1314
1569
 
1315
- #Update B, and change it's dropbox
1570
+ # Update B, and change it's dropbox
1316
1571
  CV = get_cv_option()
1317
- cv_option = CV_tkinter.get() - 1 #want 0 for cv (1,2) , want 1 for cv (2,1)
1318
- if CV == 'Avg':
1319
- #Use average CV value
1320
- option_b = np.flip(np.argsort(output_avg[int(tmp_a),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1572
+ cv_option = CV_tkinter.get() - 1 # want 0 for cv (1,2) , want 1 for cv (2,1)
1573
+ if CV == "Avg":
1574
+ # Use average CV value
1575
+ option_b = np.flip(
1576
+ np.argsort(
1577
+ output_avg[
1578
+ int(tmp_a),
1579
+ session_switch[session_b - 1] : session_switch[session_b],
1580
+ ]
1581
+ )
1582
+ + session_switch[session_b - 1]
1583
+ )
1321
1584
  option_b = option_b.tolist()
1322
- else :
1323
- option_b = np.flip(np.argsort(output_GUI[cv_option][int(tmp_a),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1585
+ else:
1586
+ option_b = np.flip(
1587
+ np.argsort(
1588
+ output_GUI[cv_option][
1589
+ int(tmp_a),
1590
+ session_switch[session_b - 1] : session_switch[session_b],
1591
+ ]
1592
+ )
1593
+ + session_switch[session_b - 1]
1594
+ )
1324
1595
  option_b = option_b.tolist()
1325
-
1596
+
1326
1597
  ##################
1327
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
1598
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
1328
1599
  entry_b.set(tmp_b)
1329
- entry_b.bind('<<ComboboxSelected>>', update)
1600
+ entry_b.bind("<<ComboboxSelected>>", update)
1330
1601
 
1331
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
1602
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
1332
1603
 
1333
1604
  update(event)
1334
1605
 
1606
+
1335
1607
  def previous_pair(event):
1336
- """
1608
+ """
1337
1609
  This function is called when moving to the previous unit in the mathc list:
1338
1610
  - get the new unit idx for unit A and unit B
1339
1611
  - update the Units
@@ -1344,36 +1616,52 @@ def previous_pair(event):
1344
1616
  global entry_b
1345
1617
  global option_a
1346
1618
  global session_entry_b
1347
-
1619
+
1348
1620
  session_b = int(session_entry_b.get())
1349
- match_idx -=1
1621
+ match_idx -= 1
1350
1622
  tmp_a, tmp_b = option_a[match_idx]
1351
1623
  entry_a.set(tmp_a)
1352
1624
 
1353
-
1354
1625
  if entry_b.winfo_exists() == 1:
1355
1626
  entry_b.destroy()
1356
1627
 
1357
- #Update B, and change it's dropbox
1628
+ # Update B, and change it's dropbox
1358
1629
  CV = get_cv_option()
1359
- CV_option = CV_tkinter.get() - 1 #want 0 for cv (1,2) , want 1 for cv (2,1)
1360
- if CV == 'Avg':
1361
- #Use average CV value
1362
- option_b = np.flip(np.argsort(output_avg[int(tmp_a),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1630
+ CV_option = CV_tkinter.get() - 1 # want 0 for cv (1,2) , want 1 for cv (2,1)
1631
+ if CV == "Avg":
1632
+ # Use average CV value
1633
+ option_b = np.flip(
1634
+ np.argsort(
1635
+ output_avg[
1636
+ int(tmp_a),
1637
+ session_switch[session_b - 1] : session_switch[session_b],
1638
+ ]
1639
+ )
1640
+ + session_switch[session_b - 1]
1641
+ )
1363
1642
  option_b = option_b.tolist()
1364
- else :
1365
- option_b = np.flip(np.argsort(output_GUI[CV_option][int(tmp_a),session_switch[session_b-1]:session_switch[session_b]]) + session_switch[session_b-1])
1643
+ else:
1644
+ option_b = np.flip(
1645
+ np.argsort(
1646
+ output_GUI[CV_option][
1647
+ int(tmp_a),
1648
+ session_switch[session_b - 1] : session_switch[session_b],
1649
+ ]
1650
+ )
1651
+ + session_switch[session_b - 1]
1652
+ )
1366
1653
  option_b = option_b.tolist()
1367
-
1654
+
1368
1655
  ##################
1369
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
1656
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
1370
1657
  entry_b.set(tmp_b)
1371
- entry_b.bind('<<ComboboxSelected>>', update)
1658
+ entry_b.bind("<<ComboboxSelected>>", update)
1372
1659
 
1373
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
1660
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
1374
1661
 
1375
1662
  update(event)
1376
1663
 
1664
+
1377
1665
  def swap_units():
1378
1666
  global entry_frame
1379
1667
  global entry_a
@@ -1383,86 +1671,121 @@ def swap_units():
1383
1671
  global match_idx
1384
1672
  global option_a
1385
1673
 
1386
- #get all initial info
1674
+ # get all initial info
1387
1675
  entry_a_tmp = int(entry_a.get())
1388
1676
  entry_b_tmp = int(entry_b.get())
1389
1677
  session_a_tmp = int(session_entry_a.get())
1390
1678
  session_b_tmp = int(session_entry_b.get())
1391
1679
 
1392
- #delte old box a and b
1680
+ # delte old box a and b
1393
1681
  if entry_a.winfo_exists() == 1:
1394
1682
  entry_a.destroy()
1395
1683
  if entry_b.winfo_exists() == 1:
1396
1684
  entry_b.destroy()
1397
1685
 
1398
- #swap allpairs
1686
+ # swap allpairs
1399
1687
  session_entry_a.set(session_b_tmp)
1400
1688
  session_entry_b.set(session_a_tmp)
1401
-
1402
- #Update A and B dropsown boxs
1689
+
1690
+ # Update A and B dropsown boxs
1403
1691
  CV = get_cv_option()
1404
- cv_option = CV_tkinter.get() - 1 #want 0 for cv (1,2) , want 1 for cv (2,1)
1405
- if CV == 'Avg':
1406
- #Use average CV values
1407
- tmp_idx_a = np.argwhere((session_switch[session_b_tmp -1] <= matches_avg[:,0]) * (matches_avg[:,0] < session_switch[session_b_tmp]) == True ).squeeze()
1408
- tmp_idx_b = np.argwhere((session_switch[session_a_tmp -1] <= matches_avg[:,1]) * (matches_avg[:,1] < session_switch[session_a_tmp]) == True).squeeze()
1692
+ cv_option = CV_tkinter.get() - 1 # want 0 for cv (1,2) , want 1 for cv (2,1)
1693
+ if CV == "Avg":
1694
+ # Use average CV values
1695
+ tmp_idx_a = np.argwhere(
1696
+ (session_switch[session_b_tmp - 1] <= matches_avg[:, 0])
1697
+ * (matches_avg[:, 0] < session_switch[session_b_tmp])
1698
+ == True
1699
+ ).squeeze()
1700
+ tmp_idx_b = np.argwhere(
1701
+ (session_switch[session_a_tmp - 1] <= matches_avg[:, 1])
1702
+ * (matches_avg[:, 1] < session_switch[session_a_tmp])
1703
+ == True
1704
+ ).squeeze()
1409
1705
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
1410
- option_a = matches_avg[tmp_idx_a[in_both],:].tolist()
1706
+ option_a = matches_avg[tmp_idx_a[in_both], :].tolist()
1411
1707
 
1412
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
1708
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1413
1709
  entry_a.set(entry_b_tmp)
1414
1710
 
1415
- option_b = np.flip(np.argsort(output_avg[int(entry_a.get()),session_switch[session_a_tmp-1]:session_switch[session_a_tmp]]) + session_switch[session_a_tmp-1])
1711
+ option_b = np.flip(
1712
+ np.argsort(
1713
+ output_avg[
1714
+ int(entry_a.get()),
1715
+ session_switch[session_a_tmp - 1] : session_switch[session_a_tmp],
1716
+ ]
1717
+ )
1718
+ + session_switch[session_a_tmp - 1]
1719
+ )
1416
1720
  option_b = option_b.tolist()
1417
1721
 
1418
- else :
1419
-
1420
- tmp_idx_a = np.argwhere((session_switch[session_b_tmp -1] <= matches_GUI[cv_option][:,0]) * ( matches_GUI[cv_option][:,0] < session_switch[session_b_tmp]) == True).squeeze()
1421
- tmp_idx_b = np.argwhere((session_switch[session_a_tmp -1] <= matches_GUI[cv_option][:,1]) * ( matches_GUI[cv_option][:,1] < session_switch[session_a_tmp]) == True).squeeze()
1722
+ else:
1723
+ tmp_idx_a = np.argwhere(
1724
+ (session_switch[session_b_tmp - 1] <= matches_GUI[cv_option][:, 0])
1725
+ * (matches_GUI[cv_option][:, 0] < session_switch[session_b_tmp])
1726
+ == True
1727
+ ).squeeze()
1728
+ tmp_idx_b = np.argwhere(
1729
+ (session_switch[session_a_tmp - 1] <= matches_GUI[cv_option][:, 1])
1730
+ * (matches_GUI[cv_option][:, 1] < session_switch[session_a_tmp])
1731
+ == True
1732
+ ).squeeze()
1422
1733
  in_both = np.isin(tmp_idx_a, tmp_idx_b)
1423
1734
 
1424
- #So is orderby unit A
1425
- option_a = matches_GUI[cv_option][tmp_idx_a[in_both],:].tolist()
1735
+ # So is orderby unit A
1736
+ option_a = matches_GUI[cv_option][tmp_idx_a[in_both], :].tolist()
1426
1737
  if cv_option == 0:
1427
1738
  option_a = sorted(option_a)
1428
1739
 
1429
- entry_a = ttk.Combobox(entry_frame, values = option_a, width = 10)
1740
+ entry_a = ttk.Combobox(entry_frame, values=option_a, width=10)
1430
1741
  entry_a.set(entry_b_tmp)
1431
1742
 
1432
1743
  ##NOT SORTED FOR CV
1433
- option_b = np.flip(np.argsort(output_GUI[cv_option][int(entry_a.get()),session_switch[session_a_tmp-1]:session_switch[session_a_tmp]]) + session_switch[session_a_tmp-1])
1744
+ option_b = np.flip(
1745
+ np.argsort(
1746
+ output_GUI[cv_option][
1747
+ int(entry_a.get()),
1748
+ session_switch[session_a_tmp - 1] : session_switch[session_a_tmp],
1749
+ ]
1750
+ )
1751
+ + session_switch[session_a_tmp - 1]
1752
+ )
1434
1753
  option_b = option_b.tolist()
1435
1754
 
1436
1755
  ##################
1437
- entry_b = ttk.Combobox(entry_frame, values = option_b, width = 10 )
1756
+ entry_b = ttk.Combobox(entry_frame, values=option_b, width=10)
1438
1757
  entry_b.set(entry_a_tmp)
1439
-
1440
- entry_a.bind('<<ComboboxSelected>>', update_units)
1441
- entry_b.bind('<<ComboboxSelected>>', update)
1442
- entry_a.grid(row = 2, column = 1, columnspan = 2, stick = 'WE', padx = 5)
1443
- entry_b.grid(row = 2, column = 3, columnspan = 2, sticky = 'WE', padx = 5)
1758
+
1759
+ entry_a.bind("<<ComboboxSelected>>", update_units)
1760
+ entry_b.bind("<<ComboboxSelected>>", update)
1761
+ entry_a.grid(row=2, column=1, columnspan=2, stick="WE", padx=5)
1762
+ entry_b.grid(row=2, column=3, columnspan=2, sticky="WE", padx=5)
1444
1763
 
1445
1764
  tmp_list = [int(entry_b_tmp), int(entry_a_tmp)]
1446
1765
 
1447
1766
  match_idx = option_a.index(tmp_list)
1448
1767
  update(None)
1449
1768
 
1769
+
1450
1770
  def get_score_histograms(scores_to_include, output_threshold):
1451
- """
1771
+ """
1452
1772
  Scores2Include is the dictionary of all scores.
1453
1773
  ProbThreshold is a nUnits*nUnits array where each index is 0 (Not Match) 1 (Match)
1454
1774
  """
1455
1775
 
1456
- #are lsit of length 6 each list item is 2 np arrays(bins, values)
1776
+ # are lsit of length 6 each list item is 2 np arrays(bins, values)
1457
1777
  hist_names = []
1458
1778
  hist = []
1459
1779
  hist_matches = []
1460
1780
  for key, values in scores_to_include.items():
1461
1781
  hist_names.append(key)
1462
- hist.append(np.histogram(values, bins = 100, density = True))
1463
- hist_matches.append(np.histogram(values[output_threshold.astype(bool)], bins = 100, density = True))
1782
+ hist.append(np.histogram(values, bins=100, density=True))
1783
+ hist_matches.append(
1784
+ np.histogram(values[output_threshold.astype(bool)], bins=100, density=True)
1785
+ )
1786
+
1787
+ return hist_names, hist, hist_matches
1464
1788
 
1465
- return hist_names, hist, hist_matches
1466
1789
 
1467
1790
  def add_original_ID(UnitA, UnitB):
1468
1791
  global original_id_label
@@ -1475,13 +1798,21 @@ def add_original_ID(UnitA, UnitB):
1475
1798
  try:
1476
1799
  original_id_a = int(clus_info["original_ids"][UnitA].squeeze())
1477
1800
  original_id_b = int(clus_info["original_ids"][UnitB].squeeze())
1478
- original_id_label = ttk.Label(root, text=f'The Original Unit IDs are:\nUnit A: {original_id_a} Unit B: {original_id_b}', borderwidth=2, relief='groove')
1801
+ original_id_label = ttk.Label(
1802
+ root,
1803
+ text=f"The Original Unit IDs are:\nUnit A: {original_id_a} Unit B: {original_id_b}",
1804
+ borderwidth=2,
1805
+ relief="groove",
1806
+ )
1479
1807
  except IndexError as e:
1480
1808
  print(f"Error: {e}")
1481
- original_id_label = ttk.Label(root, text='Error: Unit ID out of bounds', borderwidth=2, relief='groove')
1809
+ original_id_label = ttk.Label(
1810
+ root, text="Error: Unit ID out of bounds", borderwidth=2, relief="groove"
1811
+ )
1482
1812
 
1483
1813
  original_id_label.grid(row=2, column=2, ipadx=5, ipady=5)
1484
1814
 
1815
+
1485
1816
  def add_probability_label(UnitA, UnitB, CVoption):
1486
1817
  global bayes_label
1487
1818
 
@@ -1489,148 +1820,202 @@ def add_probability_label(UnitA, UnitB, CVoption):
1489
1820
  bayes_label.destroy()
1490
1821
 
1491
1822
  if CVoption == -1:
1492
- bayes_label = ttk.Label(root, text = f'The UM probabilty for this match is:\n {np.round(output_avg[UnitA, UnitB],5)}', borderwidth = 2 , relief= 'groove' )
1493
- bayes_label.grid(row = 2, column = 1, ipadx = 5, ipady = 5)
1823
+ bayes_label = ttk.Label(
1824
+ root,
1825
+ text=f"The UM probabilty for this match is:\n {np.round(output_avg[UnitA, UnitB], 5)}",
1826
+ borderwidth=2,
1827
+ relief="groove",
1828
+ )
1829
+ bayes_label.grid(row=2, column=1, ipadx=5, ipady=5)
1494
1830
  else:
1495
- bayes_label = ttk.Label(root, text = f'The UM probabilty for this match is:\n {np.round(output_GUI[CVoption][UnitA, UnitB],5)}', borderwidth = 2 , relief= 'groove')
1496
- bayes_label.grid(row = 2, column = 1, ipadx = 5, ipady = 5)
1831
+ bayes_label = ttk.Label(
1832
+ root,
1833
+ text=f"The UM probabilty for this match is:\n {np.round(output_GUI[CVoption][UnitA, UnitB], 5)}",
1834
+ borderwidth=2,
1835
+ relief="groove",
1836
+ )
1837
+ bayes_label.grid(row=2, column=1, ipadx=5, ipady=5)
1497
1838
 
1498
1839
 
1499
- def set_match(event = None):
1840
+ def set_match(event=None):
1500
1841
  global is_match
1501
1842
  unit_a = int(entry_a.get())
1502
1843
  unit_b = int(entry_b.get())
1503
1844
 
1504
- is_match.append( [unit_a, unit_b] )
1505
- is_match.append( [unit_b, unit_a] )
1845
+ is_match.append([unit_a, unit_b])
1846
+ is_match.append([unit_b, unit_a])
1506
1847
 
1507
-
1508
1848
 
1509
- def set_not_match(event = None):
1849
+ def set_not_match(event=None):
1510
1850
  global not_match
1511
1851
  unit_a = int(entry_a.get())
1512
1852
  unit_b = int(entry_b.get())
1513
1853
 
1514
- not_match.append( [unit_a, unit_b] )
1515
- not_match.append( [unit_b, unit_a] )
1854
+ not_match.append([unit_a, unit_b])
1855
+ not_match.append([unit_b, unit_a])
1516
1856
 
1517
1857
 
1518
1858
  def MakeTable(table):
1519
1859
  global frame_table
1520
-
1860
+
1521
1861
  if frame_table.winfo_exists() == 1:
1522
1862
  frame_table.destroy()
1523
1863
 
1524
1864
  total_rows = len(table)
1525
1865
  total_columns = len(table[0])
1526
1866
 
1527
- colors = ['black', 'green', 'blue']
1528
- frame_table = ttk.LabelFrame(root, text = 'UnitData')
1867
+ colors = ["black", "green", "blue"]
1868
+ frame_table = ttk.LabelFrame(root, text="UnitData")
1529
1869
  for i in range(total_rows):
1530
1870
  for j in range(total_columns):
1531
-
1532
1871
  e = ttk.Entry(frame_table, width=20)
1533
1872
  e.insert(END, table[i][j])
1534
- e.configure(state='readonly')
1873
+ e.configure(state="readonly")
1535
1874
  e.grid(row=i, column=j)
1536
- frame_table.grid(row = 4, column = 0, padx = 10, pady = 10)
1875
+ frame_table.grid(row=4, column=0, padx=10, pady=10)
1876
+
1537
1877
 
1538
- #get table data #ADD STABILTY - prob of unit with itself accros cv
1878
+ # get table data #ADD STABILTY - prob of unit with itself accros cv
1539
1879
  def get_table_data(UnitA, UnitB, CV):
1540
- template = [['Unit','A','B'],
1541
- ['Avg Centroid','tmp','tmp'],
1542
- ['Amplitude','tmp','tmp'],
1543
- ['Spatial Decay','tmp','tmp'],
1544
- ['Units Matches','tmp','tmp'],
1545
- ['Stability','tmp','tmp']]
1880
+ template = [
1881
+ ["Unit", "A", "B"],
1882
+ ["Avg Centroid", "tmp", "tmp"],
1883
+ ["Amplitude", "tmp", "tmp"],
1884
+ ["Spatial Decay", "tmp", "tmp"],
1885
+ ["Units Matches", "tmp", "tmp"],
1886
+ ["Stability", "tmp", "tmp"],
1887
+ ]
1546
1888
 
1547
1889
  total_rows = len(template)
1548
1890
  total_columns = len(template[0])
1549
- unit_idx_tmp =[0 , UnitA, UnitB]
1891
+ unit_idx_tmp = [0, UnitA, UnitB]
1550
1892
  table = template
1551
1893
 
1552
- if CV == 'Avg':
1894
+ if CV == "Avg":
1553
1895
  for i in range(total_rows):
1554
1896
  for j in range(total_columns):
1555
- if j == 0 :
1556
- continue
1897
+ if j == 0:
1898
+ continue
1557
1899
  if i == 0:
1558
1900
  table[i][j] = str(unit_idx_tmp[j])
1559
1901
  if i == 1:
1560
- table[i][j] = str( np.round(avg_centroid_avg[:,unit_idx_tmp[j]], 2))
1561
- if i == 2:
1562
- table[i][j] = str( np.round(amplitude_avg[unit_idx_tmp[j]], 2))
1902
+ table[i][j] = str(np.round(avg_centroid_avg[:, unit_idx_tmp[j]], 2))
1903
+ if i == 2:
1904
+ table[i][j] = str(np.round(amplitude_avg[unit_idx_tmp[j]], 2))
1563
1905
  if i == 3:
1564
- table[i][j] = str( np.round(spatial_decay_avg[unit_idx_tmp[j]], 3))
1906
+ table[i][j] = str(np.round(spatial_decay_avg[unit_idx_tmp[j]], 3))
1565
1907
  if i == 4:
1566
- table[i][j] = str(np.argwhere( (within_session*output_avg)[unit_idx_tmp[j],:] > match_threshold)).replace('[', '').replace(']', '')
1567
- if i ==5:
1568
- table[i][j] = str( np.round(output_GUI[0][unit_idx_tmp[j], unit_idx_tmp[j]], 3))
1569
-
1908
+ table[i][j] = (
1909
+ str(
1910
+ np.argwhere(
1911
+ (within_session * output_avg)[unit_idx_tmp[j], :]
1912
+ > match_threshold
1913
+ )
1914
+ )
1915
+ .replace("[", "")
1916
+ .replace("]", "")
1917
+ )
1918
+ if i == 5:
1919
+ table[i][j] = str(
1920
+ np.round(output_GUI[0][unit_idx_tmp[j], unit_idx_tmp[j]], 3)
1921
+ )
1922
+
1570
1923
  else:
1571
1924
  for i in range(total_rows):
1572
1925
  for j in range(total_columns):
1573
- if j == 0 :
1574
- continue
1926
+ if j == 0:
1927
+ continue
1575
1928
  if i == 0:
1576
1929
  table[i][j] = str(unit_idx_tmp[j])
1577
1930
  if i == 1:
1578
- table[i][j] = str( np.round(avg_centroid[:,unit_idx_tmp[j],CV[j-1]], 2))
1579
- if i == 2:
1580
- table[i][j] = str( np.round(amplitude[unit_idx_tmp[j],CV[j-1]], 2))
1931
+ table[i][j] = str(
1932
+ np.round(avg_centroid[:, unit_idx_tmp[j], CV[j - 1]], 2)
1933
+ )
1934
+ if i == 2:
1935
+ table[i][j] = str(
1936
+ np.round(amplitude[unit_idx_tmp[j], CV[j - 1]], 2)
1937
+ )
1581
1938
  if i == 3:
1582
- table[i][j] = str( np.round(spatial_decay[unit_idx_tmp[j],CV[j-1]], 3))
1939
+ table[i][j] = str(
1940
+ np.round(spatial_decay[unit_idx_tmp[j], CV[j - 1]], 3)
1941
+ )
1583
1942
  if i == 4:
1584
- table[i][j] = str(np.argwhere( (within_session*output_GUI[CV[0]])[unit_idx_tmp[j],:] > match_threshold )).replace('[', '').replace(']', '')
1585
- if i ==5:
1586
- table[i][j] = str( np.round(output_GUI[0][unit_idx_tmp[j], unit_idx_tmp[j]], 3))
1587
-
1943
+ table[i][j] = (
1944
+ str(
1945
+ np.argwhere(
1946
+ (within_session * output_GUI[CV[0]])[unit_idx_tmp[j], :]
1947
+ > match_threshold
1948
+ )
1949
+ )
1950
+ .replace("[", "")
1951
+ .replace("]", "")
1952
+ )
1953
+ if i == 5:
1954
+ table[i][j] = str(
1955
+ np.round(output_GUI[0][unit_idx_tmp[j], unit_idx_tmp[j]], 3)
1956
+ )
1957
+
1588
1958
  return table
1589
1959
 
1960
+
1590
1961
  def get_unit_score_table(UnitA, UnitB, CVoption):
1591
-
1592
- table = [['tmp'] * 2 for i in range((len(scores_to_include_avg) +1))]
1593
1962
 
1594
- table[0] = ['Score', f'{UnitA} and {UnitB}']
1963
+ table = [["tmp"] * 2 for i in range((len(scores_to_include_avg) + 1))]
1964
+
1965
+ table[0] = ["Score", f"{UnitA} and {UnitB}"]
1595
1966
 
1596
1967
  if CVoption == -1:
1597
1968
  for i in range(len(scores_to_include_avg)):
1598
1969
  for j in range(2):
1599
- if j ==0:
1600
- table[i+1][j] = list(scores_to_include_avg.keys())[i]
1970
+ if j == 0:
1971
+ table[i + 1][j] = list(scores_to_include_avg.keys())[i]
1601
1972
  else:
1602
- table[i+1][j] = str( np.round(scores_to_include_avg[list(scores_to_include_avg.keys())[i]][UnitA, UnitB], 3))
1603
-
1973
+ table[i + 1][j] = str(
1974
+ np.round(
1975
+ scores_to_include_avg[
1976
+ list(scores_to_include_avg.keys())[i]
1977
+ ][UnitA, UnitB],
1978
+ 3,
1979
+ )
1980
+ )
1981
+
1604
1982
  else:
1605
1983
  for i in range(len(scores_to_include_avg)):
1606
1984
  for j in range(2):
1607
- if j ==0:
1608
- table[i+1][j] = list(scores_to_include_GUI[CVoption].keys())[i]
1985
+ if j == 0:
1986
+ table[i + 1][j] = list(scores_to_include_GUI[CVoption].keys())[i]
1609
1987
  else:
1610
- table[i+1][j] = str( np.round(scores_to_include_GUI[CVoption][list(scores_to_include_GUI[CVoption].keys())[i]][UnitA, UnitB], 3))
1988
+ table[i + 1][j] = str(
1989
+ np.round(
1990
+ scores_to_include_GUI[CVoption][
1991
+ list(scores_to_include_GUI[CVoption].keys())[i]
1992
+ ][UnitA, UnitB],
1993
+ 3,
1994
+ )
1995
+ )
1611
1996
 
1612
1997
  return table
1613
1998
 
1999
+
1614
2000
  def make_unit_score_table(table):
1615
2001
  global score_table
1616
-
2002
+
1617
2003
  if score_table.winfo_exists() == 1:
1618
2004
  score_table.destroy()
1619
2005
 
1620
2006
  total_rows = len(table)
1621
2007
  total_columns = len(table[0])
1622
2008
 
1623
- colors = ['black', 'Purple']
1624
- score_table = ttk.LabelFrame(root, text = 'UM Scores')
2009
+ colors = ["black", "Purple"]
2010
+ score_table = ttk.LabelFrame(root, text="UM Scores")
1625
2011
  for i in range(total_rows):
1626
2012
  for j in range(total_columns):
1627
-
1628
- e = ttk.Entry(score_table, width = 30)
2013
+ e = ttk.Entry(score_table, width=30)
1629
2014
  e.insert(END, table[i][j])
1630
- e.configure(state='readonly')
2015
+ e.configure(state="readonly")
1631
2016
  e.grid(row=i, column=j)
1632
2017
 
1633
- score_table.grid(row = 5, column = 0, columnspan=2, padx = 10, pady = 10)
2018
+ score_table.grid(row=5, column=0, columnspan=2, padx=10, pady=10)
1634
2019
 
1635
2020
 
1636
2021
  def plot_avg_waveforms(UnitA, UnitB, CV):
@@ -1638,212 +2023,300 @@ def plot_avg_waveforms(UnitA, UnitB, CV):
1638
2023
  if avg_waveform_plot.winfo_exists() == 1:
1639
2024
  avg_waveform_plot.destroy()
1640
2025
 
1641
- fig = Figure(figsize = (3, 3),
1642
- dpi = 100)
1643
- fig.patch.set_facecolor('#33393b')
1644
-
2026
+ fig = Figure(figsize=(3, 3), dpi=100)
2027
+ fig.patch.set_facecolor("#33393b")
2028
+
1645
2029
  plt1 = fig.add_subplot(111)
1646
- #plt1.spines[["left", "bottom"]].set_position(("data", 0))
2030
+ # plt1.spines[["left", "bottom"]].set_position(("data", 0))
1647
2031
  plt1.spines[["bottom"]].set_position(("data", 0))
1648
2032
  plt1.spines[["top", "right"]].set_visible(False)
1649
- plt1.patch.set_facecolor('#2d2d2d')
1650
- plt1.xaxis.set_label_coords(0.9,0)
1651
-
1652
-
1653
- if CV =='Avg':
1654
- plt1.plot(avg_waveform_avg[:,UnitA], 'g', label=f'Unit A ({UnitA})')
1655
- plt1.plot(avg_waveform_avg[:,UnitB], 'b', label=f'Unit B ({UnitB})')
1656
- plt1.set_xlabel('Time (ms)')
1657
- plt1.set_ylabel('Amplitude (µV)')
2033
+ plt1.patch.set_facecolor("#2d2d2d")
2034
+ plt1.xaxis.set_label_coords(0.9, 0)
2035
+
2036
+ if CV == "Avg":
2037
+ plt1.plot(avg_waveform_avg[:, UnitA], "g", label=f"Unit A ({UnitA})")
2038
+ plt1.plot(avg_waveform_avg[:, UnitB], "b", label=f"Unit B ({UnitB})")
2039
+ plt1.set_xlabel("Time (ms)")
2040
+ plt1.set_ylabel("Amplitude (µV)")
1658
2041
  # plt1.set_xlim(left = 0)
1659
2042
  # plt1.set_xticks([])
1660
2043
 
1661
2044
  else:
1662
- plt1.plot(avg_waveform[:,UnitA,CV[0]], 'g', label=f'Unit A ({UnitA})')
1663
- plt1.plot(avg_waveform[:,UnitB,CV[1]], 'b', label=f'Unit B ({UnitB})')
1664
- plt1.set_xlabel('Time (ms)')
1665
- plt1.set_ylabel('Amplitude (µV)')
2045
+ plt1.plot(avg_waveform[:, UnitA, CV[0]], "g", label=f"Unit A ({UnitA})")
2046
+ plt1.plot(avg_waveform[:, UnitB, CV[1]], "b", label=f"Unit B ({UnitB})")
2047
+ plt1.set_xlabel("Time (ms)")
2048
+ plt1.set_ylabel("Amplitude (µV)")
1666
2049
  # plt1.set_xlim(left = 0)
1667
2050
 
1668
- avg_waveform_plot = FigureCanvasTkAgg(fig, master = root)
2051
+ avg_waveform_plot = FigureCanvasTkAgg(fig, master=root)
1669
2052
  avg_waveform_plot.draw()
1670
2053
  avg_waveform_plot = avg_waveform_plot.get_tk_widget()
1671
- avg_waveform_plot.grid(row = 3, column = 0)
2054
+ avg_waveform_plot.grid(row=3, column=0)
2055
+
1672
2056
 
1673
2057
  def plot_trajectories(UnitA, UnitB, CV):
1674
2058
  global trajectory_plot
1675
2059
  if trajectory_plot.winfo_exists() == 1:
1676
2060
  trajectory_plot.destroy()
1677
2061
 
1678
- fig = Figure(figsize = (3,3),
1679
- dpi = 100)
1680
- fig.patch.set_facecolor('#33393b')
2062
+ fig = Figure(figsize=(3, 3), dpi=100)
2063
+ fig.patch.set_facecolor("#33393b")
1681
2064
 
1682
-
1683
2065
  plt2 = fig.add_subplot(111)
1684
- plt2.patch.set_facecolor('#2d2d2d')
2066
+ plt2.patch.set_facecolor("#2d2d2d")
1685
2067
  plt2.set_aspect(0.5)
1686
- plt2.spines[['right', 'top']].set_visible(False)
1687
-
2068
+ plt2.spines[["right", "top"]].set_visible(False)
1688
2069
 
1689
- if CV =='Avg':
1690
-
2070
+ if CV == "Avg":
1691
2071
  # AM not doing a time averaged WaveIDX (where you fins goodtimepoints), will just uses CV 0 for both
1692
- plt2.plot(avg_waveform_per_tp_avg[1,UnitA,wave_idx[UnitA,:,0].astype(bool)], avg_waveform_per_tp_avg[2,UnitA,wave_idx[UnitA,:,0].astype(bool)], 'g', label=f'Unit A ({UnitA})')
1693
- plt2.scatter(avg_centroid_avg[1,UnitA], avg_centroid_avg[2,UnitA], c = 'g')
1694
-
1695
- plt2.plot(avg_waveform_per_tp_avg[1,UnitB,wave_idx[UnitB,:,0].astype(bool)], avg_waveform_per_tp_avg[2,UnitB,wave_idx[UnitB,:,0].astype(bool)],'b', label=f'Unit B ({UnitB})')
1696
- plt2.scatter(avg_centroid_avg[1,UnitB], avg_centroid_avg[2,UnitB], c = 'b')
1697
-
1698
- plt2.set_xlabel(r'X position ($\mu$m)')
1699
- plt2.set_ylabel(r'Y position ($\mu$m)')
2072
+ plt2.plot(
2073
+ avg_waveform_per_tp_avg[1, UnitA, wave_idx[UnitA, :, 0].astype(bool)],
2074
+ avg_waveform_per_tp_avg[2, UnitA, wave_idx[UnitA, :, 0].astype(bool)],
2075
+ "g",
2076
+ label=f"Unit A ({UnitA})",
2077
+ )
2078
+ plt2.scatter(avg_centroid_avg[1, UnitA], avg_centroid_avg[2, UnitA], c="g")
2079
+
2080
+ plt2.plot(
2081
+ avg_waveform_per_tp_avg[1, UnitB, wave_idx[UnitB, :, 0].astype(bool)],
2082
+ avg_waveform_per_tp_avg[2, UnitB, wave_idx[UnitB, :, 0].astype(bool)],
2083
+ "b",
2084
+ label=f"Unit B ({UnitB})",
2085
+ )
2086
+ plt2.scatter(avg_centroid_avg[1, UnitB], avg_centroid_avg[2, UnitB], c="b")
2087
+
2088
+ plt2.set_xlabel(r"X position ($\mu$m)")
2089
+ plt2.set_ylabel(r"Y position ($\mu$m)")
1700
2090
 
1701
2091
  else:
1702
- plt2.plot(avg_waveform_per_tp[1,UnitA,wave_idx[UnitA,:,CV[0]].astype(bool), CV[0]], avg_waveform_per_tp[2,UnitA,wave_idx[UnitA,:,CV[0]].astype(bool), CV[0]], 'g', label=f'Unit A ({UnitA})')
1703
- plt2.scatter(avg_centroid[1,UnitA,CV[0]], avg_centroid[2,UnitA,CV[0]], c = 'g')
1704
-
1705
- plt2.plot(avg_waveform_per_tp[1,UnitB,wave_idx[UnitB,:,CV[1]].astype(bool), CV[1]], avg_waveform_per_tp[2,UnitB,wave_idx[UnitB,:,CV[1]].astype(bool), CV[1]],'b', label=f'Unit B ({UnitB})')
1706
- plt2.scatter(avg_centroid[1,UnitB,CV[1]], avg_centroid[2,UnitB,CV[1]], c = 'b')
1707
-
1708
- plt2.set_xlabel(r'X position ($\mu$m)')
1709
- plt2.set_ylabel(r'Y position ($\mu$m)')
1710
-
1711
- trajectory_plot=FigureCanvasTkAgg(fig, master = root)
2092
+ plt2.plot(
2093
+ avg_waveform_per_tp[
2094
+ 1, UnitA, wave_idx[UnitA, :, CV[0]].astype(bool), CV[0]
2095
+ ],
2096
+ avg_waveform_per_tp[
2097
+ 2, UnitA, wave_idx[UnitA, :, CV[0]].astype(bool), CV[0]
2098
+ ],
2099
+ "g",
2100
+ label=f"Unit A ({UnitA})",
2101
+ )
2102
+ plt2.scatter(
2103
+ avg_centroid[1, UnitA, CV[0]], avg_centroid[2, UnitA, CV[0]], c="g"
2104
+ )
2105
+
2106
+ plt2.plot(
2107
+ avg_waveform_per_tp[
2108
+ 1, UnitB, wave_idx[UnitB, :, CV[1]].astype(bool), CV[1]
2109
+ ],
2110
+ avg_waveform_per_tp[
2111
+ 2, UnitB, wave_idx[UnitB, :, CV[1]].astype(bool), CV[1]
2112
+ ],
2113
+ "b",
2114
+ label=f"Unit B ({UnitB})",
2115
+ )
2116
+ plt2.scatter(
2117
+ avg_centroid[1, UnitB, CV[1]], avg_centroid[2, UnitB, CV[1]], c="b"
2118
+ )
2119
+
2120
+ plt2.set_xlabel(r"X position ($\mu$m)")
2121
+ plt2.set_ylabel(r"Y position ($\mu$m)")
2122
+
2123
+ trajectory_plot = FigureCanvasTkAgg(fig, master=root)
1712
2124
  trajectory_plot.draw()
1713
2125
  trajectory_plot = trajectory_plot.get_tk_widget()
1714
- # TrajectoryPlot.configure(bg = '#33393b')
1715
- trajectory_plot.grid(row = 3, column = 1, columnspan = 2)
2126
+ # TrajectoryPlot.configure(bg = '#33393b')
2127
+ trajectory_plot.grid(row=3, column=1, columnspan=2)
2128
+
1716
2129
 
1717
2130
  def order_good_sites(good_sites, channel_pos, n_sessions):
1718
2131
  # make it so it goes from biggest to smallest
1719
- reordered_idx = np.argsort(-channel_pos[n_sessions][good_sites,2].squeeze())
2132
+ reordered_idx = np.argsort(-channel_pos[n_sessions][good_sites, 2].squeeze())
1720
2133
  reordered_good_sites = good_sites[reordered_idx]
1721
2134
 
1722
- #re-arange x-axis so it goes (smaller x, bigger x)
1723
- for i in range(9):
1724
- a,b = channel_pos[n_sessions][reordered_good_sites[[2*i, 2*i+1]],1]
2135
+ # re-arange x-axis so it goes (smaller x, bigger x)
2136
+ for i in range(len(reordered_good_sites) // 2):
2137
+ a, b = channel_pos[n_sessions][reordered_good_sites[[2 * i, 2 * i + 1]], 1]
1725
2138
 
1726
2139
  if a > b:
1727
- #swap order
1728
- reordered_good_sites[[2*i + 1, 2*i]] = reordered_good_sites[[2*i, 2*i+1]]
2140
+ # swap order
2141
+ reordered_good_sites[[2 * i + 1, 2 * i]] = reordered_good_sites[
2142
+ [2 * i, 2 * i + 1]
2143
+ ]
1729
2144
  return reordered_good_sites
1730
2145
 
2146
+
1731
2147
  def nearest_channels(max_site, max_site_mean, channel_pos, clus_info, unit, CV):
1732
2148
 
1733
- n_sessions = clus_info['session_id'][unit]
1734
- if CV == 'Avg':
2149
+ n_sessions = clus_info["session_id"][unit]
2150
+ if CV == "Avg":
1735
2151
  maxsite = max_site_mean[unit].squeeze()
1736
- __, x, y = channel_pos[n_sessions][maxsite,:]
1737
-
1738
- good_x_sites = np.argwhere( np.logical_and((x-50 < channel_pos[n_sessions][:,1]) == True, (channel_pos[n_sessions][:,1] < x+50) == True))
1739
- y_values = channel_pos[n_sessions][good_x_sites,2]
1740
-
1741
- y_dist_to_max_site = np.abs(y_values - channel_pos[n_sessions][maxsite,2])
1742
- good_sites = np.argsort(y_dist_to_max_site,axis = 0 )[:18]
2152
+ __, x, y = channel_pos[n_sessions][maxsite, :]
2153
+
2154
+ good_x_sites = np.argwhere(
2155
+ np.logical_and(
2156
+ (x - 50 < channel_pos[n_sessions][:, 1]) == True,
2157
+ (channel_pos[n_sessions][:, 1] < x + 50) == True,
2158
+ )
2159
+ )
2160
+ y_values = channel_pos[n_sessions][good_x_sites, 2]
2161
+
2162
+ y_dist_to_max_site = np.abs(y_values - channel_pos[n_sessions][maxsite, 2])
2163
+ good_sites = np.argsort(y_dist_to_max_site, axis=0)[:18]
1743
2164
  good_sites = good_x_sites[good_sites]
1744
2165
  reordered_good_sites = order_good_sites(good_sites, channel_pos, n_sessions)
1745
2166
 
1746
2167
  else:
1747
- maxsite = max_site[unit,CV]
1748
- __, x, y = channel_pos[n_sessions][maxsite,:]
1749
-
1750
- good_x_sites = np.argwhere( np.logical_and((x-50 < channel_pos[n_sessions][:,1]) == True, (channel_pos[n_sessions][:,1] < x+50) == True))
1751
- y_values = channel_pos[n_sessions][good_x_sites,2]
1752
-
1753
- y_dist_to_max_site = np.abs(y_values - channel_pos[n_sessions][maxsite,2])
1754
- good_sites = np.argsort(y_dist_to_max_site,axis = 0 )[:18]
2168
+ maxsite = max_site[unit, CV]
2169
+ __, x, y = channel_pos[n_sessions][maxsite, :]
2170
+
2171
+ good_x_sites = np.argwhere(
2172
+ np.logical_and(
2173
+ (x - 50 < channel_pos[n_sessions][:, 1]) == True,
2174
+ (channel_pos[n_sessions][:, 1] < x + 50) == True,
2175
+ )
2176
+ )
2177
+ y_values = channel_pos[n_sessions][good_x_sites, 2]
2178
+
2179
+ y_dist_to_max_site = np.abs(y_values - channel_pos[n_sessions][maxsite, 2])
2180
+ good_sites = np.argsort(y_dist_to_max_site, axis=0)[:18]
1755
2181
  good_sites = good_x_sites[good_sites]
1756
2182
  reordered_good_sites = order_good_sites(good_sites, channel_pos, n_sessions)
1757
-
2183
+
1758
2184
  return reordered_good_sites
1759
2185
 
2186
+
1760
2187
  def plot_raw_waveforms(unit_a, unit_b, CV):
1761
2188
 
1762
- session_no_a = clus_info['session_id'][unit_a]
2189
+ session_no_a = clus_info["session_id"][unit_a]
1763
2190
  global raw_waveform_plot
1764
2191
  if raw_waveform_plot.winfo_exists() == 1:
1765
2192
  raw_waveform_plot.destroy()
1766
2193
 
1767
- fig = Figure(figsize=(4,6), dpi = 100)
2194
+ fig = Figure(figsize=(4, 6), dpi=100)
1768
2195
  fig.set_tight_layout(False)
1769
- fig.patch.set_facecolor('#33393b')
2196
+ fig.patch.set_facecolor("#33393b")
1770
2197
 
1771
- main_ax = fig.add_axes([0.2,0.2,0.8,0.8])
1772
- main_ax.set_facecolor('#2d2d2d')
2198
+ main_ax = fig.add_axes([0.2, 0.2, 0.8, 0.8])
2199
+ main_ax.set_facecolor("#2d2d2d")
1773
2200
  main_ax_offset = 0.2
1774
2201
  main_ax_scale = 0.8
1775
2202
 
1776
- if CV =='Avg':
1777
- good_channels = nearest_channels(max_site, max_site_mean, channel_pos, clus_info, unit_a, CV)
2203
+ if CV == "Avg":
2204
+ good_channels = nearest_channels(
2205
+ max_site, max_site_mean, channel_pos, clus_info, unit_a, CV
2206
+ )
1778
2207
 
1779
- min_x, min_y = channel_pos[session_no_a][good_channels[-2],[1,2]].squeeze()
1780
- max_x, maxy = channel_pos[session_no_a][good_channels[1],[1,2]].squeeze()
2208
+ min_x, min_y = channel_pos[session_no_a][good_channels[-2], [1, 2]].squeeze()
2209
+ max_x, maxy = channel_pos[session_no_a][good_channels[1], [1, 2]].squeeze()
1781
2210
  delta_x = (max_x - min_x) / 2
1782
2211
  delta_y = (maxy - min_y) / 18
1783
2212
 
1784
- #may want to change so it find this for both units and selects the most extreme arguments
1785
- #however i dont think tis will be necessary
1786
- sub_min_y = np.nanmin(waveform[unit_a,:,good_channels].mean(axis=-1))
1787
- sub_max_y = np.nanmax(waveform[unit_a,:,good_channels].mean(axis=-1))
2213
+ # may want to change so it find this for both units and selects the most extreme arguments
2214
+ # however i dont think tis will be necessary
2215
+ sub_min_y = np.nanmin(waveform[unit_a, :, good_channels].mean(axis=-1))
2216
+ sub_max_y = np.nanmax(waveform[unit_a, :, good_channels].mean(axis=-1))
1788
2217
  # shift each waveform so 0 is at the channel site, 1/9 is width of a y waveform plot
1789
- waveform_y_offset = (np.abs(sub_max_y) / (np.abs(sub_min_y) + np.abs(sub_max_y)) ) * 1/9
1790
-
2218
+ waveform_y_offset = (
2219
+ (np.abs(sub_max_y) / (np.abs(sub_min_y) + np.abs(sub_max_y))) * 1 / 9
2220
+ )
2221
+
1791
2222
  else:
1792
- good_channels = nearest_channels(max_site, max_site_mean, channel_pos, clus_info, unit_a, CV[0])
2223
+ good_channels = nearest_channels(
2224
+ max_site, max_site_mean, channel_pos, clus_info, unit_a, CV[0]
2225
+ )
1793
2226
 
1794
- min_x, min_y = channel_pos[session_no_a][good_channels[-2],[1,2]].squeeze()
1795
- max_x, maxy = channel_pos[session_no_a][good_channels[1],[1,2]].squeeze()
2227
+ min_x, min_y = channel_pos[session_no_a][good_channels[-2], [1, 2]].squeeze()
2228
+ max_x, maxy = channel_pos[session_no_a][good_channels[1], [1, 2]].squeeze()
1796
2229
  delta_x = (max_x - min_x) / 2
1797
2230
  delta_y = (maxy - min_y) / 18
1798
- #may want to change so it find this for both units and selects the most extreme arguments
1799
- #however i dont think this will be necessary
1800
- sub_min_y = np.nanmin(waveform[unit_a,:,good_channels, CV[0]])
1801
- sub_max_y = np.nanmax(waveform[unit_a,:,good_channels, CV[0]])
2231
+ # may want to change so it find this for both units and selects the most extreme arguments
2232
+ # however i dont think this will be necessary
2233
+ sub_min_y = np.nanmin(waveform[unit_a, :, good_channels, CV[0]])
2234
+ sub_max_y = np.nanmax(waveform[unit_a, :, good_channels, CV[0]])
1802
2235
  # shift each waveform so 0 is at the channel site, 1/9 is width of a y waveform plot
1803
- waveform_y_offset = (np.abs(sub_max_y) / (np.abs(sub_min_y) + np.abs(sub_max_y)) ) * 1/9
1804
-
1805
-
1806
- #make the main scatter positiose site as scatter with opacity
1807
- main_ax.scatter(channel_pos[session_no_a][good_channels,1], channel_pos[session_no_a][good_channels,2], c = 'grey', alpha = 0.3)
2236
+ waveform_y_offset = (
2237
+ (np.abs(sub_max_y) / (np.abs(sub_min_y) + np.abs(sub_max_y))) * 1 / 9
2238
+ )
2239
+
2240
+ # make the main scatter positiose site as scatter with opacity
2241
+ main_ax.scatter(
2242
+ channel_pos[session_no_a][good_channels, 1],
2243
+ channel_pos[session_no_a][good_channels, 2],
2244
+ c="grey",
2245
+ alpha=0.3,
2246
+ )
1808
2247
  main_ax.set_xlim(min_x - delta_x, max_x + delta_x)
1809
2248
  main_ax.set_ylim(min_y - delta_y, maxy + delta_y)
1810
2249
 
1811
2250
  for i in range(9):
1812
2251
  for j in range(2):
1813
- #may need to change this positioning if units sizes are irregular
2252
+ # may need to change this positioning if units sizes are irregular
1814
2253
  if j == 0:
1815
- #The peak in the waveform is not half way, so maths says the x axis should be starting at
1816
- #0.1 and 0.6 so the middle is at 0.25/0.76 however chosen these values so it loks better by eye
2254
+ # The peak in the waveform is not half way, so maths says the x axis should be starting at
2255
+ # 0.1 and 0.6 so the middle is at 0.25/0.76 however chosen these values so it loks better by eye
1817
2256
 
1818
2257
  #
1819
- ax = fig.add_axes([main_ax_offset + main_ax_scale*0.25, main_ax_offset + main_ax_scale*(i/9 - 1/18 + waveform_y_offset), main_ax_scale*0.25, main_ax_scale*1/9])
2258
+ ax = fig.add_axes(
2259
+ [
2260
+ main_ax_offset + main_ax_scale * 0.25,
2261
+ main_ax_offset
2262
+ + main_ax_scale * (i / 9 - 1 / 18 + waveform_y_offset),
2263
+ main_ax_scale * 0.25,
2264
+ main_ax_scale * 1 / 9,
2265
+ ]
2266
+ )
1820
2267
  if j == 1:
1821
- ax = fig.add_axes([main_ax_offset + main_ax_scale*0.75, main_ax_offset + main_ax_scale*(i/9 - 1/18 + waveform_y_offset), main_ax_scale*0.25, main_ax_scale*1/9])
1822
-
1823
- if CV =='Avg':
1824
- ax.plot(waveform[unit_a,:,good_channels[i*2 + j]].mean(axis=-1).squeeze(), color = 'g')
1825
- ax.plot(waveform[unit_b,:,good_channels[i*2 + j]].mean(axis = -1).squeeze(), color = 'b', lw=0.8)
2268
+ ax = fig.add_axes(
2269
+ [
2270
+ main_ax_offset + main_ax_scale * 0.75,
2271
+ main_ax_offset
2272
+ + main_ax_scale * (i / 9 - 1 / 18 + waveform_y_offset),
2273
+ main_ax_scale * 0.25,
2274
+ main_ax_scale * 1 / 9,
2275
+ ]
2276
+ )
2277
+
2278
+ if CV == "Avg":
2279
+ ax.plot(
2280
+ waveform[unit_a, :, good_channels[i * 2 + j]]
2281
+ .mean(axis=-1)
2282
+ .squeeze(),
2283
+ color="g",
2284
+ )
2285
+ ax.plot(
2286
+ waveform[unit_b, :, good_channels[i * 2 + j]]
2287
+ .mean(axis=-1)
2288
+ .squeeze(),
2289
+ color="b",
2290
+ lw=0.8,
2291
+ )
1826
2292
  else:
1827
- ax.plot(waveform[unit_a,:,good_channels[i*2 + j], CV[0]].squeeze(), color = 'g')
1828
- ax.plot(waveform[unit_b,:,good_channels[i*2 + j],CV[1]].squeeze(), color = 'b', lw=0.8)
1829
- ax.set_ylim(sub_min_y,sub_max_y)
2293
+ ax.plot(
2294
+ waveform[unit_a, :, good_channels[i * 2 + j], CV[0]].squeeze(),
2295
+ color="g",
2296
+ )
2297
+ ax.plot(
2298
+ waveform[unit_b, :, good_channels[i * 2 + j], CV[1]].squeeze(),
2299
+ color="b",
2300
+ lw=0.8,
2301
+ )
2302
+ ax.set_ylim(sub_min_y, sub_max_y)
1830
2303
  ax.set_axis_off()
1831
2304
 
1832
-
1833
2305
  main_ax.spines.right.set_visible(False)
1834
2306
  main_ax.spines.top.set_visible(False)
1835
2307
  main_ax.set_xticks([min_x, max_x])
1836
- main_ax.set_xlabel('X position ($\mu$m)', size = 14)
1837
- main_ax.set_ylabel('Y position ($\mu$m)', size = 14)
1838
-
1839
-
2308
+ main_ax.set_xlabel("X position ($\mu$m)", size=14)
2309
+ main_ax.set_ylabel("Y position ($\mu$m)", size=14)
1840
2310
 
1841
- raw_waveform_plot = FigureCanvasTkAgg(fig, master = root)
2311
+ raw_waveform_plot = FigureCanvasTkAgg(fig, master=root)
1842
2312
  raw_waveform_plot.draw()
1843
2313
  raw_waveform_plot = raw_waveform_plot.get_tk_widget()
1844
- #RawWaveformPlot.configure(bg = '#33393b')
2314
+ # RawWaveformPlot.configure(bg = '#33393b')
2315
+
2316
+ raw_waveform_plot.grid(
2317
+ row=3, column=4, columnspan=2, rowspan=4, padx=15, pady=25, ipadx=15
2318
+ )
1845
2319
 
1846
- raw_waveform_plot.grid(row = 3, column = 4, columnspan = 2, rowspan = 4, padx = 15, pady = 25, ipadx = 15)
1847
2320
 
1848
2321
  def plot_histograms(hist_names, hist, hist_matched, scores_to_include, unit_a, unit_b):
1849
2322
 
@@ -1851,42 +2324,54 @@ def plot_histograms(hist_names, hist, hist_matched, scores_to_include, unit_a, u
1851
2324
  if hist_plot.winfo_exists() == 1:
1852
2325
  hist_plot.destroy()
1853
2326
 
1854
- fig = Figure(figsize= (4,6), dpi = 100, layout = 'constrained')
1855
- fig.patch.set_facecolor('#33393b')
1856
- axs = fig.subplots(3,2, sharex='col')
2327
+ fig = Figure(figsize=(4, 6), dpi=100, layout="constrained")
2328
+ fig.patch.set_facecolor("#33393b")
2329
+ axs = fig.subplots(3, 2, sharex="col")
1857
2330
  axs = axs.flat
1858
2331
 
1859
-
1860
2332
  # Create title mapping
1861
2333
  title_mapping = {
1862
- 'amp_score': 'Amplitude score',
1863
- 'spatial_decay_score': 'Spatial decay score',
1864
- 'centroid_overlord_score': "C'oid overlord score",
1865
- 'centroid_dist': "C'oid distance score",
1866
- 'waveform_score': 'Waveform score',
1867
- 'trajectory_score': 'Trajectory score'
2334
+ "amp_score": "Amplitude score",
2335
+ "spatial_decay_score": "Spatial decay score",
2336
+ "centroid_overlord_score": "C'oid overlord score",
2337
+ "centroid_dist": "C'oid distance score",
2338
+ "waveform_score": "Waveform score",
2339
+ "trajectory_score": "Trajectory score",
1868
2340
  }
1869
-
1870
- #loop over indexes..
2341
+
2342
+ # loop over indexes..
1871
2343
  for i in range(len(hist)):
1872
- axs[i].step(hist[i][1][:-1], hist[i][0], color = 'orange', label='All scores' if i == 0 else "")
1873
- axs[i].step(hist_matched[i][1][:-1], hist_matched[i][0], color = 'magenta', label='Expected matches' if i == 0 else "")
2344
+ axs[i].step(
2345
+ hist[i][1][:-1],
2346
+ hist[i][0],
2347
+ color="orange",
2348
+ label="All scores" if i == 0 else "",
2349
+ )
2350
+ axs[i].step(
2351
+ hist_matched[i][1][:-1],
2352
+ hist_matched[i][0],
2353
+ color="magenta",
2354
+ label="Expected matches" if i == 0 else "",
2355
+ )
1874
2356
  axs[i].set_ylim(bottom=0)
1875
-
2357
+
1876
2358
  # Use improved title from mapping
1877
2359
  plot_title = title_mapping.get(hist_names[i], hist_names[i])
1878
- axs[i].set_title(plot_title, fontsize = 12)
1879
-
2360
+ axs[i].set_title(plot_title, fontsize=12)
2361
+
1880
2362
  # Add ylabel
1881
- axs[i].set_ylabel('% units', fontsize=10)
1882
-
1883
- axs[i].axvline(scores_to_include[hist_names[i]][unit_a,unit_b], ls = '--', color = 'white', label='Current match pair' if i == 0 else "")
1884
- axs[i].set_facecolor('#2d2d2d')
1885
-
2363
+ axs[i].set_ylabel("% units", fontsize=10)
2364
+
2365
+ axs[i].axvline(
2366
+ scores_to_include[hist_names[i]][unit_a, unit_b],
2367
+ ls="--",
2368
+ color="white",
2369
+ label="Current match pair" if i == 0 else "",
2370
+ )
2371
+ axs[i].set_facecolor("#2d2d2d")
1886
2372
 
1887
- hist_plot = FigureCanvasTkAgg(fig, master = root)
2373
+ hist_plot = FigureCanvasTkAgg(fig, master=root)
1888
2374
  hist_plot.draw()
1889
2375
  hist_plot = hist_plot.get_tk_widget()
1890
2376
 
1891
- hist_plot.grid(row = 3, column = 6, columnspan = 2, rowspan = 4, padx = 5, pady = 20)
1892
-
2377
+ hist_plot.grid(row=3, column=6, columnspan=2, rowspan=4, padx=5, pady=20)