PyATCLI 2026.10.10__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.
Files changed (71) hide show
  1. PyATCLI/__init__.py +196 -0
  2. PyATCLI/__main__.py +7 -0
  3. PyATCLI/_version.py +47 -0
  4. PyATCLI/analyses.py +640 -0
  5. PyATCLI/analysis/__init__.py +81 -0
  6. PyATCLI/analysis/auc.py +79 -0
  7. PyATCLI/analysis/curve_fit.py +88 -0
  8. PyATCLI/analysis/event_peth.py +263 -0
  9. PyATCLI/analysis/fft.py +99 -0
  10. PyATCLI/analysis/group/__init__.py +318 -0
  11. PyATCLI/analysis/group/rebuild.py +59 -0
  12. PyATCLI/analysis/group/report.py +281 -0
  13. PyATCLI/analysis/group/run.py +164 -0
  14. PyATCLI/analysis/group/scan.py +92 -0
  15. PyATCLI/analysis/group/stats.py +451 -0
  16. PyATCLI/analysis/group/trials.py +188 -0
  17. PyATCLI/analysis/intervals.py +59 -0
  18. PyATCLI/analysis/peak_finder.py +155 -0
  19. PyATCLI/analysis/shared.py +100 -0
  20. PyATCLI/analysis/zscore_peth.py +107 -0
  21. PyATCLI/cli/__init__.py +105 -0
  22. PyATCLI/cli/commands.py +395 -0
  23. PyATCLI/cli/docs.py +246 -0
  24. PyATCLI/cli/parser.py +286 -0
  25. PyATCLI/cli/render.py +130 -0
  26. PyATCLI/engine/__init__.py +0 -0
  27. PyATCLI/engine/contract.py +124 -0
  28. PyATCLI/engine/server.py +169 -0
  29. PyATCLI/engine/session.py +40 -0
  30. PyATCLI/engine/store.py +222 -0
  31. PyATCLI/engine/wire.py +103 -0
  32. PyATCLI/fieldstudy/__init__.py +1 -0
  33. PyATCLI/fieldstudy/study.py +440 -0
  34. PyATCLI/fieldstudy/validation.py +443 -0
  35. PyATCLI/markers.py +71 -0
  36. PyATCLI/models.py +102 -0
  37. PyATCLI/numeric.py +35 -0
  38. PyATCLI/ops/__init__.py +274 -0
  39. PyATCLI/ops/analysis.py +136 -0
  40. PyATCLI/ops/common.py +93 -0
  41. PyATCLI/ops/compute.py +94 -0
  42. PyATCLI/ops/fieldstudy.py +52 -0
  43. PyATCLI/ops/files.py +42 -0
  44. PyATCLI/ops/group.py +144 -0
  45. PyATCLI/ops/recording.py +90 -0
  46. PyATCLI/ops/records.py +63 -0
  47. PyATCLI/ops/results.py +27 -0
  48. PyATCLI/ops/saved.py +98 -0
  49. PyATCLI/ops/system.py +31 -0
  50. PyATCLI/outputs.py +165 -0
  51. PyATCLI/progress.py +227 -0
  52. PyATCLI/provenance.py +336 -0
  53. PyATCLI/recording.py +602 -0
  54. PyATCLI/reproduce.py +278 -0
  55. PyATCLI/results.py +106 -0
  56. PyATCLI/saved_state.py +275 -0
  57. PyATCLI/sources/__init__.py +1 -0
  58. PyATCLI/sources/dataset.py +110 -0
  59. PyATCLI/sources/load.py +169 -0
  60. PyATCLI/sources/processing_TDT.py +810 -0
  61. PyATCLI/sources/processing_oxysoft.py +259 -0
  62. PyATCLI/sources/pt2.py +46 -0
  63. PyATCLI/sources/tables.py +306 -0
  64. PyATCLI/splice.py +196 -0
  65. PyATCLI/viewplan.py +181 -0
  66. pyatcli-2026.10.10.dist-info/METADATA +296 -0
  67. pyatcli-2026.10.10.dist-info/RECORD +71 -0
  68. pyatcli-2026.10.10.dist-info/WHEEL +5 -0
  69. pyatcli-2026.10.10.dist-info/entry_points.txt +2 -0
  70. pyatcli-2026.10.10.dist-info/licenses/LICENSE +661 -0
  71. pyatcli-2026.10.10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,810 @@
1
+ """
2
+ sources/processing_TDT.py
3
+ -------------------------
4
+ Signal processing pipeline for TDT (Tucker-Davis Technologies) fibre photometry data.
5
+
6
+ Handles loading, bleaching correction, denoising, and event marker extraction.
7
+ Depends on the `tdt` Python SDK for reading tank files.
8
+ """
9
+
10
+ import os
11
+
12
+ import numpy as np
13
+ from sklearn.linear_model import HuberRegressor, RANSACRegressor
14
+ from scipy.optimize import curve_fit
15
+ from scipy.signal import butter, filtfilt
16
+ import tdt
17
+
18
+ from ..models import double_exponential_model as double_exponential
19
+ from ..numeric import as_float64
20
+ from ..progress import Plan
21
+ from ..splice import replay_splices
22
+
23
+ REGRESSION_METHODS = ("ransac", "huber", "ols")
24
+
25
+ # The low-pass filter every dF/F ends with (compute_dff, and denoise_signal's defaults). Named so the
26
+ # provenance record (provenance.pipeline_parameters) reports what ran rather than a copy of it.
27
+ DENOISE_CUTOFF_HZ = 5
28
+ DENOISE_ORDER = 2
29
+
30
+
31
+ def _robust_linear_fit(x, y, method="ols"):
32
+ """
33
+ Motion correction regresses the isosbestic (415 nm) stream onto the
34
+ signal (465 nm) stream. An ordinary least-squares fit (np.polyfit) lets
35
+ the exact kind of thing this regression is meant to remove (a burst of
36
+ motion artifact, a fiber-cord twist) drag the fitted line toward
37
+ itself, corrupting the motion-free prediction everywhere else in the
38
+ recording — RANSAC and Huber are two different ways of resisting that.
39
+
40
+ method : {"ransac", "huber", "ols"}
41
+ "ols" (default): plain np.polyfit — no robustness at all. Chosen
42
+ as the default over RANSAC/Huber because it never actively
43
+ discards or downweights a sample: RANSAC in particular treats
44
+ whatever it excludes as "not part of the fit" and then still
45
+ applies the fit there, which means a point it misjudges (a real,
46
+ large biological transient that merely looks unusual relative to
47
+ the rest of the recording, not an artifact) gets a distorted
48
+ correction rather than a merely-imperfect one. OLS's own
49
+ weakness — the fit line itself gets dragged toward severe
50
+ artifacts — is a known, predictable trade-off; it doesn't risk
51
+ silently mis-classifying real signal as noise. RANSAC or Huber
52
+ are still worth trying on a given recording (see the Options
53
+ dialog's regression picker) when artifacts are severe and
54
+ occasional enough that this trade-off clearly favors excluding
55
+ them.
56
+
57
+ "ransac": repeatedly fits a line to small random
58
+ subsets, keeps whichever subset gets the most other points within
59
+ residual_threshold of it (the inliers), and does one final fit on
60
+ just those inliers. Points that never look like they belong to the
61
+ same line (i.e., artifacts) are excluded from the fit entirely
62
+ rather than merely downweighted — the right choice when artifacts
63
+ are occasional and severe (a fiber-cord twist, a brief motion
64
+ burst) rather than spread continuously through the recording.
65
+
66
+ residual_threshold is set explicitly to 3x a robust noise
67
+ estimate. sklearn's own default (the MAD of y around its median)
68
+ is calibrated for roughly-flat data and comes out far too loose
69
+ here, since y's spread is dominated by the real 415-vs-465 trend
70
+ rather than noise; left at the default, RANSAC would accept every
71
+ point as an inlier and silently degrade to an ordinary
72
+ least-squares fit.
73
+
74
+ The noise estimate itself comes from the MAD of an initial
75
+ ordinary least-squares fit's residuals (not from
76
+ consecutive-sample differences, tried previously) — diff-based
77
+ noise estimation measures noise at the timescale of one sample,
78
+ which at TDT's sampling rates (~1 kHz, adjacent samples ~1ms
79
+ apart) is dominated by ADC/thermal noise far smaller than the
80
+ residual scale a real 415-vs-465 regression actually produces once
81
+ genuine biological signal (the very thing this correction is
82
+ meant to preserve, not remove) is accounted for. Confirmed on a
83
+ real recording: diff-based noise estimation set a threshold ~350x
84
+ tighter than the fit's actual residual scale, rejecting 98% of
85
+ samples as "outliers". MAD of the OLS fit's own residuals is on
86
+ the right scale by construction, and stays robust to the
87
+ artifacts it's meant to exclude — they're exactly the kind of
88
+ minority-of-points deviation MAD is insensitive to, same reasoning
89
+ as using MAD over standard deviation anywhere else here.
90
+
91
+ "huber": every point stays in the fit, but points far from the
92
+ line (beyond `epsilon` times the residual scale, sklearn's
93
+ default epsilon=1.35) get down-weighted rather than excluded —
94
+ gentler than RANSAC's hard in/out cut, better suited to noise
95
+ that's elevated throughout rather than concentrated in a few bad
96
+ stretches.
97
+
98
+ Returns
99
+ -------
100
+ (a, b, inlier_fraction) : float
101
+ Slope, intercept, and the fraction of points kept as inliers for
102
+ the final fit (1.0 = every point used). RANSAC's is a real
103
+ exclusion fraction; OLS always reports 1.0 (never excludes
104
+ anything); Huber's is 1 - the fraction its own `outliers_` mask
105
+ flags as beyond epsilon, so it stays informative despite Huber
106
+ never truly dropping a point from the fit.
107
+ """
108
+ if method not in REGRESSION_METHODS:
109
+ raise ValueError(f"Unknown regression method {method!r}; expected one of {REGRESSION_METHODS}")
110
+
111
+ # TDT streams arrive as float32, and np.polyfit on float32 data silently
112
+ # drops the slope term once the recording is long: it discards singular
113
+ # values below n * float32-eps, so as soon as n * 1.2e-7 exceeds the ratio
114
+ # of the 415 channel's spread to its mean (~200,000 samples for a channel
115
+ # of 25 +/- 1, i.e. ~3 minutes at 1 kHz) it returns a line at roughly half
116
+ # the true slope with a large intercept, with only a RankWarning. Fit in
117
+ # float64.
118
+ x = as_float64(x)
119
+ y = as_float64(y)
120
+
121
+ if method == "ols":
122
+ a, b = np.polyfit(x, y, 1)
123
+ return float(a), float(b), 1.0
124
+
125
+ if method == "huber":
126
+ # Fit on standardised data and map the line back: sklearn's optimiser
127
+ # starts from a fixed unit scale and its L2 penalty is not scale-free,
128
+ # so on data much larger than ~1 it stops after a few iterations with
129
+ # a poor line and a meaningless inlier fraction (0.2% on data x1000).
130
+ mx, my = np.median(x), np.median(y)
131
+ sx = 1.4826 * np.median(np.abs(x - mx)) or 1.0
132
+ sy = 1.4826 * np.median(np.abs(y - my)) or 1.0
133
+ model = HuberRegressor()
134
+ model.fit(((x - mx) / sx).reshape(-1, 1), (y - my) / sy)
135
+ a = float(model.coef_[0]) * sy / sx
136
+ b = my + sy * float(model.intercept_) - a * mx
137
+ inlier_fraction = float(np.mean(~model.outliers_))
138
+ return a, b, inlier_fraction
139
+
140
+ ols_coeffs = np.polyfit(x, y, 1)
141
+ ols_resid = y - np.polyval(ols_coeffs, x)
142
+ # 0.6745 maps MAD to a Gaussian standard deviation.
143
+ noise_est = np.median(np.abs(ols_resid - np.median(ols_resid))) / 0.6745
144
+
145
+ # Set the threshold to 3x the robust noise estimate (equivalent to a 3-sigma bound)
146
+ model = RANSACRegressor(residual_threshold=3 * noise_est, random_state=0)
147
+ model.fit(x.reshape(-1, 1), y)
148
+
149
+ # Coerce to float to unpack single-element arrays safely
150
+ a = float(model.estimator_.coef_[0])
151
+ b = float(model.estimator_.intercept_)
152
+ inlier_fraction = float(np.mean(model.inlier_mask_))
153
+
154
+ return a, b, inlier_fraction
155
+
156
+
157
+ def validate_tdt_folder(path):
158
+ """
159
+ Validate whether a directory contains a TDT recording block.
160
+
161
+ Parameters
162
+ ----------
163
+ path : str
164
+ Path to the TDT data folder.
165
+
166
+ Returns
167
+ -------
168
+ tuple
169
+ (bool, str)
170
+ - True + folder name if valid
171
+ - False + error message if invalid
172
+ """
173
+ if not path:
174
+ return False, "No folder selected."
175
+
176
+ has_tbk = any(fname.endswith('.Tbk') for fname in os.listdir(path))
177
+
178
+ if has_tbk:
179
+ return True, os.path.basename(path)
180
+ else:
181
+ return False, "Invalid Folder: No TDT block files (.Tbk) found."
182
+
183
+
184
+ def compute_dff(y_465, y_415, fs, regression_method="ols", progress=None):
185
+ """
186
+ The actual motion-correction + bleaching-correction + ΔF/F + denoise
187
+ pipeline (steps 3-6 of process_tdt_folder's docstring), factored out
188
+ so it can be re-run on a signal that isn't a fresh TDT load — namely
189
+ Splice's "Cut out this range": removing an artifact and re-running
190
+ this on the stitched remainder can give a genuinely better motion
191
+ correction (the artifact is gone from what the regression fits
192
+ against), not just a shorter view of the original fit. See
193
+ physicsanalysis_qt's analysis/splice.py for that caller.
194
+
195
+ Parameters
196
+ ----------
197
+ y_465 : array
198
+ Main driver (signal) fluorescence.
199
+ y_415 : array or None
200
+ Isosbestic (control) fluorescence, same length as y_465. None
201
+ skips motion correction entirely (single-channel recording).
202
+ fs : float
203
+ Sampling rate, for correct_bleaching/denoise_signal.
204
+ regression_method : {"ransac", "huber", "ols"}
205
+ See _robust_linear_fit.
206
+ progress : None, True or callable(fraction, message)
207
+ Progress reporting; see PyATCLI.progress. The photobleaching
208
+ fit dominates the run time (a single scipy call with no steps to
209
+ tick), so it shows as one long stage.
210
+
211
+ Returns
212
+ -------
213
+ dict with raw (motion-corrected fluorescence: with a 415 stream, the 465
214
+ minus its isosbestic-predicted motion component, i.e. ΔF in the
215
+ recording's own units), corr/dff (denoised ΔF/F), f0 (baseline
216
+ fluorescence, the photobleaching trend of the 465 stream — the
217
+ denominator of ΔF/F), motion_correction_inlier_fraction (None if y_415
218
+ is None) — the same subset of process_tdt_folder's own return dict that
219
+ actually depends on this computation.
220
+ """
221
+ # ΔF/F is (F - F0) / F0 with F0 the baseline FLUORESCENCE. With a 415
222
+ # stream, the motion-corrected residual (465 minus its isosbestic-
223
+ # predicted motion component) already IS F - F0, so it is divided by the
224
+ # 465's own bleaching baseline. (Running correct_bleaching on the
225
+ # residual itself and normalising by that, as this function used to,
226
+ # divides by a near-zero number and gives a value that isn't a ΔF/F —
227
+ # its scale and offset changed by orders of magnitude with the choice of
228
+ # regression method.) Without a 415 stream there is no motion term to
229
+ # remove, so the trace's own trend is F0.
230
+ #
231
+ # Everything is done in float64: TDT hands over float32, and the fit (see
232
+ # _robust_linear_fit) is not safe in single precision.
233
+ y_465 = as_float64(y_465)
234
+ # Weights are roughly the measured share of the run time: on a 17-minute
235
+ # 1 kHz recording the bleaching fit is ~70-90% of it, the regression 2-20%
236
+ # depending on the method, the filtering almost nothing.
237
+ stages = [("Fitting motion correction", 10)] if y_415 is not None else []
238
+ plan = Plan(progress, stages + [("Fitting photobleaching baseline", 83),
239
+ ("Normalising and filtering", 7)])
240
+ if y_415 is not None:
241
+ y_415 = as_float64(y_415)
242
+ plan.begin("Fitting motion correction")
243
+ a, b, inlier_fraction = _robust_linear_fit(y_415, y_465, method=regression_method)
244
+ y_fit = a * y_415 + b
245
+ y_final = y_465 - y_fit
246
+ plan.begin("Fitting photobleaching baseline")
247
+ _, trend = correct_bleaching(y_465, fs)
248
+ f0 = np.maximum(trend, 1e-6)
249
+ plan.begin("Normalising and filtering")
250
+ dff = y_final / f0
251
+ else:
252
+ y_final = y_465
253
+ inlier_fraction = None
254
+ plan.begin("Fitting photobleaching baseline")
255
+ _, trend = correct_bleaching(y_final, fs)
256
+ f0 = np.maximum(trend, 1e-6)
257
+ plan.begin("Normalising and filtering")
258
+ dff = (y_final - f0) / f0
259
+
260
+ dff = denoise_signal(dff, fs, cutoff=DENOISE_CUTOFF_HZ, order=DENOISE_ORDER)
261
+ plan.done()
262
+
263
+ return {
264
+ "raw": y_final,
265
+ "corr": dff,
266
+ "dff": dff,
267
+ "f0": f0,
268
+ "motion_correction_inlier_fraction": inlier_fraction,
269
+ }
270
+
271
+
272
+ def process_tdt_folder(folder_path, regression_method="ols", progress=None):
273
+ """
274
+ Full photometry processing pipeline for a TDT recording.
275
+
276
+ Steps:
277
+ 1. Load TDT block
278
+ 2. Extract 465 nm (signal) and optional 415 nm (reference)
279
+ 3. Perform regression-based motion correction
280
+ 4. Correct photobleaching trend
281
+ 5. Compute ΔF/F
282
+ 6. Denoise signal
283
+ 7. Extract event markers
284
+
285
+ Parameters
286
+ ----------
287
+ folder_path : str
288
+ Path to TDT recording folder.
289
+ regression_method : {"ransac", "huber", "ols"}
290
+ Which linear regression the isosbestic-onto-signal motion
291
+ correction (step 3) uses — see _robust_linear_fit's own docstring
292
+ for what each one actually does. Defaults to "ols", the plain
293
+ non-robust baseline — see _robust_linear_fit for why that's the
294
+ safer default over RANSAC/Huber despite being the least
295
+ artifact-resistant of the three.
296
+ progress : None, True or callable(fraction, message)
297
+ Progress reporting (see PyATCLI.progress): True draws a tqdm
298
+ bar on the console; a callable receives (fraction 0-1, message) as
299
+ the recording is read, motion/bleaching-corrected and its markers
300
+ extracted.
301
+
302
+ Returns
303
+ -------
304
+ dict
305
+ Processed signals and metadata:
306
+ - x: time vector
307
+ - raw: corrected fluorescence signal
308
+ - corr: final ΔF/F (denoised)
309
+ - dff: same as corr (alias)
310
+ - f0: bleaching baseline
311
+ - fs: sampling frequency
312
+ - store: signal label
313
+ - markers: behavioral event markers
314
+ - channels: list of {"key", "label", "y"} for each raw
315
+ per-wavelength stream found (always "main_driver"; "isosbestic"
316
+ too if a 415 reference stream exists) — the un-motion-corrected,
317
+ un-normalized traces, for a caller that wants to plot/analyze
318
+ one of them directly instead of only "raw"/"corr" above
319
+ - motion_correction_inlier_fraction: fraction (0-1) of samples
320
+ kept as inliers during motion correction (see
321
+ _robust_linear_fit for what this means per regression_method),
322
+ or None if there was no 415 reference stream to correct against
323
+ """
324
+ # Weights follow where the time goes (measured on a 17-minute, 1 kHz recording:
325
+ # ~35% reading the block, ~64% fitting/normalising, the marker extraction ~0).
326
+ plan = Plan(progress, [("Reading recording", 35), ("Computing dF/F", 64), ("Extracting markers", 1)])
327
+ data_struct = get_tdt_struct(folder_path, progress=plan.sub("Reading recording"))
328
+ streams = data_struct.streams.keys()
329
+
330
+ name_465 = next((s for s in streams if '465' in s), None)
331
+ name_415 = next((s for s in streams if '415' in s), None)
332
+
333
+ if not name_465:
334
+ raise ValueError("No 465 signal found")
335
+
336
+ x, y_465, fs = get_plot_data(data_struct, name_465)
337
+
338
+ y_415 = None
339
+ if name_415:
340
+ _, y_415, _ = get_plot_data(data_struct, name_415)
341
+ display_name = (f"Corrected {name_465} (via {name_415})" if name_415
342
+ else f"{name_465} (Uncorrected)")
343
+
344
+ computed = compute_dff(y_465, y_415, fs, regression_method=regression_method,
345
+ progress=plan.sub("Computing dF/F"))
346
+ y_final = computed["raw"]
347
+ dff = computed["corr"]
348
+ f0 = computed["f0"]
349
+ inlier_fraction = computed["motion_correction_inlier_fraction"]
350
+
351
+ # Raw per-wavelength channels, for callers that want to plot/analyze
352
+ # the main driver (probe) or isosbestic (control) trace on its own
353
+ # instead of only the motion-corrected/normalized result above.
354
+ # Nothing about stream naming or count is hardcoded beyond the 465/415
355
+ # detection already done above — a block with no 415 reference simply
356
+ # has no 'isosbestic' entry, so this works for any experimental setup
357
+ # this function already supports.
358
+ channels = [
359
+ {"key": "main_driver", "label": f"Main Driver ({name_465})", "y": y_465},
360
+ ]
361
+ if name_415:
362
+ channels.append({"key": "isosbestic", "label": f"Isosbestic ({name_415})", "y": y_415})
363
+
364
+ plan.begin("Extracting markers")
365
+ markers = get_event_markers(data_struct)
366
+ plan.done()
367
+
368
+ return {
369
+ "x": x,
370
+ "raw": y_final,
371
+ "corr": dff,
372
+ "dff": dff,
373
+ "f0": f0,
374
+ "fs": fs,
375
+ "store": display_name,
376
+ "markers": markers,
377
+ "channels": channels,
378
+ "motion_correction_inlier_fraction": inlier_fraction,
379
+ }
380
+
381
+
382
+ def get_tdt_struct(path, progress=None, read_streams=True):
383
+ """
384
+ Load a Tucker-Davis Technologies (TDT) recording block.
385
+
386
+ Streams and scalars are read in a single call (unaffected by the issue
387
+ below). Epoc stores are auto-discovered from the block's own headers
388
+ and then read ONE STORE AT A TIME, each with its own fresh
389
+ tdt.read_block() call:
390
+
391
+ - The `tdt` SDK has a bug where reading multiple epoc stores together
392
+ breaks if any store has a mismatched onset/offset count (e.g. a
393
+ strobe/epoch that was still active when the recording was stopped —
394
+ a completely normal way for a session to end). Reading one store per
395
+ call sidesteps it; a store that still fails to a genuine data issue
396
+ is skipped with a warning rather than crashing the entire load.
397
+ - Store names must come from each store's own `.name` attribute, not
398
+ the header dict's key — TDT sanitizes store codes containing `/`
399
+ into a trailing-underscore Python attribute name (e.g. dict key
400
+ "EE1_" but the real store code passed to `store=` is "EE1/").
401
+ - Epoc reads must NOT reuse the cached `headers=` object from the
402
+ initial header scan — doing so carries over the same mismatched
403
+ onset/offset state that causes the crash in the first place. Only
404
+ the streams/scalars read benefits from header reuse.
405
+
406
+ This entirely auto-discovers whatever stores a given recording
407
+ contains — nothing about store names/types is hardcoded, so it works
408
+ for any TDT block regardless of how it was configured in Synapse.
409
+
410
+ Parameters
411
+ ----------
412
+ path : str
413
+ Folder containing TDT data.
414
+ progress : None, True or callable(fraction, message)
415
+ Progress reporting (see PyATCLI.progress). Reading the
416
+ streams is one opaque SDK call; each epoc store read after it ticks
417
+ the bar.
418
+ read_streams : bool
419
+ False skips the streams (the slow part of the read, and not needed
420
+ just to list a block's event markers — see scan_tdt_markers): the
421
+ block's info, scalars and epoc stores are still read, and
422
+ data.streams is empty.
423
+
424
+ Returns
425
+ -------
426
+ object
427
+ Parsed TDT data structure (data.streams, data.epocs, data.scalars).
428
+ """
429
+ import warnings
430
+
431
+ plan = Plan(progress, [("Reading streams" if read_streams else "Reading block header", 55),
432
+ ("Reading event stores", 45)]) # ~0.3 s vs ~0.25 s measured
433
+ plan.begin("Reading streams" if read_streams else "Reading block header")
434
+ heads = tdt.read_block(path, headers=1)
435
+ if heads is None:
436
+ raise Exception("TDT returned an empty object.")
437
+
438
+ data = tdt.read_block(path, headers=heads, evtype=['streams', 'scalars'] if read_streams else ['scalars'],
439
+ verbose=0)
440
+ if data is None:
441
+ raise Exception("TDT returned an empty object.")
442
+
443
+ epoc_stores = [(key, s.name) for key, s in heads.stores.items()
444
+ if getattr(s, 'type_str', None) == 'epocs']
445
+
446
+ for key, real_name in plan.track("Reading event stores", epoc_stores):
447
+ try:
448
+ # No headers= reuse here — see docstring.
449
+ ep = tdt.read_block(path, store=real_name, evtype=['epocs'], verbose=0)
450
+ except Exception as e:
451
+ warnings.warn(
452
+ f"Skipping epoc store '{key}' ({real_name}): {e}",
453
+ RuntimeWarning, stacklevel=2,
454
+ )
455
+ continue
456
+ if not ep.epocs:
457
+ continue
458
+ store_key = next(iter(ep.epocs.keys()))
459
+ setattr(data.epocs, key, ep.epocs[store_key])
460
+
461
+ # The SDK delivers float32; everything downstream (and any caller using the struct directly) gets
462
+ # float64 — see numeric.py for why this is a rule and not an optimisation.
463
+ for stream in getattr(data, 'streams', {}).values():
464
+ stream.data = as_float64(stream.data)
465
+
466
+ return data
467
+
468
+
469
+ def _block_duration(data):
470
+ """Seconds between a block's start and stop time (what Synapse recorded), or None."""
471
+ duration = getattr(getattr(data, "info", None), "duration", None)
472
+ if duration is None:
473
+ return None
474
+ try:
475
+ return float(duration.total_seconds())
476
+ except AttributeError:
477
+ try:
478
+ return float(duration)
479
+ except (TypeError, ValueError):
480
+ return None
481
+
482
+
483
+ def scan_tdt_markers(folder_path, splices=None, progress=None):
484
+ """
485
+ List the event markers of a TDT block without processing the recording: no
486
+ dF/F, and the streams are only read when `splices` need the recording's time
487
+ axis. Group analysis uses it to find out which markers each recording has, and
488
+ how many, before any signal work is done; reading the markers takes about a
489
+ third of a second, processing the whole recording about two.
490
+
491
+ Parameters
492
+ ----------
493
+ folder_path : str
494
+ Folder containing the TDT block.
495
+ splices : list of {"mode", "start", "end"}, optional
496
+ The recording's saved splices (PyAT's splice.json), applied to the marker
497
+ times and the recording's span in order, exactly as PyAT does when it
498
+ restores them (see splice.replay_splices).
499
+ progress : None, True or callable(fraction, message)
500
+ Progress reporting (see PyATCLI.progress).
501
+
502
+ Returns
503
+ -------
504
+ dict with
505
+ markers : list of dict
506
+ What get_event_markers returns (time, label, color, store and, for
507
+ onset/offset markers, phase), after the splices if there are any.
508
+ t_range : (first, last) sample time in seconds, or None if the block does
509
+ not say how long it is. Exact when `splices` were given (the time axis
510
+ was rebuilt); otherwise (0, the block's recorded duration), which can
511
+ be a few hundredths of a second past the last sample.
512
+ n_splices : how many of the given splices took effect.
513
+ block_name : the block's name (Synapse's Subject-YYMMDD-HHMMSS), or None.
514
+ start_time : ISO date-time the block started, or None.
515
+ """
516
+ splices = list(splices or [])
517
+ data = get_tdt_struct(folder_path, progress=progress, read_streams=bool(splices))
518
+ markers = get_event_markers(data)
519
+ info = getattr(data, "info", None)
520
+
521
+ n_applied = 0
522
+ if splices:
523
+ name_465 = next((s for s in data.streams.keys() if '465' in s), None)
524
+ if not name_465:
525
+ raise ValueError("No 465 signal found")
526
+ x, _, _ = get_plot_data(data, name_465)
527
+ replayed = replay_splices(x, splices, detected_markers=markers)
528
+ x, markers, n_applied = replayed["x"], replayed["detected_markers"], replayed["applied"]
529
+ t_range = (float(x[0]), float(x[-1]))
530
+ else:
531
+ duration = _block_duration(data)
532
+ t_range = (0.0, duration) if duration is not None else None
533
+
534
+ start = getattr(info, "start_date", None)
535
+ return {
536
+ "markers": markers,
537
+ "t_range": t_range,
538
+ "n_splices": n_applied,
539
+ "block_name": getattr(info, "blockname", None),
540
+ "start_time": start.isoformat() if hasattr(start, "isoformat") else None,
541
+ }
542
+
543
+
544
+ def get_plot_data(data, store_name, channel=0, max_points=None):
545
+ """
546
+ Extract time-series data from a TDT stream.
547
+
548
+ Parameters
549
+ ----------
550
+ data : object
551
+ TDT data structure
552
+ store_name : str
553
+ Stream name (e.g., 'x465A')
554
+ channel : int
555
+ Channel index
556
+ max_points : int or None
557
+ Optional downsampling limit
558
+
559
+ Returns
560
+ -------
561
+ tuple
562
+ (time array, signal array, sampling frequency)
563
+ """
564
+ stream = data.streams[store_name]
565
+ fs = float(stream.fs)
566
+
567
+ data_2d = np.atleast_2d(as_float64(stream.data))
568
+ if channel >= data_2d.shape[0]:
569
+ channel = 0
570
+
571
+ y_full = data_2d[channel, :]
572
+
573
+ if max_points:
574
+ ds_factor = max(1, len(y_full) // max_points)
575
+ y = y_full[::ds_factor]
576
+ x = np.arange(len(y)) * (ds_factor / fs)
577
+ else:
578
+ y = y_full
579
+ x = np.arange(len(y)) / fs
580
+
581
+ return x, y, fs
582
+
583
+
584
+ def correct_bleaching(y, fs):
585
+ """
586
+ Estimate and correct photobleaching using masked curve fitting.
587
+
588
+ Returns
589
+ -------
590
+ corrected : array
591
+ Bleaching-corrected signal
592
+ trend : array
593
+ Estimated baseline trend
594
+ """
595
+ y = as_float64(y)
596
+ x = np.arange(len(y)) / fs
597
+
598
+ threshold = np.median(y)
599
+ mask = y > threshold
600
+ x_fit, y_fit = x[mask], y[mask]
601
+
602
+ if len(y_fit) < 100:
603
+ return y, np.zeros_like(y)
604
+
605
+ # Fit in units of the signal's own size and scale the trend back
606
+ # afterwards: curve_fit's optimiser isn't scale-free (it converged to a
607
+ # baseline up to ~4.5% different for the same recording expressed x1000).
608
+ scale = np.max(np.abs(y_fit))
609
+ if not np.isfinite(scale) or scale <= 0:
610
+ scale = 1.0
611
+ y_fit = y_fit / scale
612
+
613
+ k_guess = np.percentile(y_fit, 10)
614
+ total_amp = np.max(y_fit) - k_guess
615
+ p0 = [total_amp * 0.6, 0.05, total_amp * 0.4, 0.0001, k_guess]
616
+ lower = [0, 0, 0, 0, k_guess * 0.8]
617
+ upper = [np.inf, 1, np.inf, 0.1, np.max(y_fit)]
618
+
619
+ try:
620
+ popt, _ = curve_fit(double_exponential, x_fit, y_fit, p0=p0,
621
+ bounds=(lower, upper), maxfev=10000)
622
+ trend = scale * double_exponential(x, *popt)
623
+ except Exception:
624
+ # curve_fit failed — fall back to log-linear fit as a rough trend estimate
625
+ import warnings
626
+ warnings.warn(
627
+ "correct_bleaching: double-exponential fit failed; falling back to log-linear trend.",
628
+ RuntimeWarning, stacklevel=2,
629
+ )
630
+ coeffs = np.polyfit(x_fit, np.log(np.maximum(y_fit, 1e-6)), 1)
631
+ trend = scale * np.exp(np.polyval(coeffs, x))
632
+
633
+ corrected = y - trend + trend[0]
634
+ return corrected, trend
635
+
636
+
637
+ def get_event_markers(data):
638
+ """
639
+ Extract behavioral event markers from every populated TDT epoc store.
640
+
641
+ A recording can easily have a dozen+ epoc stores (I/O strobes, Epoch
642
+ Event Storage, free-text notes, ...) — every one of them becomes its
643
+ own marker group here, tagged by store name via the 'store' key, so
644
+ a caller (e.g. a GUI) can let the user toggle each store's markers
645
+ independently instead of dumping every store onto the plot at once
646
+ (which overlaps into an unreadable mess). The one exception is the
647
+ 'Tick' store — TDT's own 1-second heartbeat/reference signal, not a
648
+ behavioral event — which is skipped entirely.
649
+
650
+ Every epoc is a state that goes high (onset) and later low (offset) —
651
+ for a lever press that's press/release, for a pump or light that's
652
+ on/off. Both are emitted here, each tagged with a 'phase' key ('high'
653
+ for onset, 'low' for offset), so a caller can decide per store whether
654
+ it cares about both edges (e.g. how long the pump ran) or only one
655
+ (e.g. just the press, not the release) instead of that decision being
656
+ baked into the library.
657
+
658
+ The 'Note' store keeps its original behaviour: each onset becomes a
659
+ marker labeled with the actual note text (from Notes.txt), and has no
660
+ offset/'low' marker — free-text annotations are instantaneous, not a
661
+ state with a duration. Every other epoc store gets one 'high' marker
662
+ per onset and one 'low' marker per offset, both labeled with the store
663
+ name.
664
+
665
+ Nothing about which stores exist is hardcoded — this walks whatever
666
+ data.epocs actually contains, so it works for any TDT block.
667
+
668
+ Returns
669
+ -------
670
+ list of dict
671
+ Each dict contains:
672
+ - time : float
673
+ - label : str
674
+ - color : str
675
+ - store : str (source epoc store name, for grouping/toggling)
676
+ - phase : str ('high'=onset, 'low'=offset; omitted for Note markers)
677
+ """
678
+ if not hasattr(data, 'epocs'):
679
+ return []
680
+
681
+ # Experiment-specific label→colour mapping for Note text; every other
682
+ # store cycles through a fixed palette so each store gets a distinct,
683
+ # consistent colour across redraws.
684
+ note_color_map = {'Clap': 'red', 'Sucrose': 'green', 'Stop': 'blue'}
685
+ palette = ['black', 'purple', 'orange', 'saddlebrown', 'teal', 'magenta',
686
+ 'darkgreen', 'navy', 'gray', 'olive']
687
+
688
+ markers = []
689
+ store_keys = sorted(k for k in data.epocs.keys())
690
+
691
+ for i, store_key in enumerate(store_keys):
692
+ display_name = store_key.rstrip('_') # cosmetic: TDT pads slash-containing codes with a trailing "_"
693
+ if display_name.lower() == 'tick':
694
+ # TDT's own 1-second heartbeat/reference signal, not a
695
+ # behavioral event — every recording has it, it's never
696
+ # something a caller wants to plot, analyze, or splice
697
+ # against, and its sheer regularity would otherwise flood
698
+ # every marker/event picker in the GUI.
699
+ continue
700
+
701
+ epoc = data.epocs[store_key]
702
+ onsets = getattr(epoc, 'onset', [])
703
+ if len(onsets) == 0:
704
+ continue
705
+
706
+ if store_key == 'Note':
707
+ notes = getattr(epoc, 'notes', [])
708
+ for n, t in zip(notes, onsets):
709
+ note_str = n.decode() if isinstance(n, bytes) else str(n)
710
+ note_str = note_str.strip()
711
+ markers.append({
712
+ 'time': float(t),
713
+ 'label': note_str,
714
+ 'color': note_color_map.get(note_str, 'black'),
715
+ 'store': display_name,
716
+ })
717
+ else:
718
+ color = palette[i % len(palette)]
719
+ for t in onsets:
720
+ # A level-type epoc store (buffered, tracks a logic
721
+ # signal's on/off state — common for some Synapse Gizmo
722
+ # outputs) has no history before recording starts; if its
723
+ # logic already happened to be high the instant recording
724
+ # began, TDT inserts a synthetic onset at exactly t=0 to
725
+ # represent that pre-existing state, not a real event.
726
+ # Mirrors the offset=inf guard below for the same store
727
+ # type's opposite edge case (still active at the end).
728
+ if t == 0.0:
729
+ continue
730
+ markers.append({
731
+ 'time': float(t),
732
+ 'label': display_name,
733
+ 'color': color,
734
+ 'store': display_name,
735
+ 'phase': 'high',
736
+ })
737
+ offsets = getattr(epoc, 'offset', [])
738
+ for t in offsets:
739
+ # TDT represents a strobe still active at recording end with
740
+ # offset=inf — not a real timestamp, nothing to plot.
741
+ if not np.isfinite(t):
742
+ continue
743
+ markers.append({
744
+ 'time': float(t),
745
+ 'label': display_name,
746
+ 'color': color,
747
+ 'store': display_name,
748
+ 'phase': 'low',
749
+ })
750
+
751
+ return markers
752
+
753
+
754
+ def debounce_events(times, min_isi):
755
+ """
756
+ Collapse switch-bounce / double-tap duplicates out of a list of event
757
+ timestamps (e.g. lever-press onsets), independent of any fixed-ratio
758
+ schedule (FR1, FR3, ...).
759
+
760
+ A real lever contact and a bounce/duplicate reading of the same
761
+ physical press land within milliseconds of each other — far closer
762
+ than an animal can genuinely press again. Sorting the timestamps and
763
+ dropping anything within `min_isi` seconds of the last *kept* event
764
+ removes those duplicates while leaving genuinely fast consecutive
765
+ presses (e.g. during an FR3 burst) intact, as long as `min_isi` is
766
+ below the animal's real max press rate.
767
+
768
+ Parameters
769
+ ----------
770
+ times : sequence of float
771
+ Raw event timestamps, in seconds. Need not be sorted.
772
+ min_isi : float
773
+ Minimum inter-event interval, in seconds. Any event whose gap from
774
+ the previous kept event is smaller than this is dropped. The
775
+ first press of a bounce cluster is always the one kept.
776
+
777
+ Returns
778
+ -------
779
+ list of float
780
+ Sorted timestamps with sub-`min_isi` duplicates removed.
781
+ """
782
+ sorted_times = sorted(float(t) for t in times)
783
+ kept = []
784
+ for t in sorted_times:
785
+ if not kept or (t - kept[-1]) >= min_isi:
786
+ kept.append(t)
787
+ return kept
788
+
789
+
790
+ def denoise_signal(signal, fs, cutoff=DENOISE_CUTOFF_HZ, order=DENOISE_ORDER):
791
+ """
792
+ Low-pass Butterworth filter for ΔF/F signals.
793
+
794
+ Parameters
795
+ ----------
796
+ cutoff : float
797
+ Cutoff frequency in Hz
798
+ order : int
799
+ Filter order
800
+
801
+ Returns
802
+ -------
803
+ array
804
+ Filtered signal
805
+ """
806
+ signal = as_float64(signal)
807
+ nyquist = fs / 2
808
+ normal_cutoff = cutoff / nyquist
809
+ b, a = butter(order, normal_cutoff, btype='low', analog=False)
810
+ return filtfilt(b, a, signal)