fibphot 0.1.0__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.
fibphot/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from __future__ import annotations
2
+
3
+ from .state import PhotometryState, StageRecord
4
+
5
+ __all__ = ["PhotometryState", "StageRecord"]
6
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,257 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+ from typing import Literal
6
+
7
+ import numpy as np
8
+
9
+ from ..state import PhotometryState
10
+ from ..types import FloatArray
11
+
12
+ AlignMode = Literal["intersection", "union"]
13
+ TimeRef = Literal["absolute", "start"]
14
+ InterpKind = Literal["linear", "nearest"]
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class AlignedSignals:
19
+ """
20
+ Container for a time-aligned stack of signals.
21
+
22
+ aligned has shape (n_states, n_channels, n_time).
23
+ """
24
+
25
+ time_seconds: FloatArray
26
+ aligned: FloatArray
27
+ channel_names: tuple[str, ...]
28
+ subjects: tuple[str | None, ...]
29
+ align_mode: AlignMode
30
+ time_ref: TimeRef
31
+ dt: float
32
+
33
+
34
+ def _as_relative_time(t: FloatArray) -> FloatArray:
35
+ t = np.asarray(t, dtype=float)
36
+ return t - float(t[0])
37
+
38
+
39
+ def _infer_dt(states: Sequence[PhotometryState]) -> float:
40
+ dts: list[float] = []
41
+ for s in states:
42
+ dt = np.diff(np.asarray(s.time_seconds, dtype=float))
43
+ if dt.size == 0:
44
+ continue
45
+ dts.append(float(np.nanmedian(dt)))
46
+ if not dts:
47
+ raise ValueError(
48
+ "Cannot infer dt from empty or degenerate time arrays."
49
+ )
50
+ return float(np.nanmedian(np.asarray(dts, dtype=float)))
51
+
52
+
53
+ def _time_window(
54
+ times: list[FloatArray],
55
+ mode: AlignMode,
56
+ ) -> tuple[float, float]:
57
+ starts = [float(t[0]) for t in times]
58
+ ends = [float(t[-1]) for t in times]
59
+
60
+ if mode == "intersection":
61
+ t0 = max(starts)
62
+ t1 = min(ends)
63
+ elif mode == "union":
64
+ t0 = min(starts)
65
+ t1 = max(ends)
66
+ else:
67
+ raise ValueError(f"Unknown align mode: {mode!r}")
68
+
69
+ if not np.isfinite(t0) or not np.isfinite(t1) or t1 <= t0:
70
+ raise ValueError(
71
+ f"Invalid common window from mode={mode!r}: ({t0}, {t1})."
72
+ )
73
+ return t0, t1
74
+
75
+
76
+ def _make_grid(t0: float, t1: float, dt: float) -> FloatArray:
77
+ n = int(np.floor((t1 - t0) / dt)) + 1
78
+ if n < 2:
79
+ raise ValueError("Common time grid would have <2 points.")
80
+ return t0 + dt * np.arange(n, dtype=float)
81
+
82
+
83
+ def _interp_1d(
84
+ x: FloatArray,
85
+ y: FloatArray,
86
+ x_new: FloatArray,
87
+ *,
88
+ kind: InterpKind,
89
+ fill: float,
90
+ ) -> FloatArray:
91
+ x = np.asarray(x, dtype=float)
92
+ y = np.asarray(y, dtype=float)
93
+ x_new = np.asarray(x_new, dtype=float)
94
+
95
+ mask = np.isfinite(x) & np.isfinite(y)
96
+ x0 = x[mask]
97
+ y0 = y[mask]
98
+ if x0.size < 2:
99
+ return np.full_like(x_new, fill, dtype=float)
100
+
101
+ order = np.argsort(x0)
102
+ x0 = x0[order]
103
+ y0 = y0[order]
104
+
105
+ if kind == "linear":
106
+ return np.interp(x_new, x0, y0, left=fill, right=fill).astype(float)
107
+
108
+ if kind == "nearest":
109
+ idx = np.searchsorted(x0, x_new, side="left")
110
+ idx = np.clip(idx, 0, x0.size - 1)
111
+ left = np.clip(idx - 1, 0, x0.size - 1)
112
+
113
+ choose_left = np.abs(x_new - x0[left]) <= np.abs(x_new - x0[idx])
114
+ out = np.where(choose_left, y0[left], y0[idx]).astype(float)
115
+
116
+ out[(x_new < x0[0]) | (x_new > x0[-1])] = fill
117
+ return out
118
+
119
+ raise ValueError(f"Unknown interpolation kind: {kind!r}")
120
+
121
+
122
+ def align_collection_signals(
123
+ states: Sequence[PhotometryState],
124
+ *,
125
+ channels: Sequence[str] | None = None,
126
+ align: AlignMode = "intersection",
127
+ time_ref: TimeRef = "start",
128
+ dt: float | None = None,
129
+ target_fs: float | None = None,
130
+ interpolation: InterpKind = "linear",
131
+ fill: float = float("nan"),
132
+ ) -> AlignedSignals:
133
+ """
134
+ Align a set of states to a common time axis via interpolation.
135
+
136
+ align="intersection":
137
+ Uses only the time interval present in all states (truncate behaviour).
138
+ align="union":
139
+ Uses the full time span across states and fills missing regions (pad behaviour).
140
+
141
+ time_ref="start":
142
+ Treats each state's time as relative to its own start time.
143
+ time_ref="absolute":
144
+ Uses each state's original time_seconds values.
145
+ """
146
+ if not states:
147
+ raise ValueError("No states provided.")
148
+
149
+ if channels is None:
150
+ channel_names = states[0].channel_names
151
+ idxs = list(range(states[0].n_signals))
152
+ else:
153
+ channel_names = tuple(c.lower() for c in channels)
154
+ idxs = [states[0].idx(c) for c in channel_names]
155
+
156
+ for s in states[1:]:
157
+ for c in channel_names:
158
+ _ = s.idx(c)
159
+
160
+ if target_fs is not None:
161
+ if target_fs <= 0:
162
+ raise ValueError("target_fs must be > 0.")
163
+ dt_use = 1.0 / float(target_fs)
164
+ else:
165
+ dt_use = float(dt) if dt is not None else _infer_dt(states)
166
+
167
+ times: list[FloatArray] = []
168
+ for s in states:
169
+ t = np.asarray(s.time_seconds, dtype=float)
170
+ if time_ref == "start":
171
+ t = _as_relative_time(t)
172
+ times.append(t)
173
+
174
+ t0, t1 = _time_window(times, align)
175
+ grid = _make_grid(t0, t1, dt_use)
176
+
177
+ aligned = np.full(
178
+ (len(states), len(idxs), grid.size),
179
+ fill,
180
+ dtype=float,
181
+ )
182
+
183
+ for si, s in enumerate(states):
184
+ t = times[si]
185
+ for cj, idx in enumerate(idxs):
186
+ y = np.asarray(s.signals[idx], dtype=float)
187
+ aligned[si, cj] = _interp_1d(
188
+ t,
189
+ y,
190
+ grid,
191
+ kind=interpolation,
192
+ fill=fill,
193
+ )
194
+
195
+ subjects: tuple[str | None, ...] = tuple(
196
+ getattr(s, "subject", None) for s in states
197
+ )
198
+
199
+ return AlignedSignals(
200
+ time_seconds=grid,
201
+ aligned=aligned,
202
+ channel_names=tuple(channel_names),
203
+ subjects=subjects,
204
+ align_mode=align,
205
+ time_ref=time_ref,
206
+ dt=dt_use,
207
+ )
208
+
209
+
210
+ def mean_aligned(
211
+ aligned: AlignedSignals,
212
+ ) -> tuple[FloatArray, FloatArray, FloatArray, FloatArray]:
213
+ """
214
+ Compute mean, std, sem, and n (per channel/time) from an aligned stack.
215
+ """
216
+ x = np.asarray(aligned.aligned, dtype=float)
217
+
218
+ n = np.sum(np.isfinite(x), axis=0).astype(float)
219
+ mean = np.nanmean(x, axis=0)
220
+ std = np.nanstd(x, axis=0)
221
+
222
+ sem = std / np.sqrt(np.where(n <= 0, np.nan, n))
223
+ return mean, std, sem, n
224
+
225
+
226
+ def mean_state_from_aligned(
227
+ aligned: AlignedSignals,
228
+ *,
229
+ name: str = "group_mean",
230
+ ) -> PhotometryState:
231
+ """
232
+ Return a PhotometryState whose signals are the group mean.
233
+
234
+ Additional statistics are stored in derived:
235
+ - derived["group_std"]
236
+ - derived["group_sem"]
237
+ - derived["group_n"]
238
+ """
239
+ mean, std, sem, n = mean_aligned(aligned)
240
+
241
+ return PhotometryState(
242
+ time_seconds=aligned.time_seconds,
243
+ signals=mean,
244
+ channel_names=aligned.channel_names,
245
+ derived={
246
+ "group_std": std,
247
+ "group_sem": sem,
248
+ "group_n": n,
249
+ },
250
+ metadata={
251
+ "kind": name,
252
+ "align_mode": aligned.align_mode,
253
+ "time_ref": aligned.time_ref,
254
+ "dt": aligned.dt,
255
+ "subjects": list(aligned.subjects),
256
+ },
257
+ )
@@ -0,0 +1,354 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Literal
5
+
6
+ import numpy as np
7
+
8
+ from ..state import PhotometryState
9
+ from ..types import FloatArray
10
+ from .report import AnalysisResult, AnalysisWindow
11
+
12
+ AUCMode = Literal["signed", "positive", "negative", "absolute"]
13
+ BaselineRef = Literal[
14
+ "zero",
15
+ "window_mean",
16
+ "window_median",
17
+ "pre_mean",
18
+ "pre_median",
19
+ "window_quantile",
20
+ "pre_quantile",
21
+ ]
22
+
23
+
24
+ def _trapz(y: FloatArray, x: FloatArray) -> float:
25
+ # numpy >= 2.0
26
+ if hasattr(np, "trapezoid"):
27
+ return float(np.trapezoid(y, x)) # type: ignore[attr-defined]
28
+ return float(np.trapz(y, x)) # type: ignore[attr-defined]
29
+
30
+
31
+ def _as_float_array(x: FloatArray) -> np.ndarray:
32
+ return np.asarray(x, dtype=float)
33
+
34
+
35
+ def _resolve_window_seconds(
36
+ state: PhotometryState,
37
+ window: AnalysisWindow | None,
38
+ ) -> tuple[np.ndarray, float, float, int, int]:
39
+ """
40
+ Returns:
41
+ mask: bool array over samples (finite points inside window)
42
+ t0, t1: window bounds in seconds (inclusive endpoints for display)
43
+ i0, i1: window bounds in samples [i0, i1) for pre-window logic
44
+ """
45
+ t = _as_float_array(state.time_seconds)
46
+ n = int(t.size)
47
+
48
+ if n == 0:
49
+ raise ValueError("State has zero samples.")
50
+
51
+ if window is None:
52
+ # Whole trace (finite points only)
53
+ mask = np.isfinite(t)
54
+ i0, i1 = 0, n
55
+ t0, t1 = float(t[0]), float(t[-1])
56
+ return mask, t0, t1, i0, i1
57
+
58
+ if window.ref == "seconds":
59
+ t0 = float(window.start)
60
+ t1 = float(window.end)
61
+ if t0 > t1:
62
+ raise ValueError(f"Expected start <= end, got {t0} > {t1}.")
63
+
64
+ mask = np.isfinite(t) & (t >= t0) & (t <= t1)
65
+
66
+ # i0/i1 are best-effort sample bounds for the pre-window (not exact if irregular t)
67
+ # We pick the first/last included sample indices.
68
+ idx = np.flatnonzero(mask)
69
+ if idx.size == 0:
70
+ # window empty
71
+ return mask, t0, t1, 0, 0
72
+ i0 = int(idx[0])
73
+ i1 = int(idx[-1] + 1)
74
+ return mask, t0, t1, i0, i1
75
+
76
+ if window.ref == "samples":
77
+ i0 = int(window.start)
78
+ i1 = int(window.end)
79
+ if i0 < 0 or i1 < 0:
80
+ raise ValueError("Sample windows must be non-negative.")
81
+ if i0 >= i1:
82
+ raise ValueError(
83
+ f"Expected start < end for samples, got {i0} >= {i1}."
84
+ )
85
+ i0 = max(0, min(n, i0))
86
+ i1 = max(0, min(n, i1))
87
+
88
+ mask = np.isfinite(t)
89
+ mask &= np.zeros(n, dtype=bool)
90
+ mask[i0:i1] = True
91
+
92
+ # for display, map to time bounds if possible
93
+ t0 = float(t[i0]) if i0 < n else float(t[-1])
94
+ t1 = float(t[i1 - 1]) if (i1 - 1) < n and i1 > 0 else float(t[-1])
95
+ return mask, t0, t1, i0, i1
96
+
97
+ raise ValueError(f"Unknown window.ref: {window.ref!r}")
98
+
99
+
100
+ def _baseline_value(
101
+ state: PhotometryState,
102
+ y: FloatArray,
103
+ *,
104
+ window_mask: np.ndarray,
105
+ t0: float,
106
+ t1: float,
107
+ i0: int,
108
+ i1: int,
109
+ baseline: BaselineRef,
110
+ pre_seconds: float,
111
+ quantile: float,
112
+ ) -> float:
113
+ """
114
+ baseline options:
115
+ - window_* computed over the analysis window
116
+ - pre_* computed over [t0-pre_seconds, t0] OR [i0-pre_samples, i0)
117
+ and falls back to window if empty
118
+ """
119
+ t = _as_float_array(state.time_seconds)
120
+ y = _as_float_array(y)
121
+
122
+ if baseline == "zero":
123
+ return 0.0
124
+
125
+ def _stat(vals: np.ndarray) -> float:
126
+ if vals.size == 0:
127
+ return float("nan")
128
+ if baseline.endswith("mean"):
129
+ return float(np.nanmean(vals))
130
+ if baseline.endswith("median"):
131
+ return float(np.nanmedian(vals))
132
+ if baseline.endswith("quantile"):
133
+ q = float(quantile)
134
+ if not (0.0 <= q <= 1.0):
135
+ raise ValueError("quantile must be in [0, 1].")
136
+ return float(np.nanquantile(vals, q))
137
+ raise ValueError(f"Unhandled baseline option: {baseline!r}")
138
+
139
+ if baseline.startswith("window_"):
140
+ m = window_mask & np.isfinite(y)
141
+ return _stat(y[m])
142
+
143
+ if baseline.startswith("pre_"):
144
+ # Prefer seconds logic (more robust to variable dt), but we also have sample bounds.
145
+ pre0 = t0 - float(pre_seconds)
146
+ pre1 = t0
147
+
148
+ m = np.isfinite(t) & np.isfinite(y) & (t >= pre0) & (t <= pre1)
149
+
150
+ # If pre-window is empty (event near start), fall back to sample-based pre,
151
+ # then to window.
152
+ if int(np.sum(m)) < 2:
153
+ if (
154
+ state.n_samples > 1
155
+ and np.isfinite(state.sampling_rate)
156
+ and state.sampling_rate > 0
157
+ ):
158
+ pre_n = int(
159
+ round(float(pre_seconds) * float(state.sampling_rate))
160
+ )
161
+ else:
162
+ pre_n = 0
163
+
164
+ if pre_n > 0 and i0 > 0:
165
+ j0 = max(0, i0 - pre_n)
166
+ j1 = i0
167
+ m = np.isfinite(t) & np.isfinite(y)
168
+ mm = np.zeros_like(m, dtype=bool)
169
+ mm[j0:j1] = True
170
+ m &= mm
171
+
172
+ if int(np.sum(m)) < 2:
173
+ m = window_mask & np.isfinite(y)
174
+
175
+ return _stat(y[m])
176
+
177
+ raise ValueError(f"Unknown baseline: {baseline!r}")
178
+
179
+
180
+ def _contrib(u: np.ndarray, mode: AUCMode) -> np.ndarray:
181
+ if mode == "signed":
182
+ return u
183
+ if mode == "positive":
184
+ return np.clip(u, 0.0, np.inf)
185
+ if mode == "negative":
186
+ return np.clip(u, -np.inf, 0.0)
187
+ if mode == "absolute":
188
+ return np.abs(u)
189
+ raise ValueError(f"Unknown mode: {mode!r}")
190
+
191
+
192
+ def auc_window(
193
+ t: FloatArray,
194
+ y: FloatArray,
195
+ *,
196
+ t0: float,
197
+ t1: float,
198
+ mode: AUCMode = "positive",
199
+ baseline_value: float = 0.0,
200
+ ) -> dict[str, float]:
201
+ """
202
+ Pure numeric AUC over [t0, t1] relative to a *provided* baseline value.
203
+ (Convenient for unit tests / standalone use.)
204
+ """
205
+ t = _as_float_array(t)
206
+ y = _as_float_array(y)
207
+
208
+ if t0 > t1:
209
+ raise ValueError(f"Expected t0 <= t1, got {t0} > {t1}.")
210
+
211
+ m = np.isfinite(t) & np.isfinite(y) & (t >= t0) & (t <= t1)
212
+ tt = t[m]
213
+ yy = y[m]
214
+ if tt.size < 2:
215
+ return {
216
+ "auc": float("nan"),
217
+ "mean": float("nan"),
218
+ "n_points": float(tt.size),
219
+ }
220
+
221
+ u = yy - float(baseline_value)
222
+ c = _contrib(u, mode)
223
+ area = _trapz(c, tt)
224
+
225
+ duration = float(tt[-1] - tt[0])
226
+ mean_amp = (
227
+ area / duration
228
+ if duration > 0 and np.isfinite(duration)
229
+ else float("nan")
230
+ )
231
+
232
+ return {
233
+ "auc": float(area),
234
+ "mean": float(mean_amp),
235
+ "n_points": float(tt.size),
236
+ }
237
+
238
+
239
+ @dataclass(frozen=True, slots=True)
240
+ class AUC:
241
+ """
242
+ Windowed AUC analysis that returns an AnalysisResult.
243
+
244
+ Example
245
+ -------
246
+ res = AUC(
247
+ signal="gcamp",
248
+ window=AnalysisWindow(0, 400, ref="seconds", label="cue window"),
249
+ mode="positive",
250
+ baseline="pre_median",
251
+ pre_seconds=10.0,
252
+ )(state)
253
+
254
+ Then attach to a report:
255
+ report = PhotometryReport(state).add(res)
256
+ """
257
+
258
+ signal: str
259
+ window: AnalysisWindow | None = None
260
+ mode: AUCMode = "positive"
261
+ baseline: BaselineRef = "pre_median"
262
+ pre_seconds: float = 10.0
263
+ quantile: float = 0.1
264
+
265
+ name: str = "auc"
266
+
267
+ def __call__(self, state: PhotometryState) -> AnalysisResult:
268
+ t = _as_float_array(state.time_seconds)
269
+ y = _as_float_array(state.channel(self.signal))
270
+
271
+ window_mask, t0, t1, i0, i1 = _resolve_window_seconds(
272
+ state, self.window
273
+ )
274
+
275
+ # windowed samples
276
+ m = window_mask & np.isfinite(y) & np.isfinite(t)
277
+ tt = t[m]
278
+ yy = y[m]
279
+
280
+ if tt.size < 2:
281
+ return AnalysisResult(
282
+ name=self.name,
283
+ channel=self.signal.lower(),
284
+ window=self.window,
285
+ params={
286
+ "mode": self.mode,
287
+ "baseline": self.baseline,
288
+ "pre_seconds": float(self.pre_seconds),
289
+ "quantile": float(self.quantile),
290
+ },
291
+ metrics={
292
+ "auc": float("nan"),
293
+ "mean": float("nan"),
294
+ "baseline": float("nan"),
295
+ "t0": float(t0),
296
+ "t1": float(t1),
297
+ "duration_s": float(t1 - t0),
298
+ "n_points": float(tt.size),
299
+ },
300
+ arrays={},
301
+ notes="Window contained <2 finite points; AUC not computed.",
302
+ )
303
+
304
+ b = _baseline_value(
305
+ state,
306
+ y,
307
+ window_mask=window_mask,
308
+ t0=t0,
309
+ t1=t1,
310
+ i0=i0,
311
+ i1=i1,
312
+ baseline=self.baseline,
313
+ pre_seconds=self.pre_seconds,
314
+ quantile=self.quantile,
315
+ )
316
+
317
+ u = yy - b
318
+ contrib = _contrib(u, self.mode)
319
+
320
+ area = _trapz(contrib, tt)
321
+ duration = float(tt[-1] - tt[0])
322
+ mean_amp = (
323
+ area / duration
324
+ if duration > 0 and np.isfinite(duration)
325
+ else float("nan")
326
+ )
327
+
328
+ return AnalysisResult(
329
+ name=self.name,
330
+ channel=self.signal.lower(),
331
+ window=self.window,
332
+ params={
333
+ "mode": self.mode,
334
+ "baseline": self.baseline,
335
+ "pre_seconds": float(self.pre_seconds),
336
+ "quantile": float(self.quantile),
337
+ },
338
+ metrics={
339
+ "auc": float(area),
340
+ "mean": float(mean_amp),
341
+ "baseline": float(b),
342
+ "t0": float(t0),
343
+ "t1": float(t1),
344
+ "duration_s": float(t1 - t0),
345
+ "n_points": float(tt.size),
346
+ },
347
+ arrays={
348
+ # Small, window-only arrays: safe to store and perfect for plotting/QA
349
+ "t_window": tt,
350
+ "y_window": yy,
351
+ "u_window": u,
352
+ "contrib": contrib,
353
+ },
354
+ )