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,81 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analysis
|
|
3
|
+
--------
|
|
4
|
+
Format-agnostic analysis routines for PyAT, one file per
|
|
5
|
+
tool (mirrors physicsanalysis_qt/analysis/'s own layout):
|
|
6
|
+
|
|
7
|
+
shared.py - estimate_sample_rate, mean_channels, smooth_signal
|
|
8
|
+
(used by more than one tool below)
|
|
9
|
+
zscore_peth.py - single-click Z-Score PETH (get_zscore_slice, bin_for_heatmap)
|
|
10
|
+
event_peth.py - stacked-heatmap + trial-average PETH: compute_event_zscore_peth,
|
|
11
|
+
compute_group_stats, compute_auc_matrix, compute_peri_event_*
|
|
12
|
+
auc.py - area under curve (compute_auc_from_trace, compute_auc_window)
|
|
13
|
+
fft.py - compute_fft_slice, find_fft_peaks (peak *drawing* is
|
|
14
|
+
physicsanalysis_qt's own concern, not this library's —
|
|
15
|
+
see that repo's analysis/fft.py)
|
|
16
|
+
peak_finder.py - find_significant_peaks, find_peak_near_events
|
|
17
|
+
curve_fit.py - compute_slope_segment, fit_model_to_segment
|
|
18
|
+
intervals.py - compute_marker_intervals
|
|
19
|
+
group/ - group analysis across recordings (a package):
|
|
20
|
+
__init__.py - GroupSpec (the settings), marker_index / common_markers / design_summary (what the recordings
|
|
21
|
+
share, trials per subject)
|
|
22
|
+
trials.py - extract_group_trials: the window around each event of a marker, baseline-corrected,
|
|
23
|
+
reduced to AUC / peak / mean / latency / decay time
|
|
24
|
+
stats.py - fit_group_models: mixed-effects models and pairwise comparisons (GroupResults)
|
|
25
|
+
report.py - write_group_results, report_text: the tables as CSV and a text report
|
|
26
|
+
scan.py - scan_recording(s): what each recording of a group holds (markers, length), no signal work
|
|
27
|
+
run.py - run_group_analysis: the whole headless run (load, trials, models, tables); and
|
|
28
|
+
read/write_group_settings, the analysis_settings.json that makes a run repeatable
|
|
29
|
+
|
|
30
|
+
This __init__ just re-exports every public name under the same
|
|
31
|
+
`PyATCLI.analysis` namespace the single-file version used to
|
|
32
|
+
provide, so PyATCLI/__init__.py's own `from .analysis import ...`
|
|
33
|
+
line — and every external caller — didn't need to change.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from .shared import (
|
|
37
|
+
estimate_sample_rate,
|
|
38
|
+
mean_channels,
|
|
39
|
+
smooth_signal,
|
|
40
|
+
)
|
|
41
|
+
from .zscore_peth import (
|
|
42
|
+
get_zscore_slice,
|
|
43
|
+
bin_for_heatmap,
|
|
44
|
+
)
|
|
45
|
+
from .event_peth import (
|
|
46
|
+
compute_group_stats,
|
|
47
|
+
compute_event_zscore_peth,
|
|
48
|
+
compute_auc_matrix,
|
|
49
|
+
compute_peri_event_from_trace,
|
|
50
|
+
compute_peri_event_matrix,
|
|
51
|
+
)
|
|
52
|
+
from .auc import (
|
|
53
|
+
compute_auc_from_trace,
|
|
54
|
+
compute_auc_window,
|
|
55
|
+
)
|
|
56
|
+
from .fft import (
|
|
57
|
+
compute_fft_slice,
|
|
58
|
+
find_fft_peaks,
|
|
59
|
+
)
|
|
60
|
+
from .peak_finder import (
|
|
61
|
+
find_significant_peaks,
|
|
62
|
+
find_peak_near_events,
|
|
63
|
+
)
|
|
64
|
+
from .curve_fit import (
|
|
65
|
+
compute_slope_segment,
|
|
66
|
+
fit_model_to_segment,
|
|
67
|
+
)
|
|
68
|
+
from .intervals import (
|
|
69
|
+
compute_marker_intervals,
|
|
70
|
+
)
|
|
71
|
+
from .group import (
|
|
72
|
+
GroupSpec,
|
|
73
|
+
marker_index,
|
|
74
|
+
common_markers,
|
|
75
|
+
design_summary,
|
|
76
|
+
)
|
|
77
|
+
from .group.trials import extract_group_trials, measures_for_trial, decay_time
|
|
78
|
+
from .group.stats import fit_group_models, GroupResults
|
|
79
|
+
from .group.report import write_group_results, report_text as group_report_text
|
|
80
|
+
from .group.scan import default_subject_names, scan_recording, scan_recordings
|
|
81
|
+
from .group.run import GROUP_SETTINGS_FILENAME, load_group_recording, run_group_analysis, write_group_settings, read_group_settings
|
PyATCLI/analysis/auc.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analysis/auc.py
|
|
3
|
+
----------------
|
|
4
|
+
Area under curve, split by sign. compute_auc_from_trace is the shared
|
|
5
|
+
core both compute_auc_window (single window, this file) and
|
|
6
|
+
event_peth.py's compute_auc_matrix (per-trial/group, across a whole
|
|
7
|
+
trial x time matrix) delegate to, so the sign-split logic lives in
|
|
8
|
+
exactly one place.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from ..numeric import as_float64
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def compute_auc_from_trace(x, y):
|
|
17
|
+
"""
|
|
18
|
+
Trapezoidal area under an already-extracted trace, split by sign.
|
|
19
|
+
|
|
20
|
+
positive_auc integrates only where y >= 0 (negative samples clipped
|
|
21
|
+
to 0); negative_auc integrates only where y <= 0 (positive samples
|
|
22
|
+
clipped to 0) and is a real *signed* area (<= 0), not an absolute
|
|
23
|
+
value — total_auc is their sum, equivalent to the plain net signed
|
|
24
|
+
integral of y.
|
|
25
|
+
|
|
26
|
+
Parameters
|
|
27
|
+
----------
|
|
28
|
+
x : array
|
|
29
|
+
y : array
|
|
30
|
+
|
|
31
|
+
Returns
|
|
32
|
+
-------
|
|
33
|
+
dict with total_auc, positive_auc, negative_auc (all float). All
|
|
34
|
+
zero if x has fewer than 2 points (np.trapezoid needs at least 2 to
|
|
35
|
+
integrate anything).
|
|
36
|
+
"""
|
|
37
|
+
x = as_float64(x)
|
|
38
|
+
y = as_float64(y)
|
|
39
|
+
if len(x) < 2:
|
|
40
|
+
return {"total_auc": 0.0, "positive_auc": 0.0, "negative_auc": 0.0}
|
|
41
|
+
total = float(np.trapezoid(y, x))
|
|
42
|
+
positive = float(np.trapezoid(np.clip(y, 0, None), x))
|
|
43
|
+
negative = float(np.trapezoid(np.clip(y, None, 0), x))
|
|
44
|
+
return {"total_auc": total, "positive_auc": positive, "negative_auc": negative}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def compute_auc_window(time_array, signal, center_t, pre, post):
|
|
48
|
+
"""
|
|
49
|
+
Slice a pre/post window around an event and integrate it — same
|
|
50
|
+
windowing convention as get_zscore_slice/compute_fft_slice, so this
|
|
51
|
+
drops into the same click-triggered dispatch path those use.
|
|
52
|
+
Deliberately does NOT z-score the segment first: AUC is meant to
|
|
53
|
+
quantify the signal (already dF/F-normalized upstream) in its own
|
|
54
|
+
units, not a re-baselined version of it.
|
|
55
|
+
|
|
56
|
+
Parameters
|
|
57
|
+
----------
|
|
58
|
+
time_array : array
|
|
59
|
+
signal : array
|
|
60
|
+
center_t : float
|
|
61
|
+
Event time in seconds.
|
|
62
|
+
pre, post : float
|
|
63
|
+
Seconds before/after center_t to include.
|
|
64
|
+
|
|
65
|
+
Returns
|
|
66
|
+
-------
|
|
67
|
+
dict with seg_x, seg_y (the windowed slice actually integrated) plus
|
|
68
|
+
total_auc, positive_auc, negative_auc (see compute_auc_from_trace).
|
|
69
|
+
"""
|
|
70
|
+
time_array = as_float64(time_array)
|
|
71
|
+
signal = as_float64(signal)
|
|
72
|
+
start_idx = np.searchsorted(time_array, center_t - pre)
|
|
73
|
+
end_idx = np.searchsorted(time_array, center_t + post)
|
|
74
|
+
seg_x = time_array[start_idx:end_idx]
|
|
75
|
+
seg_y = signal[start_idx:end_idx]
|
|
76
|
+
result = compute_auc_from_trace(seg_x, seg_y)
|
|
77
|
+
result["seg_x"] = seg_x
|
|
78
|
+
result["seg_y"] = seg_y
|
|
79
|
+
return result
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analysis/curve_fit.py
|
|
3
|
+
-----------------------
|
|
4
|
+
Two-point linear slope between click-selected indices, and general
|
|
5
|
+
model fitting (any model_fn/p0_fn pair — see PyATCLI.models for
|
|
6
|
+
the model functions themselves) via scipy curve_fit.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from scipy.optimize import curve_fit
|
|
11
|
+
|
|
12
|
+
from ..numeric import as_float64
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def compute_slope_segment(x_data, y_data, p1_idx, p2_idx, padding_pct=0.05):
|
|
16
|
+
"""
|
|
17
|
+
Least-squares linear regression slope between two index boundaries.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
x_data : array
|
|
22
|
+
y_data : array
|
|
23
|
+
p1_idx : int
|
|
24
|
+
p2_idx : int
|
|
25
|
+
padding_pct : float visual context padding
|
|
26
|
+
|
|
27
|
+
Returns
|
|
28
|
+
-------
|
|
29
|
+
dict with slope, intercept, crop_x, crop_y, x1, y1, x2, y2
|
|
30
|
+
"""
|
|
31
|
+
x_data = as_float64(x_data)
|
|
32
|
+
y_data = as_float64(y_data)
|
|
33
|
+
idx1, idx2 = sorted([p1_idx, p2_idx])
|
|
34
|
+
|
|
35
|
+
fit_x = x_data[idx1:idx2 + 1]
|
|
36
|
+
fit_y = y_data[idx1:idx2 + 1]
|
|
37
|
+
|
|
38
|
+
if len(fit_x) < 2:
|
|
39
|
+
slope, intercept = 0.0, 0.0
|
|
40
|
+
else:
|
|
41
|
+
slope, intercept = np.polyfit(fit_x, fit_y, 1)
|
|
42
|
+
|
|
43
|
+
x1, y1 = fit_x[0], fit_y[0]
|
|
44
|
+
x2, y2 = fit_x[-1], fit_y[-1]
|
|
45
|
+
|
|
46
|
+
pad = max(5, int(len(x_data) * padding_pct))
|
|
47
|
+
start_idx = max(0, idx1 - pad)
|
|
48
|
+
end_idx = min(len(x_data) - 1, idx2 + pad)
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
'slope': slope,
|
|
52
|
+
'intercept': intercept,
|
|
53
|
+
'crop_x': x_data[start_idx:end_idx + 1],
|
|
54
|
+
'crop_y': y_data[start_idx:end_idx + 1],
|
|
55
|
+
'x1': x1, 'y1': y1,
|
|
56
|
+
'x2': x2, 'y2': y2,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def fit_model_to_segment(x_seg, y_seg, model_fn, p0_fn):
|
|
61
|
+
"""
|
|
62
|
+
Fit a model function to a data segment using scipy curve_fit.
|
|
63
|
+
|
|
64
|
+
Parameters
|
|
65
|
+
----------
|
|
66
|
+
x_seg : array
|
|
67
|
+
y_seg : array
|
|
68
|
+
model_fn : callable f(x, *params) -> y
|
|
69
|
+
p0_fn : callable f(x_seg, y_seg) -> list of initial guesses
|
|
70
|
+
|
|
71
|
+
Returns
|
|
72
|
+
-------
|
|
73
|
+
dict with popt, y_fit, r2, success, error
|
|
74
|
+
"""
|
|
75
|
+
x_seg = as_float64(x_seg)
|
|
76
|
+
y_seg = as_float64(y_seg)
|
|
77
|
+
try:
|
|
78
|
+
p0 = p0_fn(x_seg, y_seg)
|
|
79
|
+
popt, _ = curve_fit(model_fn, x_seg, y_seg, p0=p0, maxfev=10000)
|
|
80
|
+
y_fit = model_fn(x_seg, *popt)
|
|
81
|
+
ss_res = np.sum((y_seg - y_fit) ** 2)
|
|
82
|
+
ss_tot = np.sum((y_seg - y_seg.mean()) ** 2)
|
|
83
|
+
r2 = 1 - ss_res / ss_tot if ss_tot > 0 else 0.0
|
|
84
|
+
return {"popt": popt, "y_fit": y_fit, "r2": r2,
|
|
85
|
+
"success": True, "error": None}
|
|
86
|
+
except Exception as e:
|
|
87
|
+
return {"popt": None, "y_fit": np.zeros_like(y_seg),
|
|
88
|
+
"r2": 0.0, "success": False, "error": str(e)}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analysis/event_peth.py
|
|
3
|
+
------------------------
|
|
4
|
+
Stacked-heatmap + trial-average PETH (GuPPy-style): align every
|
|
5
|
+
occurrence of one event type into a trial x time matrix, then group
|
|
6
|
+
stats (mean/SEM), AUC, and peak/latency/mean-time-bins over that matrix
|
|
7
|
+
or an arbitrary subset of its rows (e.g. Event PETH's currently-checked
|
|
8
|
+
trials). compute_auc_matrix lives here rather than in auc.py because its
|
|
9
|
+
whole shape (per_trial/group over a trial_matrix) only exists in this
|
|
10
|
+
stacked-trials context — it delegates to auc.py's compute_auc_from_trace
|
|
11
|
+
for the actual per-row integration rather than duplicating it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from ..numeric import as_float64
|
|
17
|
+
from ..progress import Plan
|
|
18
|
+
from .zscore_peth import get_zscore_slice
|
|
19
|
+
from .auc import compute_auc_from_trace
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def compute_group_stats(trial_matrix):
|
|
23
|
+
"""
|
|
24
|
+
Mean + SEM across trials (rows) of an already-built trial x time
|
|
25
|
+
matrix (see compute_event_zscore_peth) — the same formula that
|
|
26
|
+
function uses internally for its own full-trial-set mean_trace/
|
|
27
|
+
sem_trace, exposed separately so a caller needing it for an arbitrary
|
|
28
|
+
subset of trials (e.g. Event PETH's currently-checked trials, not
|
|
29
|
+
necessarily every trial compute_event_zscore_peth originally computed)
|
|
30
|
+
doesn't have to re-derive the formula.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
trial_matrix : array, shape (n_trials, n_samples)
|
|
35
|
+
|
|
36
|
+
Returns
|
|
37
|
+
-------
|
|
38
|
+
(mean_trace, sem_trace) : both array, shape (n_samples,). sem_trace
|
|
39
|
+
is all zeros if trial_matrix has fewer than 2 rows (ddof=1 SEM is
|
|
40
|
+
undefined below 2 samples) — matches compute_event_zscore_peth's
|
|
41
|
+
own zero-trials/one-trial handling. mean_trace is all zeros for
|
|
42
|
+
0 rows (nothing to average).
|
|
43
|
+
"""
|
|
44
|
+
trial_matrix = as_float64(trial_matrix)
|
|
45
|
+
n = trial_matrix.shape[0]
|
|
46
|
+
if n == 0:
|
|
47
|
+
return np.zeros(trial_matrix.shape[1]), np.zeros(trial_matrix.shape[1])
|
|
48
|
+
mean_trace = trial_matrix.mean(axis=0)
|
|
49
|
+
if n > 1:
|
|
50
|
+
sem_trace = trial_matrix.std(axis=0, ddof=1) / np.sqrt(n)
|
|
51
|
+
else:
|
|
52
|
+
sem_trace = np.zeros_like(mean_trace)
|
|
53
|
+
return mean_trace, sem_trace
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def compute_event_zscore_peth(time_array, signal, event_times, pre, post, num_bins=300, progress=None):
|
|
57
|
+
"""
|
|
58
|
+
Z-score and align every occurrence of one event type into a
|
|
59
|
+
trial x time matrix, for a stacked-heatmap + trial-average PETH view
|
|
60
|
+
(GuPPy-style) rather than a single click-triggered PETH.
|
|
61
|
+
|
|
62
|
+
Each trial is z-scored independently against its own pre-event
|
|
63
|
+
baseline (see get_zscore_slice) — that's what makes a trial's
|
|
64
|
+
response comparable regardless of the signal's absolute level at
|
|
65
|
+
that point in the recording. Trials are then resampled onto one
|
|
66
|
+
shared relative-time axis (num_bins points spanning -pre..+post) so
|
|
67
|
+
they can be stacked into a single matrix despite each trial's raw
|
|
68
|
+
segment having a slightly different sample count from indexing
|
|
69
|
+
rounding.
|
|
70
|
+
|
|
71
|
+
Parameters
|
|
72
|
+
----------
|
|
73
|
+
time_array : array
|
|
74
|
+
signal : array
|
|
75
|
+
event_times : list of float
|
|
76
|
+
Timestamps (same units as time_array) for every occurrence of
|
|
77
|
+
the event being analyzed.
|
|
78
|
+
pre, post : float
|
|
79
|
+
Seconds before/after each event to include.
|
|
80
|
+
num_bins : int
|
|
81
|
+
Number of points each trial is resampled to.
|
|
82
|
+
progress : None, True or callable(fraction, message)
|
|
83
|
+
Progress reporting, one tick per event; see PyATCLI.progress.
|
|
84
|
+
|
|
85
|
+
Returns
|
|
86
|
+
-------
|
|
87
|
+
dict with:
|
|
88
|
+
time_axis : array, shape (num_bins,) — relative time, -pre..+post
|
|
89
|
+
trial_matrix : array, shape (n_valid_trials, num_bins)
|
|
90
|
+
trial_event_times : list of the event_times that produced a
|
|
91
|
+
usable trial (too-short/edge-of-recording events are skipped)
|
|
92
|
+
mean_trace : array, shape (num_bins,)
|
|
93
|
+
sem_trace : array, shape (num_bins,) — standard error of the mean
|
|
94
|
+
across trials, zero if fewer than 2 trials
|
|
95
|
+
"""
|
|
96
|
+
time_array = as_float64(time_array)
|
|
97
|
+
signal = as_float64(signal)
|
|
98
|
+
time_axis = np.linspace(-pre, post, num_bins)
|
|
99
|
+
rows = []
|
|
100
|
+
valid_times = []
|
|
101
|
+
for t in Plan(progress, [("Aligning trials", 1)]).track("Aligning trials", event_times):
|
|
102
|
+
seg_x, seg_z = get_zscore_slice(time_array, signal, t, pre=pre, post=post)
|
|
103
|
+
if seg_x is None or len(seg_x) < 2:
|
|
104
|
+
continue
|
|
105
|
+
rel_x = seg_x - t
|
|
106
|
+
rows.append(np.interp(time_axis, rel_x, seg_z))
|
|
107
|
+
valid_times.append(t)
|
|
108
|
+
|
|
109
|
+
if not rows:
|
|
110
|
+
empty = np.zeros(num_bins)
|
|
111
|
+
return {
|
|
112
|
+
"time_axis": time_axis, "trial_matrix": np.zeros((0, num_bins)),
|
|
113
|
+
"trial_event_times": [], "mean_trace": empty, "sem_trace": empty,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
trial_matrix = np.array(rows)
|
|
117
|
+
mean_trace, sem_trace = compute_group_stats(trial_matrix)
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
"time_axis": time_axis, "trial_matrix": trial_matrix,
|
|
121
|
+
"trial_event_times": valid_times, "mean_trace": mean_trace, "sem_trace": sem_trace,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def compute_auc_matrix(time_axis, trial_matrix):
|
|
126
|
+
"""
|
|
127
|
+
Per-trial + group (mean-trace) AUC for an already-built trial x time
|
|
128
|
+
matrix (see compute_event_zscore_peth) — lets Event PETH compute its
|
|
129
|
+
group stat and per-trial list in one call over whichever subset of
|
|
130
|
+
trials is currently relevant, without re-deriving the trapezoidal/
|
|
131
|
+
clip logic per caller.
|
|
132
|
+
|
|
133
|
+
Parameters
|
|
134
|
+
----------
|
|
135
|
+
time_axis : array, shape (num_bins,)
|
|
136
|
+
trial_matrix : array, shape (n_trials, num_bins)
|
|
137
|
+
|
|
138
|
+
Returns
|
|
139
|
+
-------
|
|
140
|
+
dict with:
|
|
141
|
+
per_trial : list of dict (one per row of trial_matrix, same
|
|
142
|
+
order), each {"total_auc", "positive_auc", "negative_auc"}
|
|
143
|
+
group : dict, same three keys, computed on trial_matrix's
|
|
144
|
+
mean(axis=0) — all zero if trial_matrix has 0 rows
|
|
145
|
+
"""
|
|
146
|
+
time_axis = as_float64(time_axis)
|
|
147
|
+
trial_matrix = as_float64(trial_matrix)
|
|
148
|
+
per_trial = [compute_auc_from_trace(time_axis, row) for row in trial_matrix]
|
|
149
|
+
if trial_matrix.shape[0] > 0:
|
|
150
|
+
group = compute_auc_from_trace(time_axis, trial_matrix.mean(axis=0))
|
|
151
|
+
else:
|
|
152
|
+
group = {"total_auc": 0.0, "positive_auc": 0.0, "negative_auc": 0.0}
|
|
153
|
+
return {"per_trial": per_trial, "group": group}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _mean_time_bins(rel_x, y, post, bin_width):
|
|
157
|
+
"""Post-event window [0, post] divided into bin_width-second chunks
|
|
158
|
+
(the last bin is truncated, not dropped, if post isn't evenly
|
|
159
|
+
divisible by bin_width). rel_x is already relative to the event
|
|
160
|
+
(0 = event time).
|
|
161
|
+
|
|
162
|
+
Returns
|
|
163
|
+
-------
|
|
164
|
+
list of dict, each {"bin_start", "bin_end", "mean"} — empty if
|
|
165
|
+
post <= 0, bin_width <= 0, or there are no rel_x >= 0 samples.
|
|
166
|
+
"""
|
|
167
|
+
if post <= 0 or bin_width <= 0:
|
|
168
|
+
return []
|
|
169
|
+
bins = []
|
|
170
|
+
edge = 0.0
|
|
171
|
+
while edge < post:
|
|
172
|
+
bin_end = min(edge + bin_width, post)
|
|
173
|
+
mask = (rel_x >= edge) & (rel_x < bin_end)
|
|
174
|
+
mean_val = float(np.mean(y[mask])) if mask.any() else float("nan")
|
|
175
|
+
bins.append({"bin_start": edge, "bin_end": bin_end, "mean": mean_val})
|
|
176
|
+
edge = bin_end
|
|
177
|
+
return bins
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def compute_peri_event_from_trace(rel_x, y, post, bin_width=1.0):
|
|
181
|
+
"""
|
|
182
|
+
Peak amplitude, time-to-peak (latency), and mean-time-bins from an
|
|
183
|
+
already-extracted, already-relative-to-event trace (0 = event time).
|
|
184
|
+
|
|
185
|
+
Peak amplitude/latency are deliberately post-event only (rel_x >= 0)
|
|
186
|
+
— a pre-event sample can't be a response to the event. Uses the same
|
|
187
|
+
signed argmax(|y|) convention peth.py's own single-click peak-Z stat
|
|
188
|
+
already uses, rather than a plain positive-only max, so "peak" can
|
|
189
|
+
correctly capture a strong inhibitory (negative-going) response too.
|
|
190
|
+
|
|
191
|
+
Parameters
|
|
192
|
+
----------
|
|
193
|
+
rel_x : array
|
|
194
|
+
Time relative to the event (seconds), 0 = event time.
|
|
195
|
+
y : array
|
|
196
|
+
Signal values aligned to rel_x.
|
|
197
|
+
post : float
|
|
198
|
+
Seconds after the event covered by rel_x/y — bounds the
|
|
199
|
+
mean-time-bins range and is passed separately (rather than
|
|
200
|
+
inferred from rel_x.max()) so a caller with a fixed window size
|
|
201
|
+
(e.g. Event PETH, same post for every trial) gets identical bin
|
|
202
|
+
edges across trials even if a particular trial's samples don't
|
|
203
|
+
quite reach the nominal edge.
|
|
204
|
+
bin_width : float
|
|
205
|
+
Width of each mean-time-bin, in seconds.
|
|
206
|
+
|
|
207
|
+
Returns
|
|
208
|
+
-------
|
|
209
|
+
dict with peak_amplitude, latency (both float — 0.0 if no post-event
|
|
210
|
+
samples exist) and mean_bins (list of dict, see _mean_time_bins).
|
|
211
|
+
"""
|
|
212
|
+
rel_x = as_float64(rel_x)
|
|
213
|
+
y = as_float64(y)
|
|
214
|
+
mask = rel_x >= 0
|
|
215
|
+
if not mask.any():
|
|
216
|
+
peak_amplitude, latency = 0.0, 0.0
|
|
217
|
+
else:
|
|
218
|
+
rx, ry = rel_x[mask], y[mask]
|
|
219
|
+
idx = int(np.argmax(np.abs(ry)))
|
|
220
|
+
peak_amplitude, latency = float(ry[idx]), float(rx[idx])
|
|
221
|
+
return {
|
|
222
|
+
"peak_amplitude": peak_amplitude,
|
|
223
|
+
"latency": latency,
|
|
224
|
+
"mean_bins": _mean_time_bins(rel_x, y, post, bin_width),
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def compute_peri_event_matrix(time_axis, trial_matrix, post, bin_width=1.0):
|
|
229
|
+
"""
|
|
230
|
+
Per-trial + group (mean-trace) peak amplitude / time-to-peak /
|
|
231
|
+
mean-time-bins for an already-built trial x time matrix (see
|
|
232
|
+
compute_event_zscore_peth) — mirrors compute_auc_matrix exactly, so
|
|
233
|
+
Event PETH can compute both AUC and these stats the same way.
|
|
234
|
+
|
|
235
|
+
Parameters
|
|
236
|
+
----------
|
|
237
|
+
time_axis : array, shape (num_bins,)
|
|
238
|
+
Already relative to the event (-pre..+post), per
|
|
239
|
+
compute_event_zscore_peth's convention.
|
|
240
|
+
trial_matrix : array, shape (n_trials, num_bins)
|
|
241
|
+
post : float
|
|
242
|
+
Seconds after the event covered by time_axis.
|
|
243
|
+
bin_width : float
|
|
244
|
+
Width of each mean-time-bin, in seconds.
|
|
245
|
+
|
|
246
|
+
Returns
|
|
247
|
+
-------
|
|
248
|
+
dict with:
|
|
249
|
+
per_trial : list of dict (one per row of trial_matrix, same
|
|
250
|
+
order), each {"peak_amplitude", "latency", "mean_bins"}
|
|
251
|
+
group : dict, same shape, computed on trial_matrix's
|
|
252
|
+
mean(axis=0) — peak/latency 0.0 and mean_bins empty if
|
|
253
|
+
trial_matrix has 0 rows
|
|
254
|
+
"""
|
|
255
|
+
time_axis = as_float64(time_axis)
|
|
256
|
+
trial_matrix = as_float64(trial_matrix)
|
|
257
|
+
per_trial = [compute_peri_event_from_trace(time_axis, row, post, bin_width)
|
|
258
|
+
for row in trial_matrix]
|
|
259
|
+
if trial_matrix.shape[0] > 0:
|
|
260
|
+
group = compute_peri_event_from_trace(time_axis, trial_matrix.mean(axis=0), post, bin_width)
|
|
261
|
+
else:
|
|
262
|
+
group = {"peak_amplitude": 0.0, "latency": 0.0, "mean_bins": []}
|
|
263
|
+
return {"per_trial": per_trial, "group": group}
|
PyATCLI/analysis/fft.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""
|
|
2
|
+
analysis/fft.py
|
|
3
|
+
-----------------
|
|
4
|
+
FFT of a windowed signal segment, plus picking out its top peaks as
|
|
5
|
+
data. Drawing those peaks onto a plot (labels, arrows, a vertical line)
|
|
6
|
+
is presentation, not computation, and lives in physicsanalysis_qt's own
|
|
7
|
+
analysis/fft.py instead — this file only ever returns numbers.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from scipy.signal import detrend, find_peaks
|
|
12
|
+
|
|
13
|
+
from ..numeric import as_float64
|
|
14
|
+
from .shared import window_around
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def compute_fft_slice(time_array, signal, center_t, fs, window=None, pre=None, post=None):
|
|
18
|
+
"""
|
|
19
|
+
Extract a time window around center_t and compute its FFT.
|
|
20
|
+
|
|
21
|
+
Applies mean removal and linear detrending before FFT to eliminate
|
|
22
|
+
the DC spike and slow drift, making physiological frequencies
|
|
23
|
+
(breathing ~0.3 Hz, heart rate ~1 Hz) visible.
|
|
24
|
+
|
|
25
|
+
Supports either a symmetric `window` (split evenly before/after
|
|
26
|
+
center_t, legacy behaviour) or an asymmetric `pre`/`post` pair. If
|
|
27
|
+
pre/post are given they take precedence over window.
|
|
28
|
+
|
|
29
|
+
Parameters
|
|
30
|
+
----------
|
|
31
|
+
time_array : array
|
|
32
|
+
signal : array
|
|
33
|
+
center_t : float
|
|
34
|
+
Center time in seconds
|
|
35
|
+
fs : float
|
|
36
|
+
Sampling frequency in Hz
|
|
37
|
+
window : float or None
|
|
38
|
+
Total window size in seconds, split evenly before/after center_t.
|
|
39
|
+
Ignored if pre/post are given.
|
|
40
|
+
pre : float or None
|
|
41
|
+
Seconds before center_t to include. Defaults to window/2.
|
|
42
|
+
post : float or None
|
|
43
|
+
Seconds after center_t to include. Defaults to window/2.
|
|
44
|
+
|
|
45
|
+
Returns
|
|
46
|
+
-------
|
|
47
|
+
freqs : array
|
|
48
|
+
power : array
|
|
49
|
+
seg_x : array
|
|
50
|
+
seg_y : array
|
|
51
|
+
"""
|
|
52
|
+
seg_x, seg_y = window_around(time_array, signal, center_t, window, pre, post)
|
|
53
|
+
|
|
54
|
+
if len(seg_y) < 4:
|
|
55
|
+
return np.array([]), np.array([]), seg_x, seg_y
|
|
56
|
+
|
|
57
|
+
seg_y = detrend(seg_y, type='linear') # removes mean and linear trend
|
|
58
|
+
windowed = seg_y * np.hanning(len(seg_y))
|
|
59
|
+
|
|
60
|
+
n = len(windowed)
|
|
61
|
+
fft_y = np.fft.rfft(windowed)
|
|
62
|
+
freqs = np.fft.rfftfreq(n, d=1.0 / fs)
|
|
63
|
+
power = (np.abs(fft_y) ** 2) / n
|
|
64
|
+
|
|
65
|
+
return freqs, power, seg_x, seg_y
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def find_fft_peaks(freqs, power, n_peaks=3):
|
|
69
|
+
"""
|
|
70
|
+
Find the top N peaks in a power spectrum, as data.
|
|
71
|
+
|
|
72
|
+
Parameters
|
|
73
|
+
----------
|
|
74
|
+
freqs : array
|
|
75
|
+
power : array
|
|
76
|
+
n_peaks: int
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
list of dict, each {"freq_hz": float, "power": float, "bpm": float},
|
|
81
|
+
sorted by power descending. Empty if fewer than 3 usable frequency
|
|
82
|
+
bins (freqs >= 0.05 Hz) exist, or no peak clears the prominence bar.
|
|
83
|
+
"""
|
|
84
|
+
freqs = as_float64(freqs)
|
|
85
|
+
power = as_float64(power)
|
|
86
|
+
mask = freqs >= 0.05
|
|
87
|
+
f_m = freqs[mask]
|
|
88
|
+
p_m = power[mask]
|
|
89
|
+
if len(p_m) < 3:
|
|
90
|
+
return []
|
|
91
|
+
min_prom = 0.05 * p_m.max()
|
|
92
|
+
peaks, _ = find_peaks(p_m, prominence=min_prom)
|
|
93
|
+
if len(peaks) == 0:
|
|
94
|
+
return []
|
|
95
|
+
top = sorted(peaks, key=lambda i: p_m[i], reverse=True)[:n_peaks]
|
|
96
|
+
return [
|
|
97
|
+
{"freq_hz": float(f_m[i]), "power": float(p_m[i]), "bpm": float(f_m[i] * 60)}
|
|
98
|
+
for i in top
|
|
99
|
+
]
|