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
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analysis/intervals.py
|
|
3
|
+
-----------------------
|
|
4
|
+
Time-since-previous-marker, for the Measure Intervals tool.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def compute_marker_intervals(markers):
|
|
9
|
+
"""
|
|
10
|
+
Time-since-previous-marker, two ways, for a list of already-placed
|
|
11
|
+
markers — universal to any marker source (TDT epocs, Oxysoft events,
|
|
12
|
+
manually-placed), since it only looks at each marker's own 'time'/
|
|
13
|
+
'store'/'label'/'phase' keys, not any format-specific structure.
|
|
14
|
+
|
|
15
|
+
For a store with alternating high/low phases (e.g. a pump or lever),
|
|
16
|
+
a low marker's dt_store IS its on-duration (time since its own high).
|
|
17
|
+
For a store with no phase concept, dt_store is just the interval
|
|
18
|
+
since that store's last event. dt_global is the interval since
|
|
19
|
+
whatever marker came before it, regardless of store — useful when
|
|
20
|
+
several event types are interleaved. No special-casing for phase is
|
|
21
|
+
needed — both columns are computed the same generic way (diff
|
|
22
|
+
against the previous timestamp in the relevant sequence), and
|
|
23
|
+
duration falls out of that automatically wherever high/low pairs
|
|
24
|
+
happen to alternate.
|
|
25
|
+
|
|
26
|
+
Parameters
|
|
27
|
+
----------
|
|
28
|
+
markers : list of dict, each with at least 'time' and 'label' keys,
|
|
29
|
+
optionally 'store' (falls back to 'label' if absent) and 'phase'.
|
|
30
|
+
|
|
31
|
+
Returns
|
|
32
|
+
-------
|
|
33
|
+
list of dict, sorted by time, each {"time", "store", "label",
|
|
34
|
+
"phase", "dt_store", "dt_global"} — dt_* are None for the first
|
|
35
|
+
event in their respective sequence.
|
|
36
|
+
"""
|
|
37
|
+
ordered = sorted(markers, key=lambda m: m['time'])
|
|
38
|
+
last_time_by_store = {}
|
|
39
|
+
rows = []
|
|
40
|
+
prev_time = None
|
|
41
|
+
for m in ordered:
|
|
42
|
+
store = m.get('store') or m['label']
|
|
43
|
+
dt_store = None
|
|
44
|
+
if store in last_time_by_store:
|
|
45
|
+
dt_store = m['time'] - last_time_by_store[store]
|
|
46
|
+
last_time_by_store[store] = m['time']
|
|
47
|
+
|
|
48
|
+
dt_global = None if prev_time is None else m['time'] - prev_time
|
|
49
|
+
prev_time = m['time']
|
|
50
|
+
|
|
51
|
+
rows.append({
|
|
52
|
+
'time': m['time'],
|
|
53
|
+
'store': store,
|
|
54
|
+
'label': m['label'],
|
|
55
|
+
'phase': m.get('phase', ''),
|
|
56
|
+
'dt_store': dt_store,
|
|
57
|
+
'dt_global': dt_global,
|
|
58
|
+
})
|
|
59
|
+
return rows
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analysis/peak_finder.py
|
|
3
|
+
-------------------------
|
|
4
|
+
Statistically significant transients: either auto-detected straight
|
|
5
|
+
from the signal (find_significant_peaks), or checked for near a given
|
|
6
|
+
set of event times (find_peak_near_events) rather than assuming an
|
|
7
|
+
event marker itself marks where the neural signal responds.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from scipy.signal import find_peaks
|
|
12
|
+
|
|
13
|
+
from ..numeric import as_float64
|
|
14
|
+
from ..progress import Plan
|
|
15
|
+
from .shared import estimate_sample_rate
|
|
16
|
+
from .zscore_peth import get_zscore_slice
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def find_significant_peaks(time_array, signal, z_threshold=5.0, min_distance_sec=1.0,
|
|
20
|
+
include_troughs=False):
|
|
21
|
+
"""
|
|
22
|
+
Auto-detect statistically significant transients directly from the
|
|
23
|
+
signal, rather than relying on externally-supplied event markers
|
|
24
|
+
(TDT epocs, manual markers, ...) that may not actually line up with
|
|
25
|
+
where the neural signal itself is doing something.
|
|
26
|
+
|
|
27
|
+
The whole recording is z-scored against its own global mean/std
|
|
28
|
+
(not a local baseline — this is a single-pass "how unusual is this
|
|
29
|
+
point relative to the entire recording" measure, not per-event), and
|
|
30
|
+
scipy.signal.find_peaks picks local maxima at or above z_threshold,
|
|
31
|
+
at least min_distance_sec apart so a single transient's rising edge
|
|
32
|
+
doesn't get counted as several peaks.
|
|
33
|
+
|
|
34
|
+
Parameters
|
|
35
|
+
----------
|
|
36
|
+
time_array : array
|
|
37
|
+
signal : array
|
|
38
|
+
Already-processed signal (e.g. bleach-corrected + smoothed) —
|
|
39
|
+
this function does no filtering of its own.
|
|
40
|
+
z_threshold : float
|
|
41
|
+
Minimum z-score (standard deviations above the recording's own
|
|
42
|
+
mean) for a peak to count as "statistically significant". The
|
|
43
|
+
default of 5 is the usual five-sigma convention.
|
|
44
|
+
min_distance_sec : float
|
|
45
|
+
Minimum spacing between detected peaks, in seconds.
|
|
46
|
+
include_troughs : bool
|
|
47
|
+
Also detect significant negative-going deflections (z <=
|
|
48
|
+
-z_threshold) — off by default since most fibre-photometry
|
|
49
|
+
analyses care about excitatory transients specifically.
|
|
50
|
+
|
|
51
|
+
Returns
|
|
52
|
+
-------
|
|
53
|
+
list of dict, each {"time": float, "z_score": float, "kind": "peak"|"trough"},
|
|
54
|
+
sorted by time.
|
|
55
|
+
"""
|
|
56
|
+
time_array = as_float64(time_array)
|
|
57
|
+
signal = as_float64(signal)
|
|
58
|
+
fs = estimate_sample_rate(time_array)
|
|
59
|
+
distance = max(1, int(min_distance_sec * fs))
|
|
60
|
+
|
|
61
|
+
mu, std = np.mean(signal), np.std(signal)
|
|
62
|
+
if std < 1e-9:
|
|
63
|
+
return []
|
|
64
|
+
z = (signal - mu) / std
|
|
65
|
+
|
|
66
|
+
results = []
|
|
67
|
+
peak_idx, _ = find_peaks(z, height=z_threshold, distance=distance)
|
|
68
|
+
for i in peak_idx:
|
|
69
|
+
results.append({"time": float(time_array[i]), "z_score": float(z[i]), "kind": "peak"})
|
|
70
|
+
|
|
71
|
+
if include_troughs:
|
|
72
|
+
trough_idx, _ = find_peaks(-z, height=z_threshold, distance=distance)
|
|
73
|
+
for i in trough_idx:
|
|
74
|
+
results.append({"time": float(time_array[i]), "z_score": float(z[i]), "kind": "trough"})
|
|
75
|
+
|
|
76
|
+
results.sort(key=lambda r: r["time"])
|
|
77
|
+
return results
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def find_peak_near_events(time_array, signal, event_times, pre, post,
|
|
81
|
+
z_threshold=5.0, include_troughs=False, progress=None):
|
|
82
|
+
"""
|
|
83
|
+
Check whether a statistically significant peak actually shows up near
|
|
84
|
+
each given event time, rather than assuming the event marker itself
|
|
85
|
+
marks where the neural signal responds. Works for a single event
|
|
86
|
+
(event_times of length 1) or many occurrences of the same event type
|
|
87
|
+
(checking consistency across all of them).
|
|
88
|
+
|
|
89
|
+
Each event's window is baselined the same way as get_zscore_slice
|
|
90
|
+
(pre-event portion), so "significant" means relative to that event's
|
|
91
|
+
own local baseline, not the whole recording's.
|
|
92
|
+
|
|
93
|
+
Parameters
|
|
94
|
+
----------
|
|
95
|
+
time_array : array
|
|
96
|
+
signal : array
|
|
97
|
+
event_times : list of float
|
|
98
|
+
pre, post : float
|
|
99
|
+
Seconds before/after each event to search within.
|
|
100
|
+
z_threshold : float
|
|
101
|
+
Minimum |z-score| within the window for a peak to count as found.
|
|
102
|
+
The default of 5 (the usual five-sigma convention) is deliberately
|
|
103
|
+
strict: the search takes the LARGEST z over every sample in the
|
|
104
|
+
window, so a low threshold reports a "response" by chance in most
|
|
105
|
+
windows. On a real fibre-photometry recording searched the way PyAT
|
|
106
|
+
does it (0.5 s-smoothed dF/F, 5 s baseline, 10 s response window),
|
|
107
|
+
random pseudo-events (nothing to do with the animal) were reported
|
|
108
|
+
as having a response 58% of the time at 2.5, 40% at 3, 21% at 4 and
|
|
109
|
+
10% at 5; the exact rates depend on the window lengths.
|
|
110
|
+
include_troughs : bool
|
|
111
|
+
Also consider negative-going deflections as candidate "peaks",
|
|
112
|
+
keeping whichever (peak or trough) is more extreme.
|
|
113
|
+
progress : None, True or callable(fraction, message)
|
|
114
|
+
Progress reporting, one tick per event; see PyATCLI.progress.
|
|
115
|
+
|
|
116
|
+
Returns
|
|
117
|
+
-------
|
|
118
|
+
list of dict, one per event_time (same order), each:
|
|
119
|
+
{"event_time": float, "found": bool, "peak_time": float or None,
|
|
120
|
+
"latency": float or None (peak_time - event_time),
|
|
121
|
+
"z_score": float or None, "kind": "peak"|"trough"|None}
|
|
122
|
+
"found" is False when the window was unusable (too close to the
|
|
123
|
+
recording's edges) or nothing in it reached z_threshold.
|
|
124
|
+
"""
|
|
125
|
+
time_array = as_float64(time_array)
|
|
126
|
+
signal = as_float64(signal)
|
|
127
|
+
results = []
|
|
128
|
+
for t in Plan(progress, [("Searching for peaks", 1)]).track("Searching for peaks", event_times):
|
|
129
|
+
seg_x, seg_z = get_zscore_slice(time_array, signal, t, pre=pre, post=post)
|
|
130
|
+
if seg_x is None or len(seg_x) == 0:
|
|
131
|
+
results.append({"event_time": t, "found": False, "peak_time": None,
|
|
132
|
+
"latency": None, "z_score": None, "kind": None})
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
idx_max = int(np.argmax(seg_z))
|
|
136
|
+
if include_troughs:
|
|
137
|
+
idx_min = int(np.argmin(seg_z))
|
|
138
|
+
if abs(seg_z[idx_min]) > seg_z[idx_max]:
|
|
139
|
+
best_idx, kind = idx_min, "trough"
|
|
140
|
+
else:
|
|
141
|
+
best_idx, kind = idx_max, "peak"
|
|
142
|
+
else:
|
|
143
|
+
best_idx, kind = idx_max, "peak"
|
|
144
|
+
|
|
145
|
+
best_z = float(seg_z[best_idx])
|
|
146
|
+
found = abs(best_z) >= z_threshold
|
|
147
|
+
peak_time = float(seg_x[best_idx]) if found else None
|
|
148
|
+
results.append({
|
|
149
|
+
"event_time": t, "found": found,
|
|
150
|
+
"peak_time": peak_time,
|
|
151
|
+
"latency": (peak_time - t) if found else None,
|
|
152
|
+
"z_score": best_z if found else None,
|
|
153
|
+
"kind": kind if found else None,
|
|
154
|
+
})
|
|
155
|
+
return results
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analysis/shared.py
|
|
3
|
+
-------------------
|
|
4
|
+
Small helpers used by more than one analysis tool (or by a loader
|
|
5
|
+
outside analysis/ entirely, e.g. estimate_sample_rate for a generic
|
|
6
|
+
tabular file with no reported fs) — kept separate from any one tool's
|
|
7
|
+
own file so pulling in, say, curve_fit.py doesn't also drag in AUC- or
|
|
8
|
+
FFT-specific code that happens to need the same helper.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from ..numeric import as_float64
|
|
14
|
+
|
|
15
|
+
# Moving-average window every event-locked analysis smooths the dF/F with first; named so provenance can report it.
|
|
16
|
+
SMOOTH_WINDOW_SEC = 0.5
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def estimate_sample_rate(time_array):
|
|
20
|
+
"""
|
|
21
|
+
Robust sample-rate estimate from a timestamp array, for a source that
|
|
22
|
+
doesn't report its own fs (e.g. a generic tabular file) or as a
|
|
23
|
+
fallback wherever one's needed internally. Uses the median inter-
|
|
24
|
+
sample interval rather than e.g. `1 / (time_array[1] - time_array[0])`
|
|
25
|
+
so one irregular gap (a dropped sample, a rounding artifact at the
|
|
26
|
+
very start) doesn't skew the whole estimate.
|
|
27
|
+
|
|
28
|
+
Parameters
|
|
29
|
+
----------
|
|
30
|
+
time_array : array
|
|
31
|
+
Must have at least 2 samples.
|
|
32
|
+
|
|
33
|
+
Returns
|
|
34
|
+
-------
|
|
35
|
+
float, sample rate in Hz.
|
|
36
|
+
"""
|
|
37
|
+
return float(1.0 / np.median(np.diff(as_float64(time_array))))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def window_around(time_array, signal, center_t, window=None, pre=None, post=None):
|
|
41
|
+
"""
|
|
42
|
+
(time segment, signal segment) of the samples from `pre` seconds before `center_t` to `post` seconds after it, both float64.
|
|
43
|
+
|
|
44
|
+
The window is either asymmetric (`pre` and/or `post`) or a symmetric `window`, the total seconds split evenly before and after: a
|
|
45
|
+
side that is not given takes half of `window`, which is 30 s when that is not given either.
|
|
46
|
+
"""
|
|
47
|
+
if pre is None or post is None:
|
|
48
|
+
half_win = (window if window is not None else 30) / 2
|
|
49
|
+
pre = pre if pre is not None else half_win
|
|
50
|
+
post = post if post is not None else half_win
|
|
51
|
+
|
|
52
|
+
time_array = as_float64(time_array)
|
|
53
|
+
signal = as_float64(signal)
|
|
54
|
+
start_idx = np.searchsorted(time_array, center_t - pre)
|
|
55
|
+
end_idx = np.searchsorted(time_array, center_t + post)
|
|
56
|
+
return time_array[start_idx:end_idx], signal[start_idx:end_idx]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def mean_channels(arr):
|
|
60
|
+
"""
|
|
61
|
+
Collapse a multi-channel array to its across-channel mean trace —
|
|
62
|
+
e.g. Oxysoft's per-detector o2hb/hhb/thb arrays, shape
|
|
63
|
+
(n_channels, n_samples), averaged down to one representative trace.
|
|
64
|
+
A no-op for an already-1D array, so callers can use this unconditionally
|
|
65
|
+
regardless of whether a given recording actually has multiple channels.
|
|
66
|
+
|
|
67
|
+
Parameters
|
|
68
|
+
----------
|
|
69
|
+
arr : array, 1D or 2D (n_channels, n_samples)
|
|
70
|
+
|
|
71
|
+
Returns
|
|
72
|
+
-------
|
|
73
|
+
array, 1D — arr unchanged if already 1D, else arr.mean(axis=0).
|
|
74
|
+
"""
|
|
75
|
+
arr = as_float64(arr)
|
|
76
|
+
return arr.mean(axis=0) if arr.ndim > 1 else arr
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def smooth_signal(data, fs, window_sec=SMOOTH_WINDOW_SEC):
|
|
80
|
+
"""
|
|
81
|
+
Moving average smoothing filter.
|
|
82
|
+
|
|
83
|
+
Parameters
|
|
84
|
+
----------
|
|
85
|
+
data : array
|
|
86
|
+
fs : float
|
|
87
|
+
Sampling frequency in Hz
|
|
88
|
+
window_sec : float
|
|
89
|
+
Smoothing window in seconds
|
|
90
|
+
|
|
91
|
+
Returns
|
|
92
|
+
-------
|
|
93
|
+
array
|
|
94
|
+
Smoothed signal
|
|
95
|
+
"""
|
|
96
|
+
data = as_float64(data)
|
|
97
|
+
window_size = int(fs * window_sec)
|
|
98
|
+
if window_size % 2 == 0:
|
|
99
|
+
window_size += 1
|
|
100
|
+
return np.convolve(data, np.ones(window_size) / window_size, mode='same')
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analysis/zscore_peth.py
|
|
3
|
+
------------------------
|
|
4
|
+
Single-click Z-Score PETH: extract and z-score a window around one
|
|
5
|
+
event. get_zscore_slice is also the shared building block event_peth.py
|
|
6
|
+
and peak_finder.py call per-event/per-trial, so a bug fix or behavior
|
|
7
|
+
change here (e.g. how the baseline is protected from artefacts) applies
|
|
8
|
+
everywhere a peri-event window gets z-scored, not just this one tool.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from ..numeric import as_float64
|
|
14
|
+
from .shared import window_around
|
|
15
|
+
|
|
16
|
+
# How far (in robust SDs) a baseline sample may sit from the baseline's median before it is pulled in for the
|
|
17
|
+
# mean/SD — see _baseline_mean_std. Named so provenance can report it.
|
|
18
|
+
BASELINE_ROBUST_SD = 5.0
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_zscore_slice(time_array, signal, center_t, window=None, pre=None, post=None):
|
|
22
|
+
"""
|
|
23
|
+
Extract and z-score a time window around an event.
|
|
24
|
+
|
|
25
|
+
Supports either a symmetric `window` (split evenly before/after
|
|
26
|
+
center_t, legacy behaviour) or an asymmetric `pre`/`post` pair — e.g.
|
|
27
|
+
10s before the event and 20s after. If pre/post are given they take
|
|
28
|
+
precedence over window.
|
|
29
|
+
|
|
30
|
+
Parameters
|
|
31
|
+
----------
|
|
32
|
+
time_array : array
|
|
33
|
+
signal : array
|
|
34
|
+
center_t : float
|
|
35
|
+
Event time in seconds
|
|
36
|
+
window : float or None
|
|
37
|
+
Total window size in seconds, split evenly before/after center_t.
|
|
38
|
+
Ignored if pre/post are given.
|
|
39
|
+
pre : float or None
|
|
40
|
+
Seconds before center_t to include. Defaults to window/2.
|
|
41
|
+
post : float or None
|
|
42
|
+
Seconds after center_t to include. Defaults to window/2.
|
|
43
|
+
|
|
44
|
+
Returns
|
|
45
|
+
-------
|
|
46
|
+
(time segment, z-scored signal)
|
|
47
|
+
"""
|
|
48
|
+
seg_x, seg_y = window_around(time_array, signal, center_t, window, pre, post)
|
|
49
|
+
if seg_y.size == 0: # nothing in the window (an event past the recording's end): no statistics to take
|
|
50
|
+
return seg_x, np.zeros_like(seg_y)
|
|
51
|
+
|
|
52
|
+
# Baseline is the pre-event portion — the part of the window that
|
|
53
|
+
# actually precedes the event, not just "the first half of the segment"
|
|
54
|
+
# (those differ once pre != post).
|
|
55
|
+
baseline_mask = seg_x < center_t
|
|
56
|
+
baseline_period = seg_y[baseline_mask] if baseline_mask.any() else seg_y
|
|
57
|
+
mu, std = _baseline_mean_std(baseline_period)
|
|
58
|
+
|
|
59
|
+
# "Flat" means the baseline's spread is down at floating-point rounding
|
|
60
|
+
# level next to its own size — a relative test, so it doesn't depend on
|
|
61
|
+
# the units the signal is in.
|
|
62
|
+
scale = np.max(np.abs(baseline_period)) if baseline_period.size else 0.0
|
|
63
|
+
if std == 0 or std <= 1e-12 * scale:
|
|
64
|
+
return seg_x, np.zeros_like(seg_y)
|
|
65
|
+
|
|
66
|
+
return seg_x, (seg_y - mu) / std
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _baseline_mean_std(baseline, n_robust_sd=BASELINE_ROBUST_SD):
|
|
70
|
+
"""
|
|
71
|
+
Mean and SD of a baseline window, protected from artefact samples.
|
|
72
|
+
|
|
73
|
+
Samples further than `n_robust_sd` robust standard deviations (1.4826 x
|
|
74
|
+
the median absolute deviation) from the baseline's median are pulled in
|
|
75
|
+
to that limit before the mean and SD are taken, so a brief motion spike
|
|
76
|
+
inside the baseline can't inflate the SD and shrink every z-score in the
|
|
77
|
+
trial. The limit is relative to the baseline's own spread, so the result
|
|
78
|
+
is the same whatever units the signal is in, and only the baseline
|
|
79
|
+
statistics are treated this way — the samples being scored are never
|
|
80
|
+
altered, so a large real response keeps its real height.
|
|
81
|
+
"""
|
|
82
|
+
med = np.median(baseline)
|
|
83
|
+
robust_sd = 1.4826 * np.median(np.abs(baseline - med))
|
|
84
|
+
if robust_sd > 0:
|
|
85
|
+
baseline = np.clip(baseline, med - n_robust_sd * robust_sd, med + n_robust_sd * robust_sd)
|
|
86
|
+
return np.mean(baseline), np.std(baseline)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def bin_for_heatmap(z_seg, num_bins=300):
|
|
90
|
+
"""
|
|
91
|
+
Bin a signal into equal segments for heatmap plotting.
|
|
92
|
+
|
|
93
|
+
Parameters
|
|
94
|
+
----------
|
|
95
|
+
z_seg : array
|
|
96
|
+
num_bins : int
|
|
97
|
+
|
|
98
|
+
Returns
|
|
99
|
+
-------
|
|
100
|
+
array
|
|
101
|
+
Binned signal
|
|
102
|
+
"""
|
|
103
|
+
if z_seg is None or len(z_seg) == 0:
|
|
104
|
+
return np.zeros(num_bins)
|
|
105
|
+
z_seg = as_float64(z_seg)
|
|
106
|
+
bin_edges = np.linspace(0, len(z_seg), num_bins + 1).astype(int)
|
|
107
|
+
return np.array([np.mean(z_seg[bin_edges[i]:bin_edges[i+1]]) for i in range(num_bins)])
|
PyATCLI/cli/__init__.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""
|
|
2
|
+
cli
|
|
3
|
+
---
|
|
4
|
+
The command line: `python -m PyATCLI <command>` (and the `pyatcli` command pip installs).
|
|
5
|
+
|
|
6
|
+
run run one analysis on a recording; writes CSV tables and a provenance record
|
|
7
|
+
reproduce run an analysis again from its .provenance.json and check the numbers
|
|
8
|
+
batch many analyses over many recordings (a folder of TDT blocks counts as many)
|
|
9
|
+
group group analysis: `group setup` (the wizard: find the recordings, list their markers, write analysis_settings.json) and `group run`
|
|
10
|
+
saved what the app's Save Changes saves, from a script: show, marker, unmark, splice, unsplice, rename, highlight, text, clear
|
|
11
|
+
kinds the analyses, and every parameter of each
|
|
12
|
+
info what is installed (versions: what a result would be stamped with)
|
|
13
|
+
serve the engine: the same operations as JSON lines on stdin/stdout, with recordings kept open (what PyAT's window talks to)
|
|
14
|
+
|
|
15
|
+
The command line is a thin front over ops/ — argparse in front of an operation, a renderer (human, --plain, --json) behind it — and the
|
|
16
|
+
engine is the same operations behind a different transport, so they cannot disagree; see ops/__init__.py.
|
|
17
|
+
|
|
18
|
+
Every command takes the same global flags, before or after its name: --json, --plain, -q, -v, -d, --no-input, --events, --progress.
|
|
19
|
+
|
|
20
|
+
Output: stdout is only ever the result (--json for a program, --plain for rows); warnings, errors, progress and anything a library prints
|
|
21
|
+
itself go to stderr or are dropped. Exit status: 0 done; 1 something failed (the message is on stderr); 2 bad usage; 3 `reproduce` ran but
|
|
22
|
+
an export did not match; 130 interrupted.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
import os
|
|
26
|
+
import sys
|
|
27
|
+
|
|
28
|
+
from .. import ops
|
|
29
|
+
from ..ops import error_info
|
|
30
|
+
from .commands import EXIT_ERROR, EXIT_MISMATCH, EXIT_OK, EXIT_USAGE, APP, collect_parameters, parse_value, recording_name # noqa: F401 — the module's public names
|
|
31
|
+
from .parser import build_parser, concise_help
|
|
32
|
+
from .render import Discard, Output
|
|
33
|
+
|
|
34
|
+
INTERRUPTED = 130
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _command_index(argv):
|
|
38
|
+
"""Where the command name is: the first token that is not a flag (the global flags take no value)."""
|
|
39
|
+
return next((n for n, token in enumerate(argv) if not token.startswith("-")), None)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _legacy(argv):
|
|
43
|
+
"""The old spellings, rewritten (with a warning on stderr): `group-setup ...` is `group setup ...` and `group SETTINGS ...` is `group run
|
|
44
|
+
SETTINGS ...`. Returns (argv, [warnings])."""
|
|
45
|
+
argv = list(argv)
|
|
46
|
+
i = _command_index(argv)
|
|
47
|
+
if i is None:
|
|
48
|
+
return argv, []
|
|
49
|
+
if argv[i] == "group-setup":
|
|
50
|
+
argv[i:i + 1] = ["group", "setup"]
|
|
51
|
+
return argv, ["`group-setup` is now `group setup` (the old name still works)"]
|
|
52
|
+
if argv[i] == "group" and i + 1 < len(argv) and not argv[i + 1].startswith("-") and argv[i + 1] not in ("setup", "run"):
|
|
53
|
+
argv.insert(i + 1, "run")
|
|
54
|
+
return argv, ["`group SETTINGS` is now `group run SETTINGS` (the old form still works)"]
|
|
55
|
+
return argv, []
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _truthy(value):
|
|
59
|
+
return bool(value) and value.strip().lower() not in ("0", "false", "no", "off")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def main(argv=None):
|
|
63
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
64
|
+
for stream in (sys.stdout, sys.stderr): # a console that cannot show ¹ or ⁰ must not kill the run
|
|
65
|
+
try:
|
|
66
|
+
stream.reconfigure(errors="replace")
|
|
67
|
+
except (AttributeError, ValueError):
|
|
68
|
+
pass
|
|
69
|
+
argv, legacy = _legacy(argv)
|
|
70
|
+
if not argv:
|
|
71
|
+
print(concise_help(), end="")
|
|
72
|
+
return EXIT_OK
|
|
73
|
+
i = _command_index(argv)
|
|
74
|
+
if i is not None and argv[i] == "serve" and not {"-h", "--help"} & set(argv): # (its help is the parser's: with examples)
|
|
75
|
+
from ..engine.server import main as serve_main
|
|
76
|
+
return serve_main(argv[:i] + argv[i + 1:])
|
|
77
|
+
parser = build_parser()
|
|
78
|
+
args = parser.parse_args(argv)
|
|
79
|
+
if args.command is None: # only global flags were given
|
|
80
|
+
print(concise_help(), end="")
|
|
81
|
+
return EXIT_OK
|
|
82
|
+
real_stdout, real_stderr = sys.stdout, sys.stderr
|
|
83
|
+
out = Output(args, real_stdout, real_stderr)
|
|
84
|
+
args.debug = args.debug or _truthy(os.environ.get("DEBUG", ""))
|
|
85
|
+
out.debug = args.debug
|
|
86
|
+
for text in legacy:
|
|
87
|
+
out.warn(text)
|
|
88
|
+
sys.stdout = real_stderr if out.verbose else Discard() # what a library prints on its own must not mix into the result
|
|
89
|
+
try:
|
|
90
|
+
return args.fn(args, out)
|
|
91
|
+
except (KeyboardInterrupt, ops.Cancelled):
|
|
92
|
+
out.error("interrupted")
|
|
93
|
+
return INTERRUPTED
|
|
94
|
+
except Exception as e: # noqa: BLE001 — every error becomes a message a person can read
|
|
95
|
+
if args.debug:
|
|
96
|
+
raise
|
|
97
|
+
info = error_info(e)
|
|
98
|
+
out.fail(info)
|
|
99
|
+
return EXIT_USAGE if info["code"] == "confirmation_required" else EXIT_ERROR
|
|
100
|
+
finally:
|
|
101
|
+
sys.stdout = real_stdout
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
if __name__ == "__main__":
|
|
105
|
+
sys.exit(main())
|