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/splice.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""
|
|
2
|
+
splice.py
|
|
3
|
+
---------
|
|
4
|
+
Non-destructive time-range edits of a signal: trim to a range, or cut
|
|
5
|
+
one out and stitch the remainder back together. Pure array/dict
|
|
6
|
+
operations — no knowledge of any GUI's cache/context shape, just plain
|
|
7
|
+
x/raw/corr arrays and marker dicts (each with at least a 'time' key).
|
|
8
|
+
|
|
9
|
+
Two operations:
|
|
10
|
+
- keep_inside: the usual "trim to a window" splice.
|
|
11
|
+
- cut_out: removes a range from the middle and stitches the two
|
|
12
|
+
remaining pieces together. Everything after the cut is shifted
|
|
13
|
+
backward by the cut's duration so the timeline stays contiguous —
|
|
14
|
+
a gap in x would break every downstream analysis that assumes
|
|
15
|
+
uniform sampling (PETH windows, FFT, ...) right at the cut boundary.
|
|
16
|
+
Markers inside the removed range are dropped (that moment no longer
|
|
17
|
+
exists); markers after it are shifted by the same amount so they
|
|
18
|
+
stay aligned with the signal.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from .numeric import as_float64
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def slice_markers_keep_inside(markers, start, end):
|
|
27
|
+
"""Keeps original absolute timestamps (not re-zeroed to the splice
|
|
28
|
+
start) so every downstream analysis that reads times straight from
|
|
29
|
+
the marker dicts keeps working with no special-casing."""
|
|
30
|
+
return [dict(m) for m in markers if start <= m['time'] <= end]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def slice_markers_cut_out(markers, start, end, shift):
|
|
34
|
+
"""Drops markers inside the removed range; shifts the rest that fall
|
|
35
|
+
after it by `shift` (the cut's duration) to stay aligned with the
|
|
36
|
+
signal's new, contiguous timeline."""
|
|
37
|
+
out = []
|
|
38
|
+
for m in markers:
|
|
39
|
+
t = m['time']
|
|
40
|
+
if start < t < end:
|
|
41
|
+
continue
|
|
42
|
+
m = dict(m)
|
|
43
|
+
if t >= end:
|
|
44
|
+
m['time'] = t - shift
|
|
45
|
+
out.append(m)
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def splice_keep_inside(x, raw, corr, markers, detected_markers, start, end, extra_channels=None):
|
|
50
|
+
"""
|
|
51
|
+
Trims x/raw/corr to [start, end] and filters both marker lists to
|
|
52
|
+
the same range.
|
|
53
|
+
|
|
54
|
+
Parameters
|
|
55
|
+
----------
|
|
56
|
+
x, raw, corr : array
|
|
57
|
+
markers, detected_markers : list of dict, each with a 'time' key
|
|
58
|
+
start, end : float
|
|
59
|
+
extra_channels : dict of {name: array}, optional
|
|
60
|
+
Any other arrays aligned sample-for-sample with x on their LAST
|
|
61
|
+
axis (e.g. a recording's raw per-wavelength channels — main
|
|
62
|
+
driver, isosbestic — each 1D; or a multi-detector array like
|
|
63
|
+
Oxysoft's o2hb/hhb, shape (n_detectors, n_samples)) that also
|
|
64
|
+
need trimming to the same range. Sliced along axis=-1 so both
|
|
65
|
+
1D and 2D arrays work with no special-casing. Not required — a
|
|
66
|
+
caller with only x/raw/corr can omit it entirely.
|
|
67
|
+
|
|
68
|
+
Returns
|
|
69
|
+
-------
|
|
70
|
+
dict with x, raw, corr (copies, not views), markers,
|
|
71
|
+
detected_markers, n_samples, extra_channels (trimmed the same way,
|
|
72
|
+
{} if none were given) — or None if the range doesn't contain at
|
|
73
|
+
least 2 samples.
|
|
74
|
+
"""
|
|
75
|
+
x, raw, corr = as_float64(x), as_float64(raw), as_float64(corr)
|
|
76
|
+
extra_channels = {name: as_float64(y) for name, y in (extra_channels or {}).items()}
|
|
77
|
+
i0 = int(np.searchsorted(x, start, side='left'))
|
|
78
|
+
i1 = int(np.searchsorted(x, end, side='right'))
|
|
79
|
+
if i1 - i0 < 2:
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
"x": x[i0:i1].copy(),
|
|
84
|
+
"raw": raw[i0:i1].copy(),
|
|
85
|
+
"corr": corr[i0:i1].copy(),
|
|
86
|
+
"markers": slice_markers_keep_inside(markers, start, end),
|
|
87
|
+
"detected_markers": slice_markers_keep_inside(detected_markers, start, end),
|
|
88
|
+
"n_samples": i1 - i0,
|
|
89
|
+
"extra_channels": {name: y[..., i0:i1].copy() for name, y in (extra_channels or {}).items()},
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def splice_cut_out(x, raw, corr, markers, detected_markers, start, end, extra_channels=None):
|
|
94
|
+
"""
|
|
95
|
+
Removes [start, end] from x/raw/corr and stitches the remainder
|
|
96
|
+
together, shifting everything after the cut backward by the cut's
|
|
97
|
+
duration so the timeline stays contiguous. Markers inside the cut
|
|
98
|
+
are dropped; markers after it are shifted by the same amount.
|
|
99
|
+
|
|
100
|
+
The cut is allowed to touch either edge of the recording — cutting
|
|
101
|
+
from x[0] up to some end point, or from some start point to x[-1],
|
|
102
|
+
needs no stitching at all (one side is simply empty) and works the
|
|
103
|
+
same as the general case below; it doesn't need special-casing
|
|
104
|
+
beyond not indexing x[i1] when i1 lands past the last sample.
|
|
105
|
+
|
|
106
|
+
Parameters
|
|
107
|
+
----------
|
|
108
|
+
x, raw, corr : array
|
|
109
|
+
markers, detected_markers : list of dict, each with a 'time' key
|
|
110
|
+
start, end : float
|
|
111
|
+
extra_channels : dict of {name: array}, optional
|
|
112
|
+
Any other arrays aligned sample-for-sample with x on their LAST
|
|
113
|
+
axis that also need the same range cut out and stitched — see
|
|
114
|
+
splice_keep_inside (1D and 2D, e.g. Oxysoft's multi-detector
|
|
115
|
+
arrays, both work).
|
|
116
|
+
|
|
117
|
+
Returns
|
|
118
|
+
-------
|
|
119
|
+
dict with x, raw, corr, markers, detected_markers, n_samples,
|
|
120
|
+
extra_channels (cut/stitched the same way, {} if none were given) —
|
|
121
|
+
or None if fewer than 2 samples would remain overall (matches
|
|
122
|
+
splice_keep_inside's own minimum).
|
|
123
|
+
"""
|
|
124
|
+
x, raw, corr = as_float64(x), as_float64(raw), as_float64(corr)
|
|
125
|
+
extra_channels = {name: as_float64(y) for name, y in (extra_channels or {}).items()}
|
|
126
|
+
i0 = int(np.searchsorted(x, start, side='left'))
|
|
127
|
+
i1 = int(np.searchsorted(x, end, side='right'))
|
|
128
|
+
if i1 <= i0:
|
|
129
|
+
return None
|
|
130
|
+
if i0 + (len(x) - i1) < 2:
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
# cut duration, used to reconnect the timeline — 0 when the cut runs
|
|
134
|
+
# to the very end, since there's nothing after it to shift anyway
|
|
135
|
+
shift = float(x[i1] - x[i0]) if i1 < len(x) else 0.0
|
|
136
|
+
new_x = np.concatenate([x[:i0], x[i1:] - shift])
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
"x": new_x,
|
|
140
|
+
"raw": np.concatenate([raw[:i0], raw[i1:]]),
|
|
141
|
+
"corr": np.concatenate([corr[:i0], corr[i1:]]),
|
|
142
|
+
"markers": slice_markers_cut_out(markers, start, end, shift),
|
|
143
|
+
"detected_markers": slice_markers_cut_out(detected_markers, start, end, shift),
|
|
144
|
+
"n_samples": len(new_x),
|
|
145
|
+
"extra_channels": {name: np.concatenate([y[..., :i0], y[..., i1:]], axis=-1)
|
|
146
|
+
for name, y in (extra_channels or {}).items()},
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
MODE_CUT_OUT = "cut_out"
|
|
151
|
+
MODE_KEEP_INSIDE = "keep_inside"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def replay_splices(x, splices, markers=None, detected_markers=None):
|
|
155
|
+
"""
|
|
156
|
+
Replays a saved list of splices on a time axis and marker lists, without
|
|
157
|
+
touching any signal: the x / marker side of what PyAT does when it restores
|
|
158
|
+
a recording's splice.json. Group analysis uses it to know where each
|
|
159
|
+
recording's events sit after the splices, and how long the recording
|
|
160
|
+
now is, without loading and re-fitting the signal.
|
|
161
|
+
|
|
162
|
+
It goes through splice_cut_out / splice_keep_inside themselves (x stands in
|
|
163
|
+
for the raw and corr arrays they require), so the result is exactly what
|
|
164
|
+
the full replay gives for x and the markers — including the last-digit
|
|
165
|
+
details of the time shift, which matter when markers saved after a splice
|
|
166
|
+
(markers.json) are matched against the re-derived ones.
|
|
167
|
+
|
|
168
|
+
Parameters
|
|
169
|
+
----------
|
|
170
|
+
x : array
|
|
171
|
+
The recording's time axis before any splice.
|
|
172
|
+
splices : list of {"mode", "start", "end"}
|
|
173
|
+
In the order they were applied; "mode" is MODE_CUT_OUT ("cut_out") or,
|
|
174
|
+
for anything else, MODE_KEEP_INSIDE ("keep_inside") — the same reading PyAT
|
|
175
|
+
gives it. A splice whose range leaves fewer than 2 samples is skipped, as
|
|
176
|
+
PyAT does (the recording stays as it was before that one).
|
|
177
|
+
markers, detected_markers : list of dict, optional
|
|
178
|
+
Each with a 'time' key, on the pre-splice timeline.
|
|
179
|
+
|
|
180
|
+
Returns
|
|
181
|
+
-------
|
|
182
|
+
dict with x, markers, detected_markers (after the splices) and applied (how
|
|
183
|
+
many of the splices took effect).
|
|
184
|
+
"""
|
|
185
|
+
x = np.asarray(x)
|
|
186
|
+
markers = list(markers or [])
|
|
187
|
+
detected_markers = list(detected_markers or [])
|
|
188
|
+
applied = 0
|
|
189
|
+
for s in splices:
|
|
190
|
+
splice = splice_cut_out if s["mode"] == MODE_CUT_OUT else splice_keep_inside
|
|
191
|
+
result = splice(x, x, x, markers, detected_markers, s["start"], s["end"])
|
|
192
|
+
if result is None:
|
|
193
|
+
continue
|
|
194
|
+
x, markers, detected_markers = result["x"], result["markers"], result["detected_markers"]
|
|
195
|
+
applied += 1
|
|
196
|
+
return {"x": x, "markers": markers, "detected_markers": detected_markers, "applied": applied}
|
PyATCLI/viewplan.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""
|
|
2
|
+
viewplan.py
|
|
3
|
+
-----------
|
|
4
|
+
What the main plot of a recording shows, as data: which lines it has (under what name, with what numbers), the range it is looking at, the markers
|
|
5
|
+
in it, and the title and axis labels it would carry. The numbers of an Export View are this — `analyses.run_view` replays them without a window or a
|
|
6
|
+
plotting library, and a viewer (PyAT's main plot, both its engines, and Export View) draws it.
|
|
7
|
+
|
|
8
|
+
plan = viewplan.plan_view(cache, signals=["normalized", "main_driver"], xlim=(40, 120))
|
|
9
|
+
plan.data_table() every sample in view, the time and a column per line
|
|
10
|
+
plan.markers_table() the markers in view
|
|
11
|
+
plan.parameters() what it takes to make this plan again (a provenance record's parameters)
|
|
12
|
+
|
|
13
|
+
How a line is drawn — its colour, width, marker, the figure it ends up in — is the viewer's business: a `Trace` carries the `role` it plays
|
|
14
|
+
("signal", "o2hb_mean", "column", ...) and the `signal` key and `color` the recording itself gives it, and the viewer styles it from those.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
from .analysis.shared import mean_channels
|
|
23
|
+
from .markers import marker_display_label
|
|
24
|
+
|
|
25
|
+
FULL_VIEW_PADDING_FRAC = 0.02 # 2% of the data span on each side of a "show everything" view
|
|
26
|
+
|
|
27
|
+
# What a line is, for a viewer that styles by it.
|
|
28
|
+
ROLE_SIGNAL = "signal" # a TDT signal (`signal` is its key in the recording's `signals`)
|
|
29
|
+
ROLE_CORRECTED = "corrected" # the corrected trace of a source with no signals map
|
|
30
|
+
ROLE_O2HB_CHANNEL, ROLE_HHB_CHANNEL = "o2hb_channel", "hhb_channel" # one NIRS channel
|
|
31
|
+
ROLE_O2HB_MEAN, ROLE_HHB_MEAN, ROLE_THB_MEAN = "o2hb_mean", "hhb_mean", "thb_mean" # the mean of the NIRS channels
|
|
32
|
+
ROLE_COLUMN = "column" # one column of a generic table, in the order the table has them
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def padded_xlim(x):
|
|
36
|
+
"""(lo, hi) for "fit the full trace with a little breathing room": an exact-bounds range leaves the trace flush against the edges of the
|
|
37
|
+
plot. Used for every "show everything" moment."""
|
|
38
|
+
lo, hi = float(x[0]), float(x[-1])
|
|
39
|
+
pad = (hi - lo) * FULL_VIEW_PADDING_FRAC
|
|
40
|
+
if pad == 0:
|
|
41
|
+
pad = 1.0 # degenerate single-point/flat data — avoid a zero-width range
|
|
42
|
+
return lo - pad, hi + pad
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Trace:
|
|
47
|
+
"""One line of the main plot. `x`/`y` are what is shown; `y_full` the same signal over the recording's whole time axis (NaN where there
|
|
48
|
+
is none), which is what the data CSV is made of. `label` is the legend name ("_nolegend_" for a channel that follows its group's
|
|
49
|
+
entry) and `key` the name a viewer files per-line choices under (a group's unnamed lines follow the group's)."""
|
|
50
|
+
label: str
|
|
51
|
+
x: np.ndarray
|
|
52
|
+
y: np.ndarray
|
|
53
|
+
csv_name: str
|
|
54
|
+
y_full: np.ndarray = None
|
|
55
|
+
key: str = None
|
|
56
|
+
role: str = ROLE_SIGNAL
|
|
57
|
+
signal: str = None # a TDT signal's key in cache["signals"]
|
|
58
|
+
color: str = None # the colour the recording itself gives the signal, if it gives one
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def view_traces(cache, *, signals=None, active=None):
|
|
62
|
+
"""(traces, title, x label, y label) for what the main plot shows for a recording, before any edit of its title, labels or legend.
|
|
63
|
+
|
|
64
|
+
signals a TDT recording's signals ticked in the Plot menu (keys of cache["signals"]: "normalized", "main_driver",
|
|
65
|
+
"isosbestic", ...); more than one are overlaid, in the recording's order. Default: "normalized".
|
|
66
|
+
active the signal shown when only one is — default: the one ticked (or the first the recording has)
|
|
67
|
+
"""
|
|
68
|
+
x = cache['x']
|
|
69
|
+
source = cache.get('source')
|
|
70
|
+
traces = []
|
|
71
|
+
|
|
72
|
+
def add(label, y, role, csv_name=None, key=None, **kw):
|
|
73
|
+
traces.append(Trace(label, kw.pop("x", x), y, csv_name or label, y_full=kw.pop("y_full", y), key=key if key is not None else label,
|
|
74
|
+
role=role, **kw))
|
|
75
|
+
|
|
76
|
+
if source == 'Oxysoft':
|
|
77
|
+
o2hb, hhb = cache['o2hb'], cache['hhb']
|
|
78
|
+
for i in range(o2hb.shape[0]):
|
|
79
|
+
add('O2Hb channels' if i == 0 else '_nolegend_', o2hb[i], ROLE_O2HB_CHANNEL, f"O2Hb ch{i + 1}", key='O2Hb channels')
|
|
80
|
+
add('HHb channels' if i == 0 else '_nolegend_', hhb[i], ROLE_HHB_CHANNEL, f"HHb ch{i + 1}", key='HHb channels')
|
|
81
|
+
ff = cache.get('fit_factor_mean')
|
|
82
|
+
ff_tag = f" [FF: {ff:.1f}%]" if ff is not None else ""
|
|
83
|
+
add(f'Mean O2Hb{ff_tag}', mean_channels(o2hb), ROLE_O2HB_MEAN)
|
|
84
|
+
add(f'Mean HHb{ff_tag}', mean_channels(hhb), ROLE_HHB_MEAN)
|
|
85
|
+
if 'thb' in cache:
|
|
86
|
+
add(f'Mean tHb{ff_tag}', mean_channels(cache['thb']), ROLE_THB_MEAN)
|
|
87
|
+
return traces, f"NIRS — {cache['store']}", "Time (s)", "Delta Concentration (uM)"
|
|
88
|
+
|
|
89
|
+
if source == 'Generic':
|
|
90
|
+
for col_name, y in cache['y_columns'].items():
|
|
91
|
+
mask = ~np.isnan(y)
|
|
92
|
+
add(col_name, y[mask], ROLE_COLUMN, x=x[mask], y_full=y)
|
|
93
|
+
return traces, cache['store'], cache.get('x_label', 'X'), "Value"
|
|
94
|
+
|
|
95
|
+
available = cache.get('signals') or {}
|
|
96
|
+
ticked = list(signals) if signals is not None else ["normalized"]
|
|
97
|
+
if source == 'TDT' and len(ticked) > 1:
|
|
98
|
+
checked = [(k, sig) for k, sig in available.items() if k in ticked]
|
|
99
|
+
if not checked and available: # nothing ticked that the recording has: the one a single view would show
|
|
100
|
+
key = active if active in available else next(iter(available))
|
|
101
|
+
checked = [(key, available[key])]
|
|
102
|
+
for key, sig in checked:
|
|
103
|
+
add(sig['label'], sig['y'], ROLE_SIGNAL, signal=key, color=sig.get('color'))
|
|
104
|
+
return traces, f"Overlay ({len(checked)}) — {cache['store']}", "Time (s)", "Amplitude"
|
|
105
|
+
|
|
106
|
+
if not available: # a source with no signals map: its corrected trace, else its raw one
|
|
107
|
+
add("dF/F (corrected)", (cache['corr'] if 'corr' in cache else cache['raw']), ROLE_CORRECTED)
|
|
108
|
+
label = "dF/F (corrected)"
|
|
109
|
+
else:
|
|
110
|
+
want = active if active is not None else (ticked[0] if ticked else "normalized")
|
|
111
|
+
key = want if want in available else next(iter(available))
|
|
112
|
+
label = available[key]['label']
|
|
113
|
+
add(label, available[key]['y'], ROLE_SIGNAL, signal=key, color=available[key].get('color'))
|
|
114
|
+
return traces, f"{label} — {cache['store']}", "Time (s)", "Amplitude"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class ViewPlan:
|
|
119
|
+
"""A view of a recording: the lines (`traces`), the range, the markers in it. `attributes` is whatever the viewer says it was drawn with
|
|
120
|
+
(a title, labels, colours...): carried into `parameters()` as it is, never interpreted here."""
|
|
121
|
+
traces: list
|
|
122
|
+
xlim: tuple
|
|
123
|
+
ylim: tuple
|
|
124
|
+
x_name: str
|
|
125
|
+
x: np.ndarray
|
|
126
|
+
markers: list = field(default_factory=list) # [(time, label, colour)] in view
|
|
127
|
+
signals: list = None # a TDT recording's signals shown, in the recording's order
|
|
128
|
+
show_grid: bool = True
|
|
129
|
+
title: str = ""
|
|
130
|
+
x_label: str = ""
|
|
131
|
+
y_label: str = ""
|
|
132
|
+
in_view: list = field(default_factory=list) # the marker dicts in view
|
|
133
|
+
attributes: dict = field(default_factory=dict)
|
|
134
|
+
|
|
135
|
+
def parameters(self):
|
|
136
|
+
"""What it takes to make this view again (analyses.run_view): the range, the signals, the grid and the attributes. JSON-ready."""
|
|
137
|
+
return {"x_range": list(self.xlim), "y_range": list(self.ylim) if self.ylim is not None else None, "signals": self.signals,
|
|
138
|
+
"show_grid": bool(self.show_grid), "attributes": self.attributes, "traces": [t.csv_name for t in self.traces]}
|
|
139
|
+
|
|
140
|
+
def data_table(self):
|
|
141
|
+
"""One row per sample in view: the time (or x) and a column per trace, at the recording's full resolution."""
|
|
142
|
+
lo, hi = self.xlim
|
|
143
|
+
mask = (self.x >= lo) & (self.x <= hi)
|
|
144
|
+
columns = {self.x_name: self.x[mask]}
|
|
145
|
+
for t in self.traces:
|
|
146
|
+
name, n = t.csv_name, 2
|
|
147
|
+
while name in columns:
|
|
148
|
+
name, n = f"{t.csv_name} ({n})", n + 1
|
|
149
|
+
columns[name] = np.asarray(t.y_full)[mask]
|
|
150
|
+
return pd.DataFrame(columns)
|
|
151
|
+
|
|
152
|
+
def markers_table(self):
|
|
153
|
+
"""The markers in view: time, shown name, colour (no rows if there are none)."""
|
|
154
|
+
return pd.DataFrame(self.markers, columns=[self.x_name, "label", "color"])
|
|
155
|
+
|
|
156
|
+
def write_data(self, base):
|
|
157
|
+
"""<base>_data.csv (every sample in view) and, if any marker is in view, <base>_markers.csv. Returns the paths."""
|
|
158
|
+
paths = [f"{base}_data.csv"]
|
|
159
|
+
self.data_table().to_csv(paths[0], index=False, encoding="utf-8")
|
|
160
|
+
if self.markers:
|
|
161
|
+
paths.append(f"{base}_markers.csv")
|
|
162
|
+
self.markers_table().to_csv(paths[1], index=False, encoding="utf-8")
|
|
163
|
+
return paths
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def plan_view(cache, *, signals=None, active=None, xlim=None, ylim=None, show_grid=True, store_labels=None, attributes=None):
|
|
167
|
+
"""What the main plot shows of `cache` (a recording, as load_recording returns it): the traces, the range, the markers in it, the title and
|
|
168
|
+
labels. `signals`, `active`: see view_traces. `xlim`, `ylim`: the range, (low, high); default all of the recording with a little room,
|
|
169
|
+
and the y range follows the data. `store_labels`: {store id: shown name}, the renames in force for marker names. `attributes`: what the
|
|
170
|
+
viewer drew it with, kept for `parameters()`."""
|
|
171
|
+
traces, title, x_label, y_label = view_traces(cache, signals=signals, active=active)
|
|
172
|
+
lo, hi = (float(min(xlim)), float(max(xlim))) if xlim is not None else padded_xlim(cache['x'])
|
|
173
|
+
ylim = (float(min(ylim)), float(max(ylim))) if ylim is not None else None
|
|
174
|
+
in_view = [m for m in cache.get('markers', []) if lo <= m['time'] <= hi]
|
|
175
|
+
x_name = "time_s" if cache.get('source') in ('TDT', 'Oxysoft') else (cache.get('x_label') or 'x')
|
|
176
|
+
markers = [(m['time'], marker_display_label(m, store_labels), m['color']) for m in in_view]
|
|
177
|
+
available = cache.get('signals') or {}
|
|
178
|
+
ticked = list(signals) if signals is not None else ["normalized"]
|
|
179
|
+
shown = [k for k in available if k in ticked] if cache.get('source') == 'TDT' else None
|
|
180
|
+
return ViewPlan(traces, (lo, hi), ylim, x_name, cache['x'], markers, signals=shown, show_grid=bool(show_grid), title=title,
|
|
181
|
+
x_label=x_label, y_label=y_label, in_view=in_view, attributes=dict(attributes or {}))
|