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/analyses.py
ADDED
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analyses.py
|
|
3
|
+
-----------
|
|
4
|
+
Every analysis PyAT offers, as a function of a recording and a plain parameter dict — so the same
|
|
5
|
+
analysis can be run from the app, from a script (`run_analysis`), from the command line
|
|
6
|
+
(`python -m PyATCLI run ...`), and replayed from a provenance record (reproduce.py), and all
|
|
7
|
+
four give the same numbers.
|
|
8
|
+
|
|
9
|
+
result = pl.run_analysis("event_peth", cache, {"event": "L1P¹", "pre_s": 10, "post_s": 20})
|
|
10
|
+
result.tables["zscore"] # a DataFrame
|
|
11
|
+
result.parameters # the parameters as run, defaults filled in — what a provenance record stores
|
|
12
|
+
|
|
13
|
+
`cache` is a recording as recording.py builds it (load_tdt_recording(...)["cache"], make_oxysoft_cache, ...).
|
|
14
|
+
Each table has the same columns, in the same order, as the CSV the app exports for that analysis, so
|
|
15
|
+
a script's output can be compared with an export column for column (reproduce.py does exactly that).
|
|
16
|
+
|
|
17
|
+
The analyses (describe_kinds() lists them with every parameter):
|
|
18
|
+
|
|
19
|
+
zscore_window z-score a window around one time (the Analysis menu's Z-Score)
|
|
20
|
+
auc_window area under the curve in a window (AUC)
|
|
21
|
+
fft_window spectrum and top peaks of a window (FFT)
|
|
22
|
+
curve_fit fit a model to the stretch between two times (Curve Fit)
|
|
23
|
+
event_peth every occurrence of one event aligned to it: trials, mean/SEM, AUC, peak, bins (Event PETH)
|
|
24
|
+
peak_finder statistically significant peaks (Find Significant Peaks)
|
|
25
|
+
event_intervals time between markers (Measure Intervals)
|
|
26
|
+
process the processed traces themselves (dF/F and the raw channels)
|
|
27
|
+
|
|
28
|
+
Group analysis is the one analysis that is not a function of one recording: it runs from a GroupSpec over
|
|
29
|
+
several (run_group_from_spec below, analysis/group/run.py's run_group_analysis, `python -m PyATCLI group`).
|
|
30
|
+
|
|
31
|
+
Not recording data: `parameters` and `summary` hold what was asked and a few numbers; the arrays are in the tables.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
import math
|
|
35
|
+
import re
|
|
36
|
+
from dataclasses import dataclass, field
|
|
37
|
+
|
|
38
|
+
import numpy as np
|
|
39
|
+
import pandas as pd
|
|
40
|
+
|
|
41
|
+
from .analysis import (
|
|
42
|
+
compute_auc_from_trace, compute_auc_matrix, compute_auc_window, compute_event_zscore_peth, compute_fft_slice,
|
|
43
|
+
compute_group_stats, compute_marker_intervals, compute_peri_event_from_trace, compute_peri_event_matrix,
|
|
44
|
+
find_fft_peaks, find_peak_near_events, find_significant_peaks, fit_model_to_segment, get_zscore_slice,
|
|
45
|
+
mean_channels, smooth_signal,
|
|
46
|
+
)
|
|
47
|
+
from .analysis.group import GroupSpec
|
|
48
|
+
from .analysis.group.report import trace_frame
|
|
49
|
+
from .analysis.group.run import GROUP_SETTINGS_FILENAME, run_group_analysis
|
|
50
|
+
from .markers import group_markers_by_name
|
|
51
|
+
from .models import CURVE_FIT_MODELS
|
|
52
|
+
from .numeric import as_float64
|
|
53
|
+
from .recording import normalized_signal
|
|
54
|
+
|
|
55
|
+
DEFAULT_WINDOW_S = 15.0 # the app's own default analysis window, each side of the point
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ParameterError(ValueError):
|
|
59
|
+
"""A parameter is missing, unknown, or has a value the analysis cannot use."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class AnalysisError(RuntimeError):
|
|
63
|
+
"""The parameters were fine but the recording does not hold enough to run the analysis (a window past
|
|
64
|
+
the end of the recording, an event with no usable trial, ...)."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class AnalysisResult:
|
|
69
|
+
kind: str
|
|
70
|
+
parameters: dict
|
|
71
|
+
tables: dict
|
|
72
|
+
summary: dict = field(default_factory=dict)
|
|
73
|
+
notes: list = field(default_factory=list)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class Param:
|
|
78
|
+
name: str
|
|
79
|
+
type: str # float | int | str | bool | floats | ints | markers | groups | choice
|
|
80
|
+
default: object = None
|
|
81
|
+
required: bool = False
|
|
82
|
+
doc: str = ""
|
|
83
|
+
choices: tuple = ()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class Analysis:
|
|
88
|
+
kind: str
|
|
89
|
+
summary: str
|
|
90
|
+
params: tuple
|
|
91
|
+
fn: object
|
|
92
|
+
tables: dict = field(default_factory=dict)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
_REGISTRY = {}
|
|
96
|
+
|
|
97
|
+
# What each analysis returns: its tables by name, and the columns of each that are ALWAYS there — a reader may ask for them by name and
|
|
98
|
+
# count on them. A table can have more columns than are listed (a column per time bin, a column per signal, columns that only some settings
|
|
99
|
+
# make), and more can be added at any time. Removing or renaming a listed column, or a table, breaks callers: that is a new PROTOCOL_VERSION
|
|
100
|
+
# (ops/__init__.py), and engine/contract.py and tests/test_engine_contract.py are what notice it.
|
|
101
|
+
TABLES = {
|
|
102
|
+
"zscore_window": {
|
|
103
|
+
"window": ["Channel", "time_from_center_s", "z_score"],
|
|
104
|
+
"peaks": ["Channel", "Peak Z-score", "Peak time from center (s)"],
|
|
105
|
+
},
|
|
106
|
+
"auc_window": {
|
|
107
|
+
"auc": ["Channel", "Total AUC", "Positive AUC", "Negative AUC", "Window Pre (s)", "Window Post (s)"],
|
|
108
|
+
"window": ["Channel", "time_from_center_s", "value"],
|
|
109
|
+
},
|
|
110
|
+
"fft_window": {
|
|
111
|
+
"peaks": ["Channel", "Peak Rank", "Frequency (Hz)", "BPM", "Power"],
|
|
112
|
+
"spectrum": ["Channel", "frequency_hz", "power"],
|
|
113
|
+
},
|
|
114
|
+
"curve_fit": {
|
|
115
|
+
"fit": ["Channel", "Model", "Parameter", "Value", "R2", "t1 (s)", "t2 (s)", "dt (s)"],
|
|
116
|
+
"curve": ["Channel", "Model", "time_s", "value", "fit"],
|
|
117
|
+
"context": ["Channel", "time_s", "value"],
|
|
118
|
+
},
|
|
119
|
+
"event_peth": {
|
|
120
|
+
"zscore": ["time_from_event_s", "z_score"],
|
|
121
|
+
"mean_sem": ["time_from_event_s", "mean", "sem"],
|
|
122
|
+
"trials": ["Trial", "Trial Event Time (s)", "time_from_event_s", "z_score"],
|
|
123
|
+
"auc": ["Trial", "Trial Event Time (s)", "Total AUC", "Positive AUC", "Negative AUC", "Checked"],
|
|
124
|
+
"peak": ["Trial", "Trial Event Time (s)", "Peak Amplitude", "Time-to-Peak (s)", "Checked"],
|
|
125
|
+
"bins": ["Trial", "Trial Event Time (s)", "Checked"], # (and a "Bin a-bs Mean" column per time bin)
|
|
126
|
+
},
|
|
127
|
+
"peak_finder": { # which tables there are depends on `scope`
|
|
128
|
+
"peaks": ["time_s", "z_score", "kind"], # whole
|
|
129
|
+
"alignment": ["Event Time (s)", "Found", "Latency (s)", "Z-score"], # one_event, all_same_name, scan_all
|
|
130
|
+
"scan": ["Event", "Occurrences", "Found", "Hit Rate", "Avg Z (found only)"], # scan_all
|
|
131
|
+
},
|
|
132
|
+
"event_intervals": {
|
|
133
|
+
"intervals": ["time_s", "store", "label", "phase", "dt_since_prev_same_store_s", "dt_since_prev_any_s"],
|
|
134
|
+
},
|
|
135
|
+
"process": {
|
|
136
|
+
"trace": ["time_s"], # (and a column per signal)
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# What else the library writes as tables, besides an analysis's own: a group analysis's folder and an Export View's data. Declared like TABLES
|
|
142
|
+
# (the columns that are always there) and, for a folder, the file each table is written to; in the engine's contract (engine/contract.py) too.
|
|
143
|
+
VIEW_TABLES = {
|
|
144
|
+
"data": [], # the x column (time_s for a TDT or Oxysoft recording), then a column per trace
|
|
145
|
+
"markers": ["label", "color"], # (and the x column first); only when there are markers in view
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def describe_outputs():
|
|
150
|
+
"""{name: {"summary", "tables": {table: [the columns that are always there]}, "files": {table or role: file name in the folder}}} for what
|
|
151
|
+
is written besides an analysis's tables: "group_analysis" (a group's results folder) and "view" (an Export View's tables)."""
|
|
152
|
+
from .analysis.group.report import GROUP_TABLES, NOTES_FILENAME, REPORT_FILENAME, TABLE_FILES
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
GROUP_KIND: {"summary": "a group analysis's results folder: every table as a CSV beside the settings it was run from, a report and its notes",
|
|
156
|
+
"tables": {name: list(cols) for name, cols in GROUP_TABLES.items()},
|
|
157
|
+
"files": {**TABLE_FILES, "settings": GROUP_SETTINGS_FILENAME, "report": REPORT_FILENAME, "notes": NOTES_FILENAME}},
|
|
158
|
+
VIEW_KIND: {"summary": "an Export View's numbers: every sample in view, and the markers in view",
|
|
159
|
+
"tables": {name: list(cols) for name, cols in VIEW_TABLES.items()}, "files": {}},
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def analysis(kind, summary, params):
|
|
164
|
+
def register(fn):
|
|
165
|
+
_REGISTRY[kind] = Analysis(kind, summary, tuple(params), fn, {name: tuple(cols) for name, cols in TABLES.get(kind, {}).items()})
|
|
166
|
+
return fn
|
|
167
|
+
return register
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def kinds():
|
|
171
|
+
"""The analyses that can be run, in the order they are listed above."""
|
|
172
|
+
return tuple(_REGISTRY)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def describe_kinds():
|
|
176
|
+
"""{kind: {"summary", "parameters": [{"name", "type", "default", "required", "doc", "choices"}], "tables": {name: [the columns that are
|
|
177
|
+
always there]}} — for help text, documentation and the engine's contract (engine/contract.py)."""
|
|
178
|
+
return {
|
|
179
|
+
k: {"summary": a.summary, "parameters": [
|
|
180
|
+
{"name": p.name, "type": p.type, "default": p.default, "required": p.required, "doc": p.doc,
|
|
181
|
+
"choices": list(p.choices)} for p in a.params],
|
|
182
|
+
"tables": {name: list(cols) for name, cols in a.tables.items()}}
|
|
183
|
+
for k, a in _REGISTRY.items()
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ---------------------------------------------------------------------------
|
|
188
|
+
# Parameters
|
|
189
|
+
# ---------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
def _coerce(p, value):
|
|
192
|
+
try:
|
|
193
|
+
if p.type == "float":
|
|
194
|
+
v = float(value)
|
|
195
|
+
if not math.isfinite(v):
|
|
196
|
+
raise ValueError("not finite")
|
|
197
|
+
return v
|
|
198
|
+
if p.type == "int":
|
|
199
|
+
if isinstance(value, float) and not value.is_integer():
|
|
200
|
+
raise ValueError("not a whole number")
|
|
201
|
+
return int(value)
|
|
202
|
+
if p.type == "bool":
|
|
203
|
+
if isinstance(value, str):
|
|
204
|
+
if value.lower() in ("true", "yes", "1", "on"):
|
|
205
|
+
return True
|
|
206
|
+
if value.lower() in ("false", "no", "0", "off"):
|
|
207
|
+
return False
|
|
208
|
+
raise ValueError("not true/false")
|
|
209
|
+
return bool(value)
|
|
210
|
+
if p.type == "str":
|
|
211
|
+
return str(value)
|
|
212
|
+
if p.type == "floats":
|
|
213
|
+
if isinstance(value, str):
|
|
214
|
+
value = [v for v in re.split(r"[,\s]+", value.strip()) if v]
|
|
215
|
+
vals = [float(v) for v in value]
|
|
216
|
+
if not all(math.isfinite(v) for v in vals):
|
|
217
|
+
raise ValueError("not finite")
|
|
218
|
+
return vals
|
|
219
|
+
if p.type == "groups":
|
|
220
|
+
return {str(k): [float(t) for t in v] for k, v in dict(value).items()}
|
|
221
|
+
if p.type == "markers":
|
|
222
|
+
marks = [dict(m) for m in value]
|
|
223
|
+
for m in marks:
|
|
224
|
+
m["time"] = float(m["time"])
|
|
225
|
+
return marks
|
|
226
|
+
if p.type == "ints":
|
|
227
|
+
if isinstance(value, str):
|
|
228
|
+
value = [v for v in re.split(r"[,\s]+", value.strip()) if v]
|
|
229
|
+
return [int(v) for v in value]
|
|
230
|
+
if p.type == "choice":
|
|
231
|
+
if value not in p.choices:
|
|
232
|
+
raise ValueError(f"must be one of {', '.join(map(str, p.choices))}")
|
|
233
|
+
return value
|
|
234
|
+
except (TypeError, ValueError) as e:
|
|
235
|
+
raise ParameterError(f"{p.name}: {e} (got {value!r})") from None
|
|
236
|
+
raise ParameterError(f"{p.name}: unknown parameter type {p.type}")
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def normalize_parameters(kind, parameters=None):
|
|
240
|
+
"""`parameters` checked against the analysis's parameter list, with defaults filled in. Raises
|
|
241
|
+
ParameterError for a missing required parameter, an unknown name or a bad value."""
|
|
242
|
+
if kind not in _REGISTRY:
|
|
243
|
+
raise ParameterError(f"Unknown analysis {kind!r}; expected one of {', '.join(_REGISTRY)}")
|
|
244
|
+
spec = {p.name: p for p in _REGISTRY[kind].params}
|
|
245
|
+
given = dict(parameters or {})
|
|
246
|
+
unknown = sorted(set(given) - set(spec))
|
|
247
|
+
if unknown:
|
|
248
|
+
raise ParameterError(f"{kind}: unknown parameter(s) {', '.join(unknown)}; valid: {', '.join(spec)}")
|
|
249
|
+
out = {}
|
|
250
|
+
for name, p in spec.items():
|
|
251
|
+
if name in given and given[name] is not None:
|
|
252
|
+
out[name] = _coerce(p, given[name])
|
|
253
|
+
elif p.required:
|
|
254
|
+
raise ParameterError(f"{kind}: {name} is required ({p.doc})")
|
|
255
|
+
else:
|
|
256
|
+
out[name] = p.default
|
|
257
|
+
return out
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def run_analysis(kind, cache, parameters=None, *, store_labels=None, progress=None):
|
|
261
|
+
"""Runs one analysis. `cache` is a recording (see the module docstring);
|
|
262
|
+
`store_labels` the store renames in effect, for analyses that name events. Returns an AnalysisResult."""
|
|
263
|
+
p = normalize_parameters(kind, parameters)
|
|
264
|
+
ctx = _Context(cache, store_labels or {}, progress)
|
|
265
|
+
tables, summary, notes = _REGISTRY[kind].fn(ctx, p)
|
|
266
|
+
p.update(ctx.resolved) # what the analysis looked up (event times, markers): the record is self-sufficient
|
|
267
|
+
result = AnalysisResult(kind, p, tables, summary, notes)
|
|
268
|
+
return result
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
@dataclass
|
|
272
|
+
class _Context:
|
|
273
|
+
cache: object
|
|
274
|
+
store_labels: dict
|
|
275
|
+
progress: object
|
|
276
|
+
resolved: dict = field(default_factory=dict) # parameters an analysis fills in from the recording
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
# ---------------------------------------------------------------------------
|
|
280
|
+
# What an analysis looks at
|
|
281
|
+
# ---------------------------------------------------------------------------
|
|
282
|
+
|
|
283
|
+
def signal_channels(cache, signal=None):
|
|
284
|
+
"""The (label, y) traces the click-triggered analyses work on: Oxysoft's mean O2Hb / HHb (/ tHb); for a TDT
|
|
285
|
+
recording the one signal named by `signal` (a key of cache["signals"], default the first); for a recording
|
|
286
|
+
with only a corrected trace, that; for a generic table its first column."""
|
|
287
|
+
if cache.get("source") == "Oxysoft":
|
|
288
|
+
out = [("Mean O2Hb", mean_channels(cache["o2hb"])), ("Mean HHb", mean_channels(cache["hhb"]))]
|
|
289
|
+
if "thb" in cache:
|
|
290
|
+
out.append(("Mean tHb", mean_channels(cache["thb"])))
|
|
291
|
+
return out
|
|
292
|
+
if "corr" in cache or "raw" in cache or cache.get("signals"):
|
|
293
|
+
signals = cache.get("signals")
|
|
294
|
+
if signals:
|
|
295
|
+
key = signal if signal in signals else next(iter(signals))
|
|
296
|
+
return [(signals[key]["label"], signals[key]["y"])]
|
|
297
|
+
return [("dF/F (corrected)", cache["corr"] if "corr" in cache else cache["raw"])]
|
|
298
|
+
return [("Signal", next(iter(cache["y_columns"].values())))]
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _frame(columns, rows):
|
|
302
|
+
return pd.DataFrame(rows, columns=columns)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
_SIGNAL = Param("signal", "str", "normalized", doc="which of the recording's signals (TDT: normalized, main_driver, isosbestic)")
|
|
306
|
+
_PRE = Param("pre_s", "float", DEFAULT_WINDOW_S, doc="seconds before the point")
|
|
307
|
+
_POST = Param("post_s", "float", DEFAULT_WINDOW_S, doc="seconds after the point")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
# ---------------------------------------------------------------------------
|
|
311
|
+
# Click-triggered window analyses
|
|
312
|
+
# ---------------------------------------------------------------------------
|
|
313
|
+
|
|
314
|
+
@analysis("zscore_window", "z-score a window around one time against its own pre-event baseline",
|
|
315
|
+
[Param("center_s", "float", required=True, doc="the time the window is centred on"), _PRE, _POST, _SIGNAL])
|
|
316
|
+
def _zscore_window(ctx, p):
|
|
317
|
+
cache, center = ctx.cache, p["center_s"]
|
|
318
|
+
x, fs = cache["x"], cache["fs"]
|
|
319
|
+
rows, peaks, notes = [], [], []
|
|
320
|
+
for label, y in signal_channels(cache, p["signal"]):
|
|
321
|
+
slice_x, z = get_zscore_slice(x, smooth_signal(y, fs), center, pre=p["pre_s"], post=p["post_s"])
|
|
322
|
+
if z is None or len(z) == 0:
|
|
323
|
+
notes.append(f"{label}: no samples in this window")
|
|
324
|
+
continue
|
|
325
|
+
i = int(np.argmax(np.abs(z)))
|
|
326
|
+
peaks.append([label, float(z[i]), float(slice_x[i] - center)])
|
|
327
|
+
rows += [[label, float(t - center), float(v)] for t, v in zip(slice_x, z)]
|
|
328
|
+
if not peaks:
|
|
329
|
+
raise AnalysisError("Not enough data in this window to compute a Z-score.")
|
|
330
|
+
tables = {"window": _frame(["Channel", "time_from_center_s", "z_score"], rows),
|
|
331
|
+
"peaks": _frame(["Channel", "Peak Z-score", "Peak time from center (s)"], peaks)}
|
|
332
|
+
return tables, {"peak_z": {r[0]: r[1] for r in peaks}}, notes
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
@analysis("auc_window", "area under the curve in a window, split by sign",
|
|
336
|
+
[Param("center_s", "float", required=True, doc="the time the window is centred on"), _PRE, _POST, _SIGNAL])
|
|
337
|
+
def _auc_window(ctx, p):
|
|
338
|
+
cache, center = ctx.cache, p["center_s"]
|
|
339
|
+
rows, window = [], []
|
|
340
|
+
for label, y in signal_channels(cache, p["signal"]):
|
|
341
|
+
r = compute_auc_window(cache["x"], y, center, p["pre_s"], p["post_s"])
|
|
342
|
+
rows.append([label, r["total_auc"], r["positive_auc"], r["negative_auc"], p["pre_s"], p["post_s"]])
|
|
343
|
+
window += [[label, float(t - center), float(v)] for t, v in zip(r["seg_x"], r["seg_y"])]
|
|
344
|
+
tables = {"auc": _frame(["Channel", "Total AUC", "Positive AUC", "Negative AUC", "Window Pre (s)", "Window Post (s)"], rows),
|
|
345
|
+
"window": _frame(["Channel", "time_from_center_s", "value"], window)}
|
|
346
|
+
return tables, {"total_auc": {r[0]: r[1] for r in rows}}, []
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@analysis("fft_window", "power spectrum of a window (mean and linear trend removed) and its top peaks",
|
|
350
|
+
[Param("center_s", "float", required=True, doc="the time the window is centred on"), _PRE, _POST, _SIGNAL])
|
|
351
|
+
def _fft_window(ctx, p):
|
|
352
|
+
cache = ctx.cache
|
|
353
|
+
peaks, spectrum = [], []
|
|
354
|
+
for label, y in signal_channels(cache, p["signal"]):
|
|
355
|
+
freqs, power, _, _ = compute_fft_slice(cache["x"], y, p["center_s"], cache["fs"], pre=p["pre_s"], post=p["post_s"])
|
|
356
|
+
found = find_fft_peaks(freqs, power) if len(freqs) > 0 else []
|
|
357
|
+
peaks += [[label, i + 1, pk["freq_hz"], pk["bpm"], pk["power"]] for i, pk in enumerate(found)]
|
|
358
|
+
spectrum += [[label, float(f), float(w)] for f, w in zip(freqs, power)]
|
|
359
|
+
tables = {"peaks": _frame(["Channel", "Peak Rank", "Frequency (Hz)", "BPM", "Power"], peaks),
|
|
360
|
+
"spectrum": _frame(["Channel", "frequency_hz", "power"], spectrum)}
|
|
361
|
+
return tables, {"n_peaks": len(peaks)}, []
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def curve_model_ids():
|
|
365
|
+
"""{short id: registry name} for the curve-fit models, e.g. {"linear": "Linear (y = mx + b)", ...}."""
|
|
366
|
+
return {re.sub(r"[^a-z0-9]+", "_", name.split("(")[0].lower()).strip("_"): name for name in CURVE_FIT_MODELS}
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def resolve_curve_model(name):
|
|
370
|
+
"""A curve-fit model's registry name from its registry name or short id ("exponential decay",
|
|
371
|
+
"exponential_decay", "Exponential Decay" all work). Raises ParameterError for an unknown one."""
|
|
372
|
+
if name in CURVE_FIT_MODELS:
|
|
373
|
+
return name
|
|
374
|
+
ids = curve_model_ids()
|
|
375
|
+
key = re.sub(r"[^a-z0-9]+", "_", str(name).lower()).strip("_")
|
|
376
|
+
if key in ids:
|
|
377
|
+
return ids[key]
|
|
378
|
+
raise ParameterError(f"model: unknown curve-fit model {name!r}; expected one of {', '.join(ids)}")
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
@analysis("curve_fit", "fit a model to the stretch of the signal between two times",
|
|
382
|
+
[Param("t1_s", "float", required=True, doc="start of the stretch (snapped to the nearest sample)"),
|
|
383
|
+
Param("t2_s", "float", required=True, doc="end of the stretch"),
|
|
384
|
+
Param("model", "str", "linear", doc="one of the curve_model_ids()"), _SIGNAL,
|
|
385
|
+
Param("window_s", "float", 30.0, doc="seconds of the signal around the stretch that the figure shows for context "
|
|
386
|
+
"(the `context` table); at least 1")])
|
|
387
|
+
def _curve_fit(ctx, p):
|
|
388
|
+
cache = ctx.cache
|
|
389
|
+
model_name = resolve_curve_model(p["model"])
|
|
390
|
+
model_fn, p0_fn, pnames = CURVE_FIT_MODELS[model_name]
|
|
391
|
+
x = cache["x"]
|
|
392
|
+
i1, i2 = sorted((int(np.argmin(np.abs(x - p["t1_s"]))), int(np.argmin(np.abs(x - p["t2_s"])))))
|
|
393
|
+
t1, t2 = float(x[i1]), float(x[i2])
|
|
394
|
+
# The wider view the figure shows around the stretch, as the app's Curve Fit window does: `window_s` seconds
|
|
395
|
+
# centred on the stretch, never narrower than the stretch itself.
|
|
396
|
+
half = max(1.0, p["window_s"]) / 2
|
|
397
|
+
t_mid = (t1 + t2) / 2
|
|
398
|
+
view_start = min(max(float(x[0]), t_mid - half), t1)
|
|
399
|
+
view_end = max(min(float(x[-1]), t_mid + half), t2)
|
|
400
|
+
w_start = int(np.searchsorted(x, view_start))
|
|
401
|
+
w_end = min(int(np.searchsorted(x, view_end)), len(x) - 1)
|
|
402
|
+
rows, curve, context, notes, r2s = [], [], [], [], {}
|
|
403
|
+
for label, y in signal_channels(cache, p["signal"]):
|
|
404
|
+
y = as_float64(y)
|
|
405
|
+
x_seg, y_seg = x[i1:i2 + 1], y[i1:i2 + 1]
|
|
406
|
+
if len(x_seg) < 4:
|
|
407
|
+
notes.append(f"{label}: fewer than 4 samples between the two times")
|
|
408
|
+
continue
|
|
409
|
+
context += [[label, float(tt), float(yy)] for tt, yy in zip(x[w_start:w_end + 1], y[w_start:w_end + 1])]
|
|
410
|
+
res = fit_model_to_segment(x_seg, y_seg, model_fn, p0_fn)
|
|
411
|
+
if not res["success"]:
|
|
412
|
+
notes.append(f"{label}: fit failed: {res['error']}")
|
|
413
|
+
curve += [[label, model_name, float(tt), float(yy), float("nan")] for tt, yy in zip(x_seg, y_seg)] # the stretch, no fit
|
|
414
|
+
continue
|
|
415
|
+
r2s[label] = float(res["r2"])
|
|
416
|
+
rows += [[label, model_name, n, float(v), float(res["r2"]), t1, t2, t2 - t1] for n, v in zip(pnames, res["popt"])]
|
|
417
|
+
curve += [[label, model_name, float(tt), float(yy), float(ff)] for tt, yy, ff in zip(x_seg, y_seg, res["y_fit"])]
|
|
418
|
+
tables = {"fit": _frame(["Channel", "Model", "Parameter", "Value", "R2", "t1 (s)", "t2 (s)", "dt (s)"], rows),
|
|
419
|
+
"curve": _frame(["Channel", "Model", "time_s", "value", "fit"], curve),
|
|
420
|
+
"context": _frame(["Channel", "time_s", "value"], context)}
|
|
421
|
+
return tables, {"r2": r2s, "model": model_name, "view": [view_start, view_end]}, notes
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
# ---------------------------------------------------------------------------
|
|
425
|
+
# Event-locked analyses
|
|
426
|
+
# ---------------------------------------------------------------------------
|
|
427
|
+
|
|
428
|
+
def _event_times(ctx, event, given):
|
|
429
|
+
if given:
|
|
430
|
+
return sorted(float(t) for t in given)
|
|
431
|
+
groups = group_markers_by_name(ctx.cache, ctx.store_labels)
|
|
432
|
+
if event not in groups:
|
|
433
|
+
shown = ", ".join(sorted(groups)[:20]) + (" ..." if len(groups) > 20 else "")
|
|
434
|
+
raise ParameterError(f"event: no event named {event!r} in this recording; it has: {shown or 'none'}")
|
|
435
|
+
return groups[event]
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
@analysis("event_peth", "align every occurrence of one event: trials, mean/SEM, AUC, peak and time bins per trial and for the group",
|
|
439
|
+
[Param("event", "str", required=True, doc="the event's name as listed (e.g. L1P¹, or a note's text)"),
|
|
440
|
+
Param("pre_s", "float", DEFAULT_WINDOW_S, doc="seconds before each event"),
|
|
441
|
+
Param("post_s", "float", DEFAULT_WINDOW_S, doc="seconds after each event"),
|
|
442
|
+
Param("bin_s", "float", 1.0, doc="width of the post-event mean-time bins"),
|
|
443
|
+
Param("selected_trials", "ints", None, doc="1-based trial numbers to include in the group statistics (default: all)"),
|
|
444
|
+
Param("event_times", "floats", None, doc="use these event times instead of looking the event up (what a record stores)")])
|
|
445
|
+
def _event_peth(ctx, p):
|
|
446
|
+
cache = ctx.cache
|
|
447
|
+
pre, post, bin_s = p["pre_s"], p["post_s"], max(0.01, p["bin_s"])
|
|
448
|
+
if pre <= 0 or post <= 0:
|
|
449
|
+
raise ParameterError("pre_s and post_s must be positive")
|
|
450
|
+
times = _event_times(ctx, p["event"], p["event_times"])
|
|
451
|
+
ctx.resolved["event_times"] = [float(t) for t in times]
|
|
452
|
+
_, _, y = normalized_signal(cache)
|
|
453
|
+
clean = smooth_signal(y, cache["fs"])
|
|
454
|
+
res = compute_event_zscore_peth(cache["x"], clean, times, pre, post, progress=ctx.progress)
|
|
455
|
+
matrix, axis, trial_times = res["trial_matrix"], res["time_axis"], res["trial_event_times"]
|
|
456
|
+
n_total = matrix.shape[0]
|
|
457
|
+
if n_total == 0:
|
|
458
|
+
raise AnalysisError(f"No usable trials for '{p['event']}' — all occurrences were too close to the "
|
|
459
|
+
"start/end of the recording for the current window.")
|
|
460
|
+
wanted = p["selected_trials"]
|
|
461
|
+
if wanted is None:
|
|
462
|
+
selected = list(range(n_total))
|
|
463
|
+
else:
|
|
464
|
+
bad = [n for n in wanted if not 1 <= n <= n_total]
|
|
465
|
+
if bad:
|
|
466
|
+
raise ParameterError(f"selected_trials: trial(s) {bad} do not exist; there are {n_total} usable trials")
|
|
467
|
+
selected = sorted({n - 1 for n in wanted})
|
|
468
|
+
sub = matrix[selected] if selected else matrix[:0]
|
|
469
|
+
mean, sem = compute_group_stats(sub)
|
|
470
|
+
per_auc = compute_auc_matrix(axis, matrix)["per_trial"]
|
|
471
|
+
per_peri = compute_peri_event_matrix(axis, matrix, post, bin_s)["per_trial"]
|
|
472
|
+
g_auc = compute_auc_from_trace(axis, mean) if selected else {"total_auc": 0.0, "positive_auc": 0.0, "negative_auc": 0.0}
|
|
473
|
+
g_peri = compute_peri_event_from_trace(axis, mean, post, bin_s) if selected else {"peak_amplitude": 0.0, "latency": 0.0, "mean_bins": []}
|
|
474
|
+
checked = set(selected)
|
|
475
|
+
GROUP = "GROUP (checked only)"
|
|
476
|
+
|
|
477
|
+
trials = [[i + 1, float(trial_times[i]), float(t), float(v)] for i in selected for t, v in zip(axis, matrix[i])]
|
|
478
|
+
auc_rows = [[i + 1, float(t), a["total_auc"], a["positive_auc"], a["negative_auc"], i in checked]
|
|
479
|
+
for i, (t, a) in enumerate(zip(trial_times, per_auc))]
|
|
480
|
+
auc_rows.append([GROUP, None, g_auc["total_auc"], g_auc["positive_auc"], g_auc["negative_auc"], None])
|
|
481
|
+
peak_rows = [[i + 1, float(t), q["peak_amplitude"], q["latency"], i in checked] for i, (t, q) in enumerate(zip(trial_times, per_peri))]
|
|
482
|
+
peak_rows.append([GROUP, None, g_peri["peak_amplitude"], g_peri["latency"], None])
|
|
483
|
+
edges = per_peri[0]["mean_bins"]
|
|
484
|
+
bin_cols = [f"Bin {b['bin_start']:.1f}-{b['bin_end']:.1f}s Mean" for b in edges]
|
|
485
|
+
bin_rows = [[i + 1, float(t)] + [b["mean"] for b in q["mean_bins"]] + [i in checked] for i, (t, q) in enumerate(zip(trial_times, per_peri))]
|
|
486
|
+
g_bins = [b["mean"] for b in g_peri["mean_bins"]]
|
|
487
|
+
bin_rows.append([GROUP, None] + g_bins + [None] * (len(edges) - len(g_bins)) + [None])
|
|
488
|
+
|
|
489
|
+
tables = {
|
|
490
|
+
"zscore": _frame(["time_from_event_s", "z_score"], list(zip(map(float, axis), map(float, mean)))),
|
|
491
|
+
"mean_sem": _frame(["time_from_event_s", "mean", "sem"], list(zip(map(float, axis), map(float, mean), map(float, sem)))),
|
|
492
|
+
"trials": _frame(["Trial", "Trial Event Time (s)", "time_from_event_s", "z_score"], trials),
|
|
493
|
+
"auc": _frame(["Trial", "Trial Event Time (s)", "Total AUC", "Positive AUC", "Negative AUC", "Checked"], auc_rows),
|
|
494
|
+
"peak": _frame(["Trial", "Trial Event Time (s)", "Peak Amplitude", "Time-to-Peak (s)", "Checked"], peak_rows),
|
|
495
|
+
"bins": _frame(["Trial", "Trial Event Time (s)"] + bin_cols + ["Checked"], bin_rows),
|
|
496
|
+
}
|
|
497
|
+
summary = {"n_trials": n_total, "n_selected": len(selected), "n_events": len(times),
|
|
498
|
+
"group_peak": g_peri["peak_amplitude"], "group_latency_s": g_peri["latency"], "group_auc": g_auc["total_auc"]}
|
|
499
|
+
notes = [f"{len(times) - n_total} of {len(times)} occurrences were too close to the recording's edges and were skipped"] \
|
|
500
|
+
if n_total < len(times) else []
|
|
501
|
+
return tables, summary, notes
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
@analysis("peak_finder", "statistically significant peaks: across the whole recording, or near events",
|
|
505
|
+
[Param("scope", "choice", "whole", choices=("whole", "one_event", "all_same_name", "scan_all"),
|
|
506
|
+
doc="whole: peaks anywhere; one_event / all_same_name: is there a peak near the event(s); scan_all: every event type"),
|
|
507
|
+
Param("z_threshold", "float", 5.0, doc="minimum z-score for a peak to count"),
|
|
508
|
+
Param("min_distance_s", "float", 1.0, doc="minimum spacing between peaks (scope whole)"),
|
|
509
|
+
Param("include_troughs", "bool", False, doc="also consider negative dips"),
|
|
510
|
+
Param("event", "str", None, doc="the event's name (scope all_same_name)"),
|
|
511
|
+
Param("event_time", "float", None, doc="the event's time (scope one_event)"),
|
|
512
|
+
Param("event_times", "floats", None, doc="use these event times instead of looking the event up"),
|
|
513
|
+
Param("event_groups", "groups", None, doc="scope scan_all: {event name: times} to scan instead of the recording's own "
|
|
514
|
+
"(what a record stores)"),
|
|
515
|
+
_PRE, _POST])
|
|
516
|
+
def _peak_finder(ctx, p):
|
|
517
|
+
cache = ctx.cache
|
|
518
|
+
_, _, y = normalized_signal(cache)
|
|
519
|
+
clean = smooth_signal(y, cache["fs"])
|
|
520
|
+
x, scope, thr, tr = cache["x"], p["scope"], p["z_threshold"], p["include_troughs"]
|
|
521
|
+
ALIGN = ["Event Time (s)", "Found", "Latency (s)", "Z-score"]
|
|
522
|
+
|
|
523
|
+
def align_rows(results):
|
|
524
|
+
return [[r["event_time"], r["found"], r["latency"] if r["found"] else None, r["z_score"] if r["found"] else None] for r in results]
|
|
525
|
+
|
|
526
|
+
if scope == "whole":
|
|
527
|
+
peaks = find_significant_peaks(x, clean, z_threshold=thr, min_distance_sec=p["min_distance_s"], include_troughs=tr)
|
|
528
|
+
return ({"peaks": _frame(["time_s", "z_score", "kind"], [[q["time"], q["z_score"], q["kind"]] for q in peaks])},
|
|
529
|
+
{"n_peaks": len(peaks)}, [])
|
|
530
|
+
if scope == "one_event":
|
|
531
|
+
if p["event_time"] is None and not p["event_times"]:
|
|
532
|
+
raise ParameterError("peak_finder: scope one_event needs event_time")
|
|
533
|
+
times = p["event_times"] or [p["event_time"]]
|
|
534
|
+
elif scope == "all_same_name":
|
|
535
|
+
if not p["event"] and not p["event_times"]:
|
|
536
|
+
raise ParameterError("peak_finder: scope all_same_name needs event")
|
|
537
|
+
times = _event_times(ctx, p["event"], p["event_times"])
|
|
538
|
+
else:
|
|
539
|
+
times = None
|
|
540
|
+
if times is not None:
|
|
541
|
+
ctx.resolved["event_times"] = [float(t) for t in times]
|
|
542
|
+
results = find_peak_near_events(x, clean, times, p["pre_s"], p["post_s"], z_threshold=thr, include_troughs=tr, progress=ctx.progress)
|
|
543
|
+
return ({"alignment": _frame(ALIGN, align_rows(results))},
|
|
544
|
+
{"n_events": len(results), "n_found": sum(1 for r in results if r["found"])}, [])
|
|
545
|
+
groups = p["event_groups"] if p["event_groups"] is not None else group_markers_by_name(cache, ctx.store_labels)
|
|
546
|
+
ctx.resolved["event_groups"] = {name: [float(t) for t in times] for name, times in groups.items()}
|
|
547
|
+
by_event = {name: find_peak_near_events(x, clean, t, p["pre_s"], p["post_s"], z_threshold=thr, include_troughs=tr)
|
|
548
|
+
for name, t in groups.items()}
|
|
549
|
+
scan = []
|
|
550
|
+
for name, results in by_event.items():
|
|
551
|
+
found = [r for r in results if r["found"]]
|
|
552
|
+
scan.append([name, len(results), len(found), len(found) / len(results) if results else 0.0,
|
|
553
|
+
sum(r["z_score"] for r in found) / len(found) if found else None])
|
|
554
|
+
scan.sort(key=lambda r: r[3], reverse=True)
|
|
555
|
+
detail = [[name] + row for name, results in by_event.items() for row in align_rows(results)]
|
|
556
|
+
return ({"scan": _frame(["Event", "Occurrences", "Found", "Hit Rate", "Avg Z (found only)"], scan),
|
|
557
|
+
"alignment": _frame(["Event"] + ALIGN, detail)},
|
|
558
|
+
{"n_event_types": len(by_event)}, [])
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
@analysis("event_intervals", "the time between markers: since the previous of the same store, and of any",
|
|
562
|
+
[Param("markers", "markers", None, doc="the markers to measure, [{time, store, label, phase}, ...] "
|
|
563
|
+
"(default: the recording's own markers; a record stores what was measured)")])
|
|
564
|
+
def _event_intervals(ctx, p):
|
|
565
|
+
markers = p["markers"] if p["markers"] is not None else ctx.cache.get("markers", [])
|
|
566
|
+
if not markers:
|
|
567
|
+
raise AnalysisError("No markers currently on the plot to measure.")
|
|
568
|
+
rows = compute_marker_intervals(markers)
|
|
569
|
+
ctx.resolved["markers"] = [{k: m.get(k) for k in ("time", "store", "label", "phase")} for m in markers]
|
|
570
|
+
table = _frame(["time_s", "store", "label", "phase", "dt_since_prev_same_store_s", "dt_since_prev_any_s"],
|
|
571
|
+
[[r["time"], r["store"], r["label"], r["phase"], r["dt_store"], r["dt_global"]] for r in rows])
|
|
572
|
+
return {"intervals": table}, {"n_markers": len(rows)}, []
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
# ---------------------------------------------------------------------------
|
|
576
|
+
# Whole-recording outputs
|
|
577
|
+
# ---------------------------------------------------------------------------
|
|
578
|
+
|
|
579
|
+
@analysis("process", "the processed traces themselves: dF/F and the raw per-wavelength channels",
|
|
580
|
+
[Param("signals", "str", None, doc="comma-separated signal keys (default: every one the recording offers)")])
|
|
581
|
+
def _process(ctx, p):
|
|
582
|
+
cache = ctx.cache
|
|
583
|
+
signals = cache.get("signals")
|
|
584
|
+
if signals:
|
|
585
|
+
keys = [k.strip() for k in p["signals"].split(",")] if p["signals"] else list(signals)
|
|
586
|
+
missing = [k for k in keys if k not in signals]
|
|
587
|
+
if missing:
|
|
588
|
+
raise ParameterError(f"signals: no signal(s) {missing}; the recording has {list(signals)}")
|
|
589
|
+
cols = {k: as_float64(signals[k]["y"]) for k in keys}
|
|
590
|
+
elif cache.get("source") == "Oxysoft":
|
|
591
|
+
cols = {f"O2Hb {i + 1}": row for i, row in enumerate(cache["o2hb"])}
|
|
592
|
+
cols.update({f"HHb {i + 1}": row for i, row in enumerate(cache["hhb"])})
|
|
593
|
+
elif "y_columns" in cache:
|
|
594
|
+
cols = dict(cache["y_columns"])
|
|
595
|
+
else:
|
|
596
|
+
cols = {"signal": normalized_signal(cache)[2]}
|
|
597
|
+
table = pd.DataFrame({"time_s": as_float64(cache["x"]), **cols})
|
|
598
|
+
return {"trace": table}, {"n_samples": len(table), "columns": list(cols)}, []
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def run_group_from_spec(spec, out_dir=None, progress=None):
|
|
602
|
+
"""The group analysis for a GroupSpec or its dict (what analysis_settings.json holds), as an AnalysisResult
|
|
603
|
+
whose tables are the group's result tables. Writes the tables, report to `out_dir` if given."""
|
|
604
|
+
spec = spec if isinstance(spec, GroupSpec) else GroupSpec.from_dict(spec)
|
|
605
|
+
problems = spec.problems()
|
|
606
|
+
if problems:
|
|
607
|
+
raise ParameterError("The group settings are not usable: " + " ".join(problems))
|
|
608
|
+
results = run_group_analysis(spec, out_dir=out_dir, progress=progress)
|
|
609
|
+
tables = {k: v for k, v in results.frames().items() if len(v)}
|
|
610
|
+
traces = trace_frame(results) if isinstance(getattr(results, "traces", None), dict) else None
|
|
611
|
+
if traces is not None and len(traces):
|
|
612
|
+
tables["mean_traces"] = traces # what mean_traces.csv holds; PyAT draws it
|
|
613
|
+
notes = [n["text"] for n in results.notes]
|
|
614
|
+
result = AnalysisResult("group_analysis", spec.to_dict(), tables, {"files": results.files}, notes)
|
|
615
|
+
return result, results
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
GROUP_KIND = "group_analysis" # the kind a provenance record of a group analysis carries
|
|
619
|
+
VIEW_KIND = "view" # the kind a provenance record of an Export View carries
|
|
620
|
+
VIEW_PARAMETERS = ("x_range", "y_range", "signals", "show_grid", "attributes", "traces")
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def run_view(cache, parameters=None, *, store_labels=None):
|
|
624
|
+
"""The numbers of an Export View, as an AnalysisResult: `tables["data"]` is the CSV beside the figure — every sample in view, the
|
|
625
|
+
time and a column per trace — and `tables["markers"]` the markers in view (when there are any). `parameters` are a view's
|
|
626
|
+
(viewplan.ViewPlan.parameters(): "x_range", "y_range", "signals", "show_grid", "attributes"); none shows all of the recording.
|
|
627
|
+
"attributes" is whatever the viewer drew the view with (a title, labels, colours): kept as it is, it changes no number.
|
|
628
|
+
This is what `reproduce` runs for a "view" record: nothing is drawn."""
|
|
629
|
+
from . import viewplan
|
|
630
|
+
|
|
631
|
+
p = dict(parameters or {})
|
|
632
|
+
unknown = sorted(set(p) - set(VIEW_PARAMETERS))
|
|
633
|
+
if unknown:
|
|
634
|
+
raise ParameterError(f"a view has no parameter {', '.join(map(repr, unknown))}; its parameters are: {', '.join(VIEW_PARAMETERS)}")
|
|
635
|
+
view = viewplan.plan_view(cache, signals=p.get("signals"), xlim=p.get("x_range"), ylim=p.get("y_range"), show_grid=p.get("show_grid", True),
|
|
636
|
+
store_labels=store_labels, attributes=p.get("attributes"))
|
|
637
|
+
tables = {"data": view.data_table()}
|
|
638
|
+
if view.markers:
|
|
639
|
+
tables["markers"] = view.markers_table()
|
|
640
|
+
return AnalysisResult(VIEW_KIND, view.parameters(), tables, {"samples": len(tables["data"]), "traces": [t.csv_name for t in view.traces]}, [])
|