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.
- PyATCLI/__init__.py +196 -0
- PyATCLI/__main__.py +7 -0
- PyATCLI/_version.py +47 -0
- PyATCLI/analyses.py +640 -0
- PyATCLI/analysis/__init__.py +81 -0
- PyATCLI/analysis/auc.py +79 -0
- PyATCLI/analysis/curve_fit.py +88 -0
- PyATCLI/analysis/event_peth.py +263 -0
- PyATCLI/analysis/fft.py +99 -0
- PyATCLI/analysis/group/__init__.py +318 -0
- PyATCLI/analysis/group/rebuild.py +59 -0
- PyATCLI/analysis/group/report.py +281 -0
- PyATCLI/analysis/group/run.py +164 -0
- PyATCLI/analysis/group/scan.py +92 -0
- PyATCLI/analysis/group/stats.py +451 -0
- PyATCLI/analysis/group/trials.py +188 -0
- PyATCLI/analysis/intervals.py +59 -0
- PyATCLI/analysis/peak_finder.py +155 -0
- PyATCLI/analysis/shared.py +100 -0
- PyATCLI/analysis/zscore_peth.py +107 -0
- PyATCLI/cli/__init__.py +105 -0
- PyATCLI/cli/commands.py +395 -0
- PyATCLI/cli/docs.py +246 -0
- PyATCLI/cli/parser.py +286 -0
- PyATCLI/cli/render.py +130 -0
- PyATCLI/engine/__init__.py +0 -0
- PyATCLI/engine/contract.py +124 -0
- PyATCLI/engine/server.py +169 -0
- PyATCLI/engine/session.py +40 -0
- PyATCLI/engine/store.py +222 -0
- PyATCLI/engine/wire.py +103 -0
- PyATCLI/fieldstudy/__init__.py +1 -0
- PyATCLI/fieldstudy/study.py +440 -0
- PyATCLI/fieldstudy/validation.py +443 -0
- PyATCLI/markers.py +71 -0
- PyATCLI/models.py +102 -0
- PyATCLI/numeric.py +35 -0
- PyATCLI/ops/__init__.py +274 -0
- PyATCLI/ops/analysis.py +136 -0
- PyATCLI/ops/common.py +93 -0
- PyATCLI/ops/compute.py +94 -0
- PyATCLI/ops/fieldstudy.py +52 -0
- PyATCLI/ops/files.py +42 -0
- PyATCLI/ops/group.py +144 -0
- PyATCLI/ops/recording.py +90 -0
- PyATCLI/ops/records.py +63 -0
- PyATCLI/ops/results.py +27 -0
- PyATCLI/ops/saved.py +98 -0
- PyATCLI/ops/system.py +31 -0
- PyATCLI/outputs.py +165 -0
- PyATCLI/progress.py +227 -0
- PyATCLI/provenance.py +336 -0
- PyATCLI/recording.py +602 -0
- PyATCLI/reproduce.py +278 -0
- PyATCLI/results.py +106 -0
- PyATCLI/saved_state.py +275 -0
- PyATCLI/sources/__init__.py +1 -0
- PyATCLI/sources/dataset.py +110 -0
- PyATCLI/sources/load.py +169 -0
- PyATCLI/sources/processing_TDT.py +810 -0
- PyATCLI/sources/processing_oxysoft.py +259 -0
- PyATCLI/sources/pt2.py +46 -0
- PyATCLI/sources/tables.py +306 -0
- PyATCLI/splice.py +196 -0
- PyATCLI/viewplan.py +181 -0
- pyatcli-2026.10.10.dist-info/METADATA +296 -0
- pyatcli-2026.10.10.dist-info/RECORD +71 -0
- pyatcli-2026.10.10.dist-info/WHEEL +5 -0
- pyatcli-2026.10.10.dist-info/entry_points.txt +2 -0
- pyatcli-2026.10.10.dist-info/licenses/LICENSE +661 -0
- pyatcli-2026.10.10.dist-info/top_level.txt +1 -0
PyATCLI/recording.py
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
"""
|
|
2
|
+
recording.py
|
|
3
|
+
------------
|
|
4
|
+
A recording as PyAT holds it, without the GUI: everything between "open a recording" and "run an
|
|
5
|
+
analysis" that isn't drawing. The GUI keeps this state in `ctx.cache`; this module builds, edits and
|
|
6
|
+
queries exactly that dict, so a script gets the same numbers the app shows.
|
|
7
|
+
|
|
8
|
+
The cache ("recording") dict
|
|
9
|
+
source 'TDT' | 'Oxysoft' | 'Generic'
|
|
10
|
+
source_path the folder / file it was read from
|
|
11
|
+
store a display name (the folder / file / table name, plus a tag per splice)
|
|
12
|
+
x, fs time axis (s) and sampling rate (Hz)
|
|
13
|
+
markers user-placed markers (list of dict, see markers.py)
|
|
14
|
+
highlights, text_annotations shaded stretches and text boxes, when the recording has them saved (saved_state.py)
|
|
15
|
+
-- TDT: raw, corr (dF/F), detected_markers, signals {key: {"label", "y"}}, motion_correction_inlier_fraction
|
|
16
|
+
-- Oxysoft: o2hb, hhb, optional thb (each (n_channels, n_samples)), detected_markers, fit_factor_mean
|
|
17
|
+
-- Generic: y_columns {name: y}, x_label
|
|
18
|
+
|
|
19
|
+
What is here
|
|
20
|
+
- the saved state next to a recording ("JSON saves/": markers, splices, the names given to its signals, highlights,
|
|
21
|
+
text boxes) — where it lives, and reading it back (saved_state.py writes it);
|
|
22
|
+
- building a cache from a load (make_tdt_cache / make_oxysoft_cache / make_generic_cache) and
|
|
23
|
+
the one-call headless load_tdt_recording;
|
|
24
|
+
- splicing (apply_splice for one, apply_splices for a saved list — Cut Out and Keep Inside both
|
|
25
|
+
re-fit the dF/F on what is left, exactly as the app does);
|
|
26
|
+
- picking the signal analyses run on (normalized_signal), and finding the recordings under a folder
|
|
27
|
+
(find_tdt_recordings).
|
|
28
|
+
|
|
29
|
+
The splice arithmetic itself (cutting/stitching arrays and markers) is in splice.py; the dF/F
|
|
30
|
+
pipeline is in sources/processing_TDT.py.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
|
|
36
|
+
import numpy as np
|
|
37
|
+
|
|
38
|
+
from .markers import group_markers_by_name # noqa: F401 — re-exported: the usual next step after loading
|
|
39
|
+
from .sources.processing_TDT import compute_dff, process_tdt_folder, validate_tdt_folder
|
|
40
|
+
from .progress import Plan
|
|
41
|
+
from .splice import MODE_CUT_OUT, MODE_KEEP_INSIDE, splice_cut_out, splice_keep_inside
|
|
42
|
+
|
|
43
|
+
# What a loaded recording (its `cache`) always has, by where it came from: a caller may count on these keys (ENGINE_CONTRACT.json lists them; removing
|
|
44
|
+
# or renaming one is a breaking change, see engine/contract.py). There are more (a TDT recording also holds the pieces it was built from, an Oxysoft
|
|
45
|
+
# one its fit factor, any of them the highlights and text boxes once there are some), and more can be added.
|
|
46
|
+
CACHE_KEYS = {
|
|
47
|
+
"always": ["x", "fs", "source", "source_path", "store", "markers"],
|
|
48
|
+
"TDT": ["signals", "corr", "raw", "detected_markers", "motion_correction_inlier_fraction"],
|
|
49
|
+
"Oxysoft": ["o2hb", "hhb", "detected_markers"],
|
|
50
|
+
"Generic": ["x_label", "y_columns"],
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
SAVES_FOLDER = "JSON saves"
|
|
54
|
+
HIGHLIGHTS_FILE = "highlights.json"
|
|
55
|
+
TEXT_ANNOTATIONS_FILE = "text_annotations.json"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ---------------------------------------------------------------------------
|
|
59
|
+
# Where the saved state lives
|
|
60
|
+
# ---------------------------------------------------------------------------
|
|
61
|
+
|
|
62
|
+
def saved_state_dir(source_path):
|
|
63
|
+
"""The "JSON saves" folder for a recording: inside a folder source (TDT), next to a file source
|
|
64
|
+
(Oxysoft, Generic)."""
|
|
65
|
+
base = source_path if os.path.isdir(source_path) else os.path.dirname(source_path)
|
|
66
|
+
return os.path.join(base, SAVES_FOLDER)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def marker_sidecar_path(source_path):
|
|
70
|
+
"""Where the recording's markers are saved: JSON saves/markers.json inside a folder source,
|
|
71
|
+
JSON saves/<file name>.markers.json next to a file source."""
|
|
72
|
+
if os.path.isdir(source_path):
|
|
73
|
+
return os.path.join(saved_state_dir(source_path), "markers.json")
|
|
74
|
+
return os.path.join(saved_state_dir(source_path), os.path.basename(source_path) + ".markers.json")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def legacy_marker_sidecar_path(source_path):
|
|
78
|
+
"""Pre-JSON-saves-folder location: a sibling file next to the raw data folder/file, e.g.
|
|
79
|
+
<source>.markers.json. Only read, for markers saved before they moved into the JSON saves/
|
|
80
|
+
folder, so old studies don't lose theirs."""
|
|
81
|
+
return source_path + ".markers.json"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def annotation_sidecar_path(source_path, filename):
|
|
85
|
+
"""Same JSON saves/ folder as markers.json, for any other list saved the same way
|
|
86
|
+
(highlights.json, text_annotations.json) — no legacy fallback, they're newer than the move."""
|
|
87
|
+
if os.path.isdir(source_path):
|
|
88
|
+
return os.path.join(saved_state_dir(source_path), filename)
|
|
89
|
+
return os.path.join(saved_state_dir(source_path), os.path.basename(source_path) + f".{filename}")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def splice_sidecar_path(source_path):
|
|
93
|
+
"""splice.json, next to markers.json in the same JSON saves/ folder — every splice stacked on
|
|
94
|
+
the recording, in order."""
|
|
95
|
+
return os.path.join(os.path.dirname(marker_sidecar_path(source_path)), "splice.json")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def read_saved_splices(source_path):
|
|
99
|
+
"""The recording's saved splices, in the order they were applied ([] if none). Accepts the
|
|
100
|
+
current list format and the old single-splice dict, like the app's loader does."""
|
|
101
|
+
path = splice_sidecar_path(source_path)
|
|
102
|
+
if not path or not os.path.exists(path):
|
|
103
|
+
return []
|
|
104
|
+
with open(path, "r") as f:
|
|
105
|
+
saved = json.load(f)
|
|
106
|
+
return [saved] if isinstance(saved, dict) else list(saved)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def signal_labels_path(source_path):
|
|
110
|
+
"""Where the names given to the recording's signals are saved (signal_labels.json, in JSON saves/)."""
|
|
111
|
+
return annotation_sidecar_path(source_path, "signal_labels.json")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def read_saved_signal_labels(source_path):
|
|
115
|
+
"""{signal key: the name it was given} saved for the recording ({} if none). `ValueError` if the file
|
|
116
|
+
does not hold an object."""
|
|
117
|
+
path = signal_labels_path(source_path)
|
|
118
|
+
if not os.path.exists(path):
|
|
119
|
+
return {}
|
|
120
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
121
|
+
saved = json.load(f)
|
|
122
|
+
if not isinstance(saved, dict):
|
|
123
|
+
raise ValueError("signal_labels.json does not hold an object of names")
|
|
124
|
+
return {str(k): str(v) for k, v in saved.items()}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def read_saved_annotations(source_path, filename):
|
|
128
|
+
"""A list of dicts saved in its own file in the saved state (HIGHLIGHTS_FILE, TEXT_ANNOTATIONS_FILE); [] if there is none.
|
|
129
|
+
`ValueError` if the file does not hold a list."""
|
|
130
|
+
path = annotation_sidecar_path(source_path, filename)
|
|
131
|
+
if not os.path.exists(path):
|
|
132
|
+
return []
|
|
133
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
134
|
+
saved = json.load(f)
|
|
135
|
+
if not isinstance(saved, list):
|
|
136
|
+
raise ValueError(f"{filename} does not hold a list")
|
|
137
|
+
return saved
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def apply_signal_labels(cache, labels):
|
|
141
|
+
"""Gives the recording's signals the names in `labels` ({signal key: name}; a key the recording does
|
|
142
|
+
not have, or an empty name, is ignored). The cache dict is updated in place (its arrays are not copied);
|
|
143
|
+
returns it. The name is what figures, legends and the "Channel" column of exports show."""
|
|
144
|
+
signals = cache.get("signals")
|
|
145
|
+
if signals and labels:
|
|
146
|
+
cache["signals"] = {k: ({**sig, "label": labels[k]} if labels.get(k) else sig) for k, sig in signals.items()}
|
|
147
|
+
return cache
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def current_signal_labels(cache):
|
|
151
|
+
"""{signal key: name in effect} for the recording ({} if it has no signals map) — what a provenance record
|
|
152
|
+
stores so a replay names the signals the same."""
|
|
153
|
+
return {k: sig["label"] for k, sig in (cache.get("signals") or {}).items()}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def name_problem(final_labels):
|
|
157
|
+
"""Why {signal key: name} can't be the recording's names, or None if it can: a name must say something, and two signals can't
|
|
158
|
+
share one (the legend, the colours and the exports tell them apart by name)."""
|
|
159
|
+
if any(not str(name).strip() for name in final_labels.values()):
|
|
160
|
+
return "A signal needs a name."
|
|
161
|
+
names = [str(name).strip() for name in final_labels.values()]
|
|
162
|
+
for name in names:
|
|
163
|
+
if names.count(name) > 1:
|
|
164
|
+
return f"Two signals can't both be called \"{name}\"."
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def plan_signal_renames(cache, renames):
|
|
169
|
+
"""{signal key: new name} for what would change: a key the recording doesn't have, or a name that is empty or unchanged, is
|
|
170
|
+
skipped. ValueError, with nothing changed, if the result would give two signals the same name."""
|
|
171
|
+
signals = cache.get('signals') if cache else None
|
|
172
|
+
if not signals:
|
|
173
|
+
return {}
|
|
174
|
+
current = current_signal_labels(cache)
|
|
175
|
+
changes = {key: str(name).strip() for key, name in renames.items()
|
|
176
|
+
if key in signals and name and str(name).strip() and str(name).strip() != current[key]}
|
|
177
|
+
if changes:
|
|
178
|
+
problem = name_problem({**current, **changes})
|
|
179
|
+
if problem:
|
|
180
|
+
raise ValueError(problem)
|
|
181
|
+
return changes
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def read_saved_markers(source_path):
|
|
185
|
+
"""The markers saved for the recording (JSON saves/markers.json, else the older sibling
|
|
186
|
+
<source>.markers.json); [] if there are none. Same lookup as the app's restore."""
|
|
187
|
+
path = marker_sidecar_path(source_path)
|
|
188
|
+
if not path or not os.path.exists(path):
|
|
189
|
+
path = legacy_marker_sidecar_path(source_path)
|
|
190
|
+
if not path or not os.path.exists(path):
|
|
191
|
+
return []
|
|
192
|
+
with open(path, "r") as f:
|
|
193
|
+
saved = json.load(f)
|
|
194
|
+
if not isinstance(saved, list):
|
|
195
|
+
raise ValueError("markers.json does not hold a list of markers")
|
|
196
|
+
return saved
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ---------------------------------------------------------------------------
|
|
200
|
+
# Building a cache from a load
|
|
201
|
+
# ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
def build_signal_options(result):
|
|
204
|
+
"""The signals a TDT recording offers for plotting/analysis: the computed normalized trace plus
|
|
205
|
+
whatever raw per-wavelength channels process_tdt_folder() found, as
|
|
206
|
+
{key: {"label", "y"}} (the app adds a display colour to each). Not hardcoded to exactly
|
|
207
|
+
"Normalized/Isosbestic/Main Driver" — a block with no isosbestic reference stream just won't
|
|
208
|
+
have that key."""
|
|
209
|
+
options = {
|
|
210
|
+
"normalized": {"label": "Normalized (dF/F)", "y": result["corr"]},
|
|
211
|
+
}
|
|
212
|
+
for ch in result.get("channels", []):
|
|
213
|
+
options[ch["key"]] = {"label": ch["label"], "y": ch["y"]}
|
|
214
|
+
return options
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def make_tdt_cache(folder_path, result, signals=None):
|
|
218
|
+
"""The cache for a freshly processed TDT folder (`result` is process_tdt_folder's return value),
|
|
219
|
+
before any splice or saved marker. `signals` replaces the default build_signal_options(result)
|
|
220
|
+
(the app passes its own, with colours added)."""
|
|
221
|
+
return {
|
|
222
|
+
'source': 'TDT',
|
|
223
|
+
'source_path': folder_path,
|
|
224
|
+
'store': os.path.basename(folder_path.rstrip('/\\')),
|
|
225
|
+
'x': result['x'],
|
|
226
|
+
'raw': result['raw'],
|
|
227
|
+
'corr': result['corr'],
|
|
228
|
+
'fs': result['fs'],
|
|
229
|
+
'detected_markers': result.get('markers', []),
|
|
230
|
+
'markers': [],
|
|
231
|
+
'signals': signals if signals is not None else build_signal_options(result),
|
|
232
|
+
# the share of samples the motion-correction fit kept (None for a recording with no reference stream): not
|
|
233
|
+
# drawn anywhere, but the number to compare regression methods by, so a window can say it after a load
|
|
234
|
+
'motion_correction_inlier_fraction': result.get('motion_correction_inlier_fraction'),
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def make_oxysoft_cache(file_path, dataset):
|
|
239
|
+
"""The cache for a loaded Oxysoft file (`dataset` is load_dataset_file's Dataset)."""
|
|
240
|
+
n_ch = dataset.metadata.get('n_channels', dataset.num_channels // 2)
|
|
241
|
+
cache = {
|
|
242
|
+
'source': 'Oxysoft',
|
|
243
|
+
'source_path': file_path,
|
|
244
|
+
'store': dataset.folder_name,
|
|
245
|
+
'x': np.arange(dataset.num_samples) / dataset.sample_rate,
|
|
246
|
+
'o2hb': dataset.signals[:n_ch],
|
|
247
|
+
'hhb': dataset.signals[n_ch:],
|
|
248
|
+
'fs': dataset.sample_rate,
|
|
249
|
+
'fit_factor_mean': dataset.metadata.get('fit_factor_mean'),
|
|
250
|
+
'detected_markers': [
|
|
251
|
+
{"time": ev["sample"] / dataset.sample_rate, "label": ev["label"],
|
|
252
|
+
"color": "black", "store": "Events"}
|
|
253
|
+
for ev in dataset.events
|
|
254
|
+
],
|
|
255
|
+
'markers': [],
|
|
256
|
+
}
|
|
257
|
+
if 'thb' in dataset.metadata:
|
|
258
|
+
cache['thb'] = dataset.metadata['thb']
|
|
259
|
+
return cache
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def make_generic_cache(path, table, x_index=0, y_indices=None):
|
|
263
|
+
"""The cache for one table of a generic tabular file (`table` is one of load_any_file's
|
|
264
|
+
GenericTables): column `x_index` is the x axis (rows with no x value are dropped) and each of
|
|
265
|
+
`y_indices` (default: every other column) becomes a trace, keyed by its header."""
|
|
266
|
+
if y_indices is None:
|
|
267
|
+
y_indices = [i for i in range(len(table.headers)) if i != x_index]
|
|
268
|
+
x_data = table.data[:, x_index]
|
|
269
|
+
valid = ~np.isnan(x_data)
|
|
270
|
+
x_data = x_data[valid]
|
|
271
|
+
y_columns = {table.headers[yi]: table.data[valid, yi] for yi in y_indices}
|
|
272
|
+
from .analysis.shared import estimate_sample_rate
|
|
273
|
+
fs = estimate_sample_rate(x_data) if len(x_data) > 1 else 1.0
|
|
274
|
+
return {
|
|
275
|
+
"source": "Generic",
|
|
276
|
+
"source_path": path,
|
|
277
|
+
"x": x_data,
|
|
278
|
+
"y_columns": y_columns,
|
|
279
|
+
"x_label": table.headers[x_index],
|
|
280
|
+
"store": table.name,
|
|
281
|
+
"fs": fs,
|
|
282
|
+
"markers": [],
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def normalized_signal(cache):
|
|
287
|
+
"""The (key, label, y) of the trace every analysis that works on the corrected signal uses
|
|
288
|
+
(Event PETH, the peak finder, group analysis, ...): "normalized" (dF/F) if the recording offers
|
|
289
|
+
it, whatever comes first if not; for a source with no signals map, its corrected trace, else its
|
|
290
|
+
raw one."""
|
|
291
|
+
signals = cache.get('signals')
|
|
292
|
+
if not signals:
|
|
293
|
+
y = cache['corr'] if 'corr' in cache else cache['raw']
|
|
294
|
+
return "normalized", "dF/F (corrected)", y
|
|
295
|
+
key = "normalized" if "normalized" in signals else next(iter(signals))
|
|
296
|
+
return key, signals[key]['label'], signals[key]['y']
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
# ---------------------------------------------------------------------------
|
|
300
|
+
# Splicing
|
|
301
|
+
# ---------------------------------------------------------------------------
|
|
302
|
+
|
|
303
|
+
def apply_splice(source_cache, mode, start, end, regression_method="ols", progress=None):
|
|
304
|
+
"""Pure computation: one splice applied to source_cache, returning the new spliced cache dict, or
|
|
305
|
+
None if the range isn't usable. Nothing is mutated.
|
|
306
|
+
|
|
307
|
+
Branches on the cache's source since each one carries the actual signal in different keys. All
|
|
308
|
+
three paths funnel every source-specific array through splice.py's extra_channels (sliced along
|
|
309
|
+
each array's own last axis, so Oxysoft's 2D per-detector arrays and Generic's 1D columns both
|
|
310
|
+
just work) so the trim/cut-and-stitch math itself lives in exactly one place.
|
|
311
|
+
|
|
312
|
+
For TDT, both modes re-run motion/bleaching correction (compute_dff) on whatever raw signal
|
|
313
|
+
survived: an artifact dragging the original fit can still be included or excluded by either
|
|
314
|
+
operation, so a fresh fit — not just a shorter view of the old one — is what a splice means.
|
|
315
|
+
regression_method only matters there (Oxysoft/Generic have no correction pipeline to re-run), and
|
|
316
|
+
so does `progress` (a PyATCLI progress callback): only that recompute is slow enough to
|
|
317
|
+
report on.
|
|
318
|
+
"""
|
|
319
|
+
splice_fn = splice_cut_out if mode == MODE_CUT_OUT else splice_keep_inside
|
|
320
|
+
source = source_cache.get('source')
|
|
321
|
+
x = source_cache['x']
|
|
322
|
+
markers = source_cache['markers']
|
|
323
|
+
detected_markers = source_cache.get('detected_markers', [])
|
|
324
|
+
|
|
325
|
+
if source == 'TDT':
|
|
326
|
+
# The raw per-wavelength channels (main driver, isosbestic, ...) are sample-aligned with
|
|
327
|
+
# x/raw/corr and must be trimmed/cut identically or they'd end up the wrong length (and
|
|
328
|
+
# showing the wrong span of samples) after this splice — 'normalized' is excluded since it's
|
|
329
|
+
# already the freshly-spliced 'corr' below.
|
|
330
|
+
source_signals = source_cache.get('signals', {})
|
|
331
|
+
extra_channels = {k: sig['y'] for k, sig in source_signals.items() if k != 'normalized'}
|
|
332
|
+
|
|
333
|
+
result = splice_fn(x, source_cache['raw'], source_cache['corr'],
|
|
334
|
+
markers, detected_markers, start, end, extra_channels=extra_channels)
|
|
335
|
+
if result is None:
|
|
336
|
+
return None
|
|
337
|
+
|
|
338
|
+
raw_out, corr_out = result['raw'], result['corr']
|
|
339
|
+
|
|
340
|
+
# Only possible when the raw main-driver channel survived the splice above (every TDT
|
|
341
|
+
# recording has one — see process_tdt_folder — so this is really just a defensive check).
|
|
342
|
+
if 'main_driver' in result['extra_channels']:
|
|
343
|
+
y_465 = result['extra_channels']['main_driver']
|
|
344
|
+
y_415 = result['extra_channels'].get('isosbestic')
|
|
345
|
+
computed = compute_dff(y_465, y_415, source_cache['fs'],
|
|
346
|
+
regression_method=regression_method, progress=progress)
|
|
347
|
+
raw_out, corr_out = computed['raw'], computed['corr']
|
|
348
|
+
inlier_fraction = computed.get('motion_correction_inlier_fraction')
|
|
349
|
+
else:
|
|
350
|
+
inlier_fraction = source_cache.get('motion_correction_inlier_fraction')
|
|
351
|
+
|
|
352
|
+
spliced = dict(source_cache)
|
|
353
|
+
spliced['motion_correction_inlier_fraction'] = inlier_fraction # of the fit on what is left
|
|
354
|
+
spliced['x'] = result['x']
|
|
355
|
+
spliced['raw'] = raw_out
|
|
356
|
+
spliced['corr'] = corr_out
|
|
357
|
+
spliced['markers'] = result['markers']
|
|
358
|
+
spliced['detected_markers'] = result['detected_markers']
|
|
359
|
+
if source_signals:
|
|
360
|
+
spliced['signals'] = {
|
|
361
|
+
key: {**sig, 'y': corr_out if key == 'normalized' else result['extra_channels'][key]}
|
|
362
|
+
for key, sig in source_signals.items()
|
|
363
|
+
}
|
|
364
|
+
return spliced
|
|
365
|
+
|
|
366
|
+
if source == 'Oxysoft':
|
|
367
|
+
# No single raw/corr pair here — the detector arrays (each shape (n_channels, n_samples)) ARE
|
|
368
|
+
# the signal, so they go through extra_channels instead; x is passed as a throwaway raw/corr
|
|
369
|
+
# placeholder since the function requires something 1D there, but result['raw']/['corr'] are
|
|
370
|
+
# never read back out below.
|
|
371
|
+
extra_channels = {'o2hb': source_cache['o2hb'], 'hhb': source_cache['hhb']}
|
|
372
|
+
if 'thb' in source_cache:
|
|
373
|
+
extra_channels['thb'] = source_cache['thb']
|
|
374
|
+
|
|
375
|
+
result = splice_fn(x, x, x, markers, detected_markers, start, end,
|
|
376
|
+
extra_channels=extra_channels)
|
|
377
|
+
if result is None:
|
|
378
|
+
return None
|
|
379
|
+
|
|
380
|
+
spliced = dict(source_cache)
|
|
381
|
+
spliced['x'] = result['x']
|
|
382
|
+
spliced['o2hb'] = result['extra_channels']['o2hb']
|
|
383
|
+
spliced['hhb'] = result['extra_channels']['hhb']
|
|
384
|
+
if 'thb' in source_cache:
|
|
385
|
+
spliced['thb'] = result['extra_channels']['thb']
|
|
386
|
+
spliced['markers'] = result['markers']
|
|
387
|
+
spliced['detected_markers'] = result['detected_markers']
|
|
388
|
+
return spliced
|
|
389
|
+
|
|
390
|
+
if source == 'Generic':
|
|
391
|
+
# y_columns are the signal(s) — same throwaway-placeholder reasoning as Oxysoft above.
|
|
392
|
+
extra_channels = dict(source_cache['y_columns'])
|
|
393
|
+
|
|
394
|
+
result = splice_fn(x, x, x, markers, detected_markers, start, end,
|
|
395
|
+
extra_channels=extra_channels)
|
|
396
|
+
if result is None:
|
|
397
|
+
return None
|
|
398
|
+
|
|
399
|
+
spliced = dict(source_cache)
|
|
400
|
+
spliced['x'] = result['x']
|
|
401
|
+
spliced['y_columns'] = result['extra_channels']
|
|
402
|
+
spliced['markers'] = result['markers']
|
|
403
|
+
spliced['detected_markers'] = result['detected_markers']
|
|
404
|
+
return spliced
|
|
405
|
+
|
|
406
|
+
return None
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def spliced_store_name(base_name, splices):
|
|
410
|
+
"""Store label reflecting every splice currently applied, in order — derived fresh from the
|
|
411
|
+
splice list each time (rather than appending a tag onto whatever the previous label happened to
|
|
412
|
+
be) so it stays correct after one is removed."""
|
|
413
|
+
if not splices:
|
|
414
|
+
return base_name
|
|
415
|
+
tags = ", ".join(
|
|
416
|
+
f"{'cut' if s['mode'] == MODE_CUT_OUT else 'kept'} {s['start']:.1f}s-{s['end']:.1f}s"
|
|
417
|
+
for s in splices
|
|
418
|
+
)
|
|
419
|
+
return f"{base_name} [{tags}]"
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def apply_splices(cache, splices, regression_method="ols", progress=None):
|
|
423
|
+
"""Replays a saved list of splices on `cache`, in order, each on top of the one before (splices
|
|
424
|
+
stack). A splice whose range leaves too little (fewer than 2 samples) is skipped, as the app does.
|
|
425
|
+
|
|
426
|
+
Returns (spliced_cache, applied): the final cache (its 'store' tagged with every applied splice;
|
|
427
|
+
`cache` itself is untouched) and the list of {"mode", "start", "end"} that took effect. With
|
|
428
|
+
nothing applied, the cache comes back as given."""
|
|
429
|
+
plan = Plan(progress, [(f"Splice {i + 1} of {len(splices)}", 1) for i in range(len(splices))])
|
|
430
|
+
base_name = cache['store']
|
|
431
|
+
current, applied = cache, []
|
|
432
|
+
for i, s in enumerate(splices):
|
|
433
|
+
spliced = apply_splice(current, s["mode"], s["start"], s["end"], regression_method=regression_method,
|
|
434
|
+
progress=plan.sub(f"Splice {i + 1} of {len(splices)}"))
|
|
435
|
+
if spliced is None:
|
|
436
|
+
continue
|
|
437
|
+
applied.append({"mode": s["mode"], "start": s["start"], "end": s["end"]})
|
|
438
|
+
spliced['store'] = spliced_store_name(base_name, applied)
|
|
439
|
+
current = spliced
|
|
440
|
+
return current, applied
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
# ---------------------------------------------------------------------------
|
|
444
|
+
# Loading
|
|
445
|
+
# ---------------------------------------------------------------------------
|
|
446
|
+
|
|
447
|
+
def load_tdt_recording(folder_path, regression_method="ols", use_saved=True, progress=None):
|
|
448
|
+
"""Loads a TDT block the way the app does: processed to dF/F, the recording's saved splices
|
|
449
|
+
replayed (each re-fits the dF/F), then its saved markers put on top. Nothing is written.
|
|
450
|
+
|
|
451
|
+
Parameters
|
|
452
|
+
----------
|
|
453
|
+
use_saved : bool
|
|
454
|
+
False skips the JSON saves/ folder entirely (the recording exactly as recorded).
|
|
455
|
+
progress : None, True or callable(fraction, message)
|
|
456
|
+
See PyATCLI.progress.
|
|
457
|
+
|
|
458
|
+
Returns
|
|
459
|
+
-------
|
|
460
|
+
dict with
|
|
461
|
+
cache the recording after splices and saved markers (see the module docstring)
|
|
462
|
+
original_cache the unspliced cache, or None if no splice was applied (what the app keeps to
|
|
463
|
+
be able to restore the full recording)
|
|
464
|
+
splices the splices that took effect, in order
|
|
465
|
+
warnings saved files that could not be read (the recording is then used without them)
|
|
466
|
+
Raises ValueError if the folder is not a readable TDT block.
|
|
467
|
+
"""
|
|
468
|
+
plan = Plan(progress, [("Reading and processing", 8), ("Applying saved splices", 2)])
|
|
469
|
+
valid, message = validate_tdt_folder(folder_path)
|
|
470
|
+
if not valid:
|
|
471
|
+
raise ValueError(message)
|
|
472
|
+
|
|
473
|
+
result = process_tdt_folder(folder_path, regression_method=regression_method,
|
|
474
|
+
progress=plan.sub("Reading and processing"))
|
|
475
|
+
cache = make_tdt_cache(folder_path, result)
|
|
476
|
+
original_cache, applied, warnings = None, [], []
|
|
477
|
+
if use_saved:
|
|
478
|
+
cache, original_cache, applied, warnings = _restore_saved_state(
|
|
479
|
+
cache, folder_path, regression_method, progress=plan.sub("Applying saved splices"))
|
|
480
|
+
plan.done()
|
|
481
|
+
return {"cache": cache, "original_cache": original_cache, "splices": applied, "warnings": warnings}
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _restore_saved_state(cache, source_path, regression_method, progress=None):
|
|
485
|
+
"""What every loader does last: replay the recording's saved splices (each re-fits the dF/F for TDT) and
|
|
486
|
+
put its saved markers on top. Returns (cache, original_cache, applied, warnings)."""
|
|
487
|
+
warnings = []
|
|
488
|
+
try:
|
|
489
|
+
splices = read_saved_splices(source_path)
|
|
490
|
+
except Exception as e: # noqa: BLE001 - an unreadable file must not stop the load
|
|
491
|
+
warnings.append(f"Saved splices could not be read ({e}); the recording is used as recorded.")
|
|
492
|
+
splices = []
|
|
493
|
+
original, applied = None, []
|
|
494
|
+
if splices:
|
|
495
|
+
spliced, applied = apply_splices(cache, splices, regression_method=regression_method, progress=progress)
|
|
496
|
+
if applied:
|
|
497
|
+
original, cache = cache, spliced
|
|
498
|
+
try:
|
|
499
|
+
cache["markers"] = read_saved_markers(source_path) # replaces the (empty) list, after the splices
|
|
500
|
+
except Exception as e: # noqa: BLE001
|
|
501
|
+
warnings.append(f"Saved markers could not be read ({e}); only the recorded events are used.")
|
|
502
|
+
for key, filename, noun in (("highlights", HIGHLIGHTS_FILE, "highlights"), ("text_annotations", TEXT_ANNOTATIONS_FILE, "text boxes")):
|
|
503
|
+
try: # not set at all when nothing is saved, as the app leaves them
|
|
504
|
+
if os.path.exists(annotation_sidecar_path(source_path, filename)):
|
|
505
|
+
cache[key] = read_saved_annotations(source_path, filename)
|
|
506
|
+
except Exception as e: # noqa: BLE001
|
|
507
|
+
warnings.append(f"Saved {noun} could not be read ({e}); the recording is used without them.")
|
|
508
|
+
try:
|
|
509
|
+
labels = read_saved_signal_labels(source_path)
|
|
510
|
+
apply_signal_labels(cache, labels)
|
|
511
|
+
if original is not None:
|
|
512
|
+
apply_signal_labels(original, labels) # so restoring the full recording keeps the names
|
|
513
|
+
except Exception as e: # noqa: BLE001
|
|
514
|
+
warnings.append(f"Saved signal names could not be read ({e}); the default names are used.")
|
|
515
|
+
return cache, original, applied, warnings
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def load_recording(path, regression_method="ols", use_saved=True, table=None, x_column=None, y_columns=None, progress=None):
|
|
519
|
+
"""Opens any recording the app can: a TDT folder, an Oxysoft .txt export, or a generic table file, the way
|
|
520
|
+
the app does — with its saved splices replayed and its saved markers on top (`use_saved=False` skips both).
|
|
521
|
+
Returns what load_tdt_recording returns: {"cache", "original_cache", "splices", "warnings"}.
|
|
522
|
+
|
|
523
|
+
For a generic file (Excel, CSV, TSV, text) `table` names which of its tables to open (needed only if it has
|
|
524
|
+
more than one), `x_column` its x column (default the first) and `y_columns` the traces (default every other
|
|
525
|
+
column). `regression_method` matters for TDT only. Raises ValueError with what is wrong if the path is
|
|
526
|
+
not a recording it can open."""
|
|
527
|
+
from .sources.dataset import DataFormat, detect_format_file
|
|
528
|
+
from .sources.load import load_dataset_file
|
|
529
|
+
from .sources.tables import load_any_file
|
|
530
|
+
|
|
531
|
+
if os.path.isdir(path):
|
|
532
|
+
return load_tdt_recording(path, regression_method=regression_method, use_saved=use_saved, progress=progress)
|
|
533
|
+
if not os.path.isfile(path):
|
|
534
|
+
raise ValueError(f"{path} does not exist")
|
|
535
|
+
if detect_format_file(path) == DataFormat.OXYSOFT:
|
|
536
|
+
cache = make_oxysoft_cache(path, load_dataset_file(path, progress=progress))
|
|
537
|
+
else:
|
|
538
|
+
tables = load_any_file(path, progress=progress)
|
|
539
|
+
if table is None and len(tables) > 1:
|
|
540
|
+
raise ValueError(f"{os.path.basename(path)} holds {len(tables)} tables ({', '.join(t.name for t in tables)}); "
|
|
541
|
+
"say which one to open")
|
|
542
|
+
chosen = next((t for t in tables if t.name == table), None) if table is not None else tables[0]
|
|
543
|
+
if chosen is None:
|
|
544
|
+
raise ValueError(f"{os.path.basename(path)} has no table named {table!r}; it has: {', '.join(t.name for t in tables)}")
|
|
545
|
+
headers = list(chosen.headers)
|
|
546
|
+
x_name = x_column if x_column is not None else headers[0]
|
|
547
|
+
bad = [c for c in [x_name] + list(y_columns or []) if c not in headers]
|
|
548
|
+
if bad:
|
|
549
|
+
raise ValueError(f"column(s) {bad} are not in table {chosen.name!r}; its columns: {', '.join(headers)}")
|
|
550
|
+
y_idx = [headers.index(c) for c in y_columns] if y_columns else None
|
|
551
|
+
cache = make_generic_cache(path, chosen, headers.index(x_name), y_idx)
|
|
552
|
+
if not use_saved:
|
|
553
|
+
return {"cache": cache, "original_cache": None, "splices": [], "warnings": []}
|
|
554
|
+
cache, original, applied, warnings = _restore_saved_state(cache, path, regression_method, progress)
|
|
555
|
+
return {"cache": cache, "original_cache": original, "splices": applied, "warnings": warnings}
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
# ---------------------------------------------------------------------------
|
|
559
|
+
# Finding recordings
|
|
560
|
+
# ---------------------------------------------------------------------------
|
|
561
|
+
|
|
562
|
+
def find_tdt_recordings(path):
|
|
563
|
+
"""Every valid TDT block anywhere under `path`, at any depth, sorted — a cohort folder
|
|
564
|
+
containing per-subcohort folders that each contain the actual per-animal/per-session TDT blocks
|
|
565
|
+
is a real lab layout, not just a flat one level down, so this walks the whole subtree rather than
|
|
566
|
+
just path's immediate children. Anything that's never a valid TDT block anywhere in the tree
|
|
567
|
+
(other folders, loose files of any type) is silently skipped, not reported, same as
|
|
568
|
+
validate_tdt_folder already does for a single folder. `path` itself is not tested (a caller that
|
|
569
|
+
wants it checks validate_tdt_folder first).
|
|
570
|
+
|
|
571
|
+
Stops descending once a directory is confirmed to be a TDT block itself (topdown os.walk,
|
|
572
|
+
pruning `dirs` in place) — its own internal files/subfolders are TDT's, not further recordings
|
|
573
|
+
to find, and there's no reason to keep walking into them.
|
|
574
|
+
|
|
575
|
+
Guards against a directory cycle (a folder that links back to one of its own ancestors, so the
|
|
576
|
+
"further down" it looks like never bottoms out) by tracking each directory's *real*,
|
|
577
|
+
symlink/junction-resolved identity rather than trusting os.walk's own followlinks=False default —
|
|
578
|
+
confirmed by direct testing that that default does NOT catch a Windows NTFS junction cycle
|
|
579
|
+
(os.path.islink() simply returns False for a junction, unlike a real symlink), which would
|
|
580
|
+
otherwise have os.walk descend into the same real folder over and over, reporting it as more and
|
|
581
|
+
more distinct-looking "finds" each time, stopped only by accidentally hitting the OS's
|
|
582
|
+
path-length limit rather than by any real protection."""
|
|
583
|
+
found = []
|
|
584
|
+
visited_real_dirs = {os.path.realpath(path)}
|
|
585
|
+
for root, dirs, _files in os.walk(path):
|
|
586
|
+
kept = []
|
|
587
|
+
for name in dirs:
|
|
588
|
+
real = os.path.realpath(os.path.join(root, name))
|
|
589
|
+
if real in visited_real_dirs:
|
|
590
|
+
continue # cycle — this real directory was already walked
|
|
591
|
+
visited_real_dirs.add(real)
|
|
592
|
+
kept.append(name)
|
|
593
|
+
dirs[:] = kept
|
|
594
|
+
|
|
595
|
+
if root == path:
|
|
596
|
+
continue # the picked folder itself is the caller's to check
|
|
597
|
+
valid, _ = validate_tdt_folder(root)
|
|
598
|
+
if valid:
|
|
599
|
+
found.append(root)
|
|
600
|
+
dirs[:] = [] # don't walk into a confirmed TDT block's own contents
|
|
601
|
+
found.sort()
|
|
602
|
+
return found
|