Skip to content

Python API

photosvi.api is the part of the package meant to be used from outside it: loading a recording, fitting it and reading the result. Its interfaces stay stable within a major version. The pages under Internals document the model and inference code behind it, which can change between versions.

Recordings

photosvi.api.Session dataclass

Session(trace, fs, inj_t, name='session', metadata=dict(), mask=None)

One recording: a trace, when the injection happened, and who it came from.

trace is corrected dF/F, one dimension. Preprocessing -- isosbestic correction, bleaching, dF/F -- happens upstream of this package.

metadata carries the experimental design: animal, drug, dose, and whatever else the study records. It is free-form here and becomes the index vectors the hierarchical model reads, so a pilot that only fits single recordings should still fill it in -- it costs nothing now and is the difference between having a cohort later and having a pile of unlabelled traces.

from_channels classmethod

from_channels(signal, isosbestic, fs, *, inj_s, inj_end_s=None, mask_min_s=0.0, als_lambda=None, name='session', **metadata)

A Session from the raw sensor and isosbestic channels, corrected to dF/F.

The correction is the one applied to Doric files: the isosbestic channel is scaled onto the sensor's baseline over the stretch before the injection and divided out (photosvi.data.preprocess.correct_isosbestic). One second is trimmed from each end, so inj_t of the result is shifted accordingly. The handling window, from inj_s to the later of inj_end_s and inj_s + mask_min_s, is masked from the likelihood.

Source code in src/photosvi/api.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@classmethod
def from_channels(cls, signal, isosbestic, fs: float, *, inj_s: float,
                  inj_end_s: float | None = None, mask_min_s: float = 0.0,
                  als_lambda: float | None = None, name: str = "session",
                  **metadata) -> Session:
    """A Session from the raw sensor and isosbestic channels, corrected to dF/F.

    The correction is the one applied to Doric files: the isosbestic channel is
    scaled onto the sensor's baseline over the stretch before the injection and
    divided out (`photosvi.data.preprocess.correct_isosbestic`). One second is trimmed
    from each end, so `inj_t` of the result is shifted accordingly. The handling
    window, from `inj_s` to the later of `inj_end_s` and `inj_s + mask_min_s`, is
    masked from the likelihood.
    """
    return _from_channels(signal, isosbestic, fs, inj_start_s=inj_s, inj_end_s=inj_end_s,
                          mask_min_s=mask_min_s, als_lambda=als_lambda, name=name,
                          **metadata)[0]

photosvi.api.Study dataclass

Study(sessions)

A set of sessions fitted together. One session is a legitimate study.

photosvi.api.load_doric_session

load_doric_session(path, *, inj_start_s=None, inj_end_s=None, event=None, mask_min_s=0.0, als_lambda=None, name=None, **metadata)

A Doric recording as a Session: isosbestic-corrected dF/F, injection and its mask.

The injection is the user's inj_start_s (and inj_end_s, the end of the handling window) when given; otherwise the file's injection event -- event by name, or the last one recorded -- and an error if there is neither. Bins from the injection to the later of inj_end_s and inj_start_s + mask_min_s are excluded from the likelihood: handling moves the fibre and produces transient-shaped artefacts at the moment the rate is meant to change. Returns the Session and a dict saying where the times came from.

Source code in src/photosvi/api.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def load_doric_session(path: Path | str, *, inj_start_s: float | None = None,
                       inj_end_s: float | None = None, event: str | None = None,
                       mask_min_s: float = 0.0, als_lambda: float | None = None,
                       name: str | None = None, **metadata) -> tuple[Session, dict]:
    """A Doric recording as a Session: isosbestic-corrected dF/F, injection and its mask.

    The injection is the user's `inj_start_s` (and `inj_end_s`, the end of the handling
    window) when given; otherwise the file's injection event -- `event` by name, or the
    last one recorded -- and an error if there is neither. Bins from the injection to the
    later of `inj_end_s` and `inj_start_s + mask_min_s` are excluded from the likelihood:
    handling moves the fibre and produces transient-shaped artefacts at the moment the rate
    is meant to change. Returns the Session and a dict saying where the times came from.
    """
    from photosvi.data.doric import read_doric

    path = Path(path)
    rec = read_doric(path)
    if inj_start_s is not None:
        start = float(inj_start_s)
        end = float(inj_end_s) if inj_end_s is not None else start
        source = "user"
    else:
        if not rec.events:
            raise ValueError(f"{path} records no injection events: give the injection "
                             "times (inj_start_s, inj_end_s)")
        key = event if event is not None else list(rec.events)[-1]
        if key not in rec.events:
            raise ValueError(f"no event {key!r} in {path}; it has {sorted(rec.events)}")
        start, end = rec.events[key]
        if inj_end_s is not None:
            end = float(inj_end_s)
        source = f"doric event {key!r}"
    session, info = _from_channels(rec.signal, rec.isosbestic, rec.fs, inj_start_s=start,
                                   inj_end_s=end, mask_min_s=mask_min_s,
                                   als_lambda=als_lambda, name=name or path.stem,
                                   **metadata)
    info = dict(source=source, **info, layout=rec.layout, events=rec.events)
    return session, info

photosvi.api.load_session

load_session(path, *, fs, inj_t=None, inj_s=None, column=None, isosbestic_column=None, name=None, **metadata)

Read one recording from .csv, .txt, .npy or .npz.

Without isosbestic_column the trace (column) must already be corrected dF/F. With it, column is the raw sensor channel and isosbestic_column the control, and the two are corrected to dF/F as a Doric file is (see Session.from_channels); one second is then trimmed from each end and inj_t of the result is shifted with it.

inj_s is accepted as well as inj_t because an injection is recorded in seconds by whoever ran the experiment, and converting by hand is a good way to be off by a factor of the sampling rate.

Source code in src/photosvi/api.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
def load_session(path: Path | str, *, fs: float, inj_t: int | None = None,
                 inj_s: float | None = None, column: str | int | None = None,
                 isosbestic_column: str | int | None = None,
                 name: str | None = None, **metadata) -> Session:
    """Read one recording from .csv, .txt, .npy or .npz.

    Without `isosbestic_column` the trace (`column`) must already be corrected dF/F. With
    it, `column` is the raw sensor channel and `isosbestic_column` the control, and the
    two are corrected to dF/F as a Doric file is (see `Session.from_channels`); one
    second is then trimmed from each end and `inj_t` of the result is shifted with it.

    `inj_s` is accepted as well as `inj_t` because an injection is recorded in
    seconds by whoever ran the experiment, and converting by hand is a good way to be
    off by a factor of the sampling rate.
    """
    path = Path(path)
    if inj_t is None and inj_s is None:
        raise ValueError("give the injection as inj_t (bins) or inj_s (seconds)")
    if inj_t is None:
        inj_t = int(round(inj_s * fs))
    name = name or path.stem
    if isosbestic_column is not None:
        if column is None:
            raise ValueError("with an isosbestic column, `column` must name the sensor "
                             "channel too")
        return Session.from_channels(_read_trace(path, column),
                                     _read_trace(path, isosbestic_column), fs,
                                     inj_s=inj_t / fs, name=name, **metadata)
    return Session(trace=_read_trace(path, column), fs=fs, inj_t=inj_t, name=name,
                   metadata=metadata)

photosvi.api.read_manifest

read_manifest(table, *, mask_min_s=0.0, fs=None)

The sessions a table lists, and for each where its injection times came from.

Source code in src/photosvi/cli/manifest.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def read_manifest(table: Path | str, *, mask_min_s: float = 0.0,
                  fs: float | None = None) -> tuple[list, list[dict[str, Any]]]:
    """The sessions a table lists, and for each where its injection times came from."""
    table = Path(table)
    with table.open(newline="") as fh:
        rows = list(csv.DictReader(fh))
    if not rows:
        raise ValueError(f"{table} lists no sessions")
    if "path" not in rows[0]:
        raise ValueError(f"{table} has no 'path' column; columns are {list(rows[0])}")
    sessions, infos = [], []
    for i, row in enumerate(rows, start=2):
        row = {k.strip(): (v or "").strip() for k, v in row.items() if k}
        p = Path(row["path"])
        p = p if p.is_absolute() else table.parent / p
        meta = {k: v for k, v in row.items() if k not in _KNOWN and v}
        try:
            s, info = load_recording(p, fs=_num(row.get("fs")) or fs,
                                     column=row.get("column") or None,
                                     isosbestic_column=row.get("isosbestic_column") or None,
                                     inj_start_s=_num(row.get("inj_start")),
                                     inj_end_s=_num(row.get("inj_end")),
                                     event=row.get("event") or None, mask_min_s=mask_min_s,
                                     **meta)
        except (ValueError, OSError) as exc:
            raise ValueError(f"{table}, line {i}: {exc}") from None
        sessions.append(s)
        infos.append(dict(path=str(p), name=s.name, **info))
    return sessions, infos

Fitting

photosvi.api.FitSettings dataclass

FitSettings(steps=None, max_steps=None, threads=4, device='auto', seed=0, event_threshold=None, refractory=None, lr=None, tau=None, window=None, sigma_y=None, ar_coeffs=None, mu_a=None, sigma_a=None, mark_prior_sd=None, mark_noise_units=None, mark_gate_floor=None, kernel_length=None, kernel=None)

Everything a caller may reasonably want to change, with defended defaults.

None means "use the shipped value" and is the default for every model hyperparameter, so a caller that changes nothing gets the paper's single-trace model: the configuration of PRODUCTION_CONFIG, with the noise scale, the AR coefficients and the mark distribution read off the recording as the paper reads them, and the mark prior and gate floor of REAL_DATA_CONFIG. Only the operational fields -- how long to run, how many threads, which device -- have literals here, because those are properties of the machine rather than of the model.

resolved

resolved(fs=None)

Every value this fit will actually use, with the shipped defaults filled in.

Durations the config gives in bins (kernel support, refractory window) are rescaled from its sampling rate to fs; without fs they are quoted at the config's own rate. Values read off the recording (sigma_y, ar_coeffs, mu_a, sigma_a) stay None here and are filled in by fit_session.

Source code in src/photosvi/api.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def resolved(self, fs: float | None = None) -> dict[str, Any]:
    """Every value this fit will actually use, with the shipped defaults filled in.

    Durations the config gives in bins (kernel support, refractory window) are
    rescaled from its sampling rate to `fs`; without `fs` they are quoted at the
    config's own rate. Values read off the recording (sigma_y, ar_coeffs, mu_a,
    sigma_a) stay None here and are filled in by `fit_session`.
    """
    c, rd = _shipped(), _shipped(REAL_DATA_CONFIG)["fit"]
    f, w, d, k = (c["fit"], c["warm"], c["detection"], c["kernel"])
    scale = (fs or c["data"]["fs"]) / c["data"]["fs"]
    mp = rd["mark_prior"]
    if mp["mu_sd"] != mp["log_sigma_sd"]:
        raise ValueError(f"{REAL_DATA_CONFIG}: one mark_prior_sd cannot carry {mp}")
    return dict(
        steps=self.steps if self.steps is not None else f["stop_min_steps"],
        max_steps=self.max_steps if self.max_steps is not None else f["max_steps"],
        threads=self.threads, device=self.device, seed=self.seed,
        event_threshold=(self.event_threshold if self.event_threshold is not None
                         else d["thresh"]),
        refractory=(self.refractory if self.refractory is not None
                    else max(1, int(round(d["refractory"] * scale)))),
        mf_thresh=d["mf_thresh"],
        lr=self.lr if self.lr is not None else f["lr"],
        tau=self.tau if self.tau is not None else f["tau"],
        window=self.window if self.window is not None else int(
            f.get("window", c.get("guide", {}).get("window", 10))),
        sigma_y=self.sigma_y,
        ar_coeffs=None if self.ar_coeffs is None else [float(v) for v in self.ar_coeffs],
        mu_a=self.mu_a, sigma_a=self.sigma_a,
        mark_prior_sd=(self.mark_prior_sd if self.mark_prior_sd is not None
                       else float(mp["mu_sd"])),
        mark_noise_units=_noise_units_default(self.mark_noise_units, f),
        mark_gate_floor=(self.mark_gate_floor if self.mark_gate_floor is not None
                         else float(f.get("mark_gate_floor", rd["mark_gate_floor"]))),
        architecture=f.get("architecture", "legacy"),
        kernel_length=(self.kernel_length if self.kernel_length is not None
                       else int(round(k["length"] * scale))),
        kernel=dict(self.kernel) if self.kernel else dict(k["fit"]),
        warm=dict(w),
        beta0_prior_scale=f["beta0_prior_scale"],
        beta_inj_prior_loc=f["beta_inj_prior_loc"],
        beta_inj_prior_scale=f["beta_inj_prior_scale"],
        beta_prior=f["beta_prior"], beta_guide=f["beta_guide"],
        stop_tol=f["stop_tol"], stop_window=f["stop_window"],
        # The shipped probe interval, untouched, unless the caller asked for a
        # shorter run than it can resolve. The plateau is only checked on a probe,
        # so a probe larger than the minimum makes the minimum meaningless --
        # asking for 30 steps and getting 60000 because the first check lands at
        # 3000. Narrowing it by default would change the validated path, so the
        # default is the config value exactly.
        stop_probe=(f["stop_probe"] if self.steps is None
                    else min(f["stop_probe"],
                             max(1, self.steps // f["stop_window"]))),
    )

photosvi.api.fit_session

fit_session(session, settings=None, *, on_progress=None, probe_every=250)

Fit one recording and return its readouts.

The model is built through PointsSetup, the same path the paper's benchmark uses, so this cannot drift from the validated configuration -- and stopping uses the same plateau rule, so it converges rather than running a fixed number of steps that happens to be too few.

on_progress is called every probe_every steps with the step number, the running ELBO and the current estimate. A forty-minute recording is ten minutes of fitting on four CPU threads, so anything with a user in front of it needs a progress channel rather than a return value.

Source code in src/photosvi/api.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
def fit_session(session: Session, settings: FitSettings | None = None, *,
                on_progress: Callable[[dict[str, Any]], None] | None = None,
                probe_every: int = 250) -> Result:
    """Fit one recording and return its readouts.

    The model is built through `PointsSetup`, the same path the paper's benchmark
    uses, so this cannot drift from the validated configuration -- and stopping uses
    the same plateau rule, so it converges rather than running a fixed number of
    steps that happens to be too few.

    `on_progress` is called every `probe_every` steps with the step number, the
    running ELBO and the current estimate. A forty-minute recording is ten minutes of
    fitting on four CPU threads, so anything with a user in front of it needs a
    progress channel rather than a return value.
    """
    import time

    import pyro
    from pyro.infer import SVI, Trace_ELBO
    from pyro.optim import ClippedAdam

    from photosvi.benchmark import matched_filter_score
    from photosvi.experiments.arms import PointsSetup
    from photosvi.experiments.marks import estimate_mark_distribution
    from photosvi.experiments.sweep import mf_anchor
    from photosvi.inference.points import EstimandPlateau, resolve_device
    from photosvi.models.points import (
        AdditiveEmission,
        PhasicEventProcess,
        SingleTraceModel,
        WindowedCategoricalEventGuide,
        build_kernel,
        estimate_ar_coeffs,
        estimate_log_noise_scale,
        fit_tonic_baseline,
    )

    st = settings or FitSettings()
    r = st.resolved(fs=session.fs)
    torch.set_num_threads(max(1, r["threads"]))
    dt = 1.0 / session.fs
    y = torch.as_tensor(session.trace, dtype=torch.float32).reshape(1, -1)
    inj = int(session.inj_t)

    kernel = build_kernel(dict(r["kernel"]), r["kernel_length"], dt)
    mf = matched_filter_score(y, kernel, inj, dt=dt)
    b0a, _ = mf_anchor(mf, inj, dt, thresh=r["mf_thresh"], refractory=r["refractory"])

    # Read off the recording, as the paper reads them: the AR coefficients by Yule-Walker
    # on the pre-injection trace, sigma_y from the successive differences corrected for
    # that correlation (the white-noise estimate is 22 times too small on dLight at 48 Hz),
    # and the centre of the mark prior from the pre-injection peak prominences.
    phi = r["ar_coeffs"] if r["ar_coeffs"] is not None else estimate_ar_coeffs(y, inj)
    sigma_y = r["sigma_y"]
    if sigma_y is None:
        sigma_y = math.exp(estimate_log_noise_scale(y, inj, ar_coeffs=phi or None))
    mu_a, sigma_a = r["mu_a"], r["sigma_a"]
    if r["mark_noise_units"] is not None:
        from photosvi.experiments.marks import noise_unit_marks
        mu_a, sigma_a = noise_unit_marks(sigma_y, *r["mark_noise_units"])
    elif mu_a is None or sigma_a is None:
        m_hat, s_hat = estimate_mark_distribution([session.trace[:inj]], session.fs)
        mu_a = m_hat if mu_a is None else mu_a
        sigma_a = s_hat if sigma_a is None else sigma_a

    setup = PointsSetup(
        dt=dt, kernel_length=r["kernel_length"], kernel_spec=dict(r["kernel"]),
        mu_a=mu_a, sigma_a=sigma_a, sigma_y=sigma_y,
        beta0_prior_loc=b0a, beta0_prior_scale=r["beta0_prior_scale"],
        beta_inj_prior_loc=r["beta_inj_prior_loc"],
        beta_inj_prior_scale=r["beta_inj_prior_scale"],
        tau=r["tau"], warm=dict(r["warm"]), window=r["window"],
        beta_prior=r["beta_prior"], beta_guide=r["beta_guide"],
        mark_gate_floor=r["mark_gate_floor"],
    )

    tonic = fit_tonic_baseline(y, inj, dt=dt)
    # The paper's final model refines the tonic jointly with the rest (as the benchmarks do);
    # earlier versions of this function held it at its least-squares pre-fit.
    if r["architecture"] != "paper_final":
        for prm in tonic.parameters():
            prm.requires_grad_(False)
    emission = AdditiveEmission(sigma_y=setup.sigma_y, ar_coeffs=phi or None)
    emission.log_sigma_y.requires_grad_(False)

    model = SingleTraceModel(
        PhasicEventProcess(kernel, beta0=b0a, beta_inj=0.0, mu_a=setup.mu_a,
                           sigma_a=setup.sigma_a, dt=dt, history=None),
        tonic, emission, tau=setup.tau,
        event_guide=WindowedCategoricalEventGuide(
            torch.as_tensor(mf, dtype=torch.float32), window=setup.window,
            # thresh and gain only: `hi`/`floor` belong to the warm-start guide,
            # not this one. Matching benchmark_guppy.py exactly is the point.
            thresh=setup.warm["thresh"], gain=setup.warm["gain"]),
        analytic_s_kl=True, mark_kl="gated", couple_events=False,
        mark_gate_floor=setup.mark_gate_floor,
        **setup.beta_prior_kwargs(),
    )
    # The amplitude-rate trade-off: the likelihood pins rate x amplitude^2 far better than
    # either, so the mark distribution is anchored on the peaks with a stated width.
    if r["mark_noise_units"] is not None:
        from photosvi.experiments.marks import fix_marks_at
        fix_marks_at(model.phasic, mu_a, sigma_a)
    else:
        model.phasic.set_mark_prior(mu_a, sigma_a, mu_sd=r["mark_prior_sd"],
                                    log_sigma_sd=r["mark_prior_sd"])
    model.train(False)
    device = resolve_device(r["device"], batch=1)
    model, y = model.to(device), y.to(device)
    # Bins outside the session's keep-mask do not enter the likelihood (the injection's
    # handling artefact, typically). Session has carried a mask since 2026-10-01 and the
    # GUI sets one, but until 2026-10-16 it never reached the model.
    obs_mask = (None if session.mask is None
                else torch.as_tensor(session.mask, dtype=torch.bool, device=device).reshape(1, -1))

    pyro.clear_param_store()
    pyro.set_rng_seed(r["seed"])
    svi = SVI(model.model, model.guide, ClippedAdam({"lr": r["lr"]}),
              Trace_ELBO(max_plate_nesting=2))
    plateau = EstimandPlateau(tol=r["stop_tol"], window=r["stop_window"],
                              min_steps=r["steps"])
    t0, stopped_at = time.time(), None
    for step in range(1, r["max_steps"] + 1):
        loss = svi.step(y, inj, obs_mask=obs_mask)
        if on_progress is not None and (step % probe_every == 0 or step == 1):
            bp = model.beta_posterior()
            on_progress(dict(step=step, total=r["max_steps"], loss=float(loss),
                             beta_inj=bp["beta_inj"][0],
                             rate_ratio=math.exp(bp["beta_inj"][0]),
                             min_steps=r["steps"], device=str(device),
                             elapsed=time.time() - t0))
        if step % r["stop_probe"] == 0 and plateau.update(
                step, model.beta_posterior()["beta_inj"][0]):
            stopped_at = step
            break
    seconds = time.time() - t0

    bp = model.beta_posterior()
    with torch.no_grad():
        prob = model.event_posterior(y, inj).reshape(-1).cpu().numpy()
        base = tonic.baseline(session.n_samples, inj).reshape(-1).cpu().numpy()
        b_mean, b_cov = None, None
        if r["beta_guide"] == "fullrank" and r["beta_prior"] != "uniform":
            L = pyro.param("q_beta_tril").detach().cpu()
            b_mean = tuple(float(v) for v in pyro.param("q_beta_loc").detach().cpu())
            b_cov = tuple(tuple(float(v) for v in row) for row in (L @ L.T))
        mu_fit = float(model.phasic.mu_a.detach().cpu())
        sigma_fit = float(model.phasic.sigma_a.detach().cpu())
    return Result(session=session, settings=st, beta0=tuple(bp["beta0"]),
                  beta_inj=tuple(bp["beta_inj"]), event_prob=prob, tonic=base,
                  stopped_at=stopped_at or r["max_steps"], seconds=seconds,
                  device=str(device), beta_mean=b_mean, beta_cov=b_cov,
                  mu_a=mu_fit, sigma_a=sigma_fit, sigma_y=float(sigma_y),
                  ar_coeffs=tuple(phi), kernel=kernel.detach().cpu().numpy().reshape(-1))

photosvi.api.fit_study

fit_study(study, settings=None, **kw)

Fit each session independently.

Deliberately NOT the hierarchical model. Fitting a cohort jointly is a different estimand -- a population contrast rather than a per-session effect -- and giving it the same name here would let a caller believe they had one when they had the other. The joint fit is fit_cohort, with its own return type.

Source code in src/photosvi/api.py
881
882
883
884
885
886
887
888
889
890
def fit_study(study: Study, settings: FitSettings | None = None,
              **kw) -> Sequence[Result]:
    """Fit each session independently.

    Deliberately NOT the hierarchical model. Fitting a cohort jointly is a different
    estimand -- a population contrast rather than a per-session effect -- and giving
    it the same name here would let a caller believe they had one when they had the
    other. The joint fit is `fit_cohort`, with its own return type.
    """
    return [fit_session(s, settings, **kw) for s in study.sessions]

photosvi.api.CohortSettings dataclass

CohortSettings(min_steps=50000, max_steps=100000, probe_every=1000, device='auto', seed=0, pre_s=600.0, levels=None, ar_coeffs=None, kernel=None, kernel_fs=None, mark_gate_floor=None, config=COHORT_CONFIG)

What a caller may change in a cohort fit. None means the shipped value.

The defaults are the paper's real-cohort fit: at least 50,000 and at most 100,000 steps, the contrast probed every 1,000 steps and the fit stopped once it no longer drifts, a window of 10 minutes before the injection, the levels of DEFAULT_LEVELS that the design identifies, and the kernel of the single-trace model.

photosvi.api.fit_cohort

fit_cohort(study, settings=None, *, reference=None, condition_keys=('condition', 'drug'), animal_keys=('animal',), on_progress=None)

Fit a cohort jointly with the hierarchical model.

study is a Study, or a list of Session, one per recording; each session's metadata names its animal (animal) and its condition (condition, or drug). The contrasts are differences between conditions in the log rate of transients after the injection; reference is the condition the others are compared against (by default the first in alphabetical order), usually the vehicle.

All sessions must have the same sampling rate. Each is cut to the same window around its injection: settings.pre_s before it, and as much after it as every session has. Bins where Session.mask is False (the handling window) are left out of the likelihood.

on_progress is called at every probe with the step, the maximum number of steps and the current contrasts against the reference. The paper's cohort, 13 forty-minute recordings, takes about half an hour on a GPU.

Source code in src/photosvi/cohort_fit.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def fit_cohort(study, settings: CohortSettings | None = None, *,
               reference: str | None = None,
               condition_keys: Sequence[str] = ("condition", "drug"),
               animal_keys: Sequence[str] = ("animal",),
               on_progress: Callable[[dict[str, Any]], None] | None = None) -> CohortResult:
    """Fit a cohort jointly with the hierarchical model.

    `study` is a `Study`, or a list of `Session`, one per recording; each session's
    metadata names its animal (`animal`) and its condition (`condition`, or `drug`). The
    contrasts are differences between conditions in the log rate of transients after the
    injection; `reference` is the condition the others are compared against (by default
    the first in alphabetical order), usually the vehicle.

    All sessions must have the same sampling rate. Each is cut to the same window around
    its injection: `settings.pre_s` before it, and as much after it as every session has.
    Bins where `Session.mask` is False (the handling window) are left out of the
    likelihood.

    `on_progress` is called at every probe with the step, the maximum number of steps and
    the current contrasts against the reference. The paper's cohort, 13 forty-minute
    recordings, takes about half an hour on a GPU.
    """
    import time

    import pyro
    from pyro.infer import SVI, Trace_ELBO
    from pyro.optim import ClippedAdam

    from photosvi.experiments.cohort import build_cohort_model
    from photosvi.inference.points import EstimandPlateau, prepare, resolve_device
    from photosvi.models.points.hierarchical import HierarchicalModel

    st = settings or CohortSettings()
    sessions = list(getattr(study, "sessions", study))
    c = prepare_cohort(sessions, st, reference=reference, condition_keys=condition_keys,
                       animal_keys=animal_keys)
    cfg, f = c["cfg"], c["cfg"]["fit"]
    conditions, ref = c["conditions"], c["reference"]
    D = len(conditions)

    levels = st.levels
    if levels is None:
        A = torch.as_tensor(c["coh"]["animal"])
        d = torch.as_tensor(c["coh"]["drug"])
        cell, n_cells = HierarchicalModel._cell_index(A, d)
        detected = HierarchicalModel._detect_levels(A, d, cell, n_cells, len(c["animals"]))
        levels = tuple(x for x in DEFAULT_LEVELS if x in detected)

    t0 = time.time()
    model, Yb, _ = build_cohort_model(cfg, c["spec"], c["coh"], levels=levels)
    device = resolve_device(st.device, batch=len(sessions))
    model, Yb = prepare(model, Yb, device)
    mask = c["mask"].to(Yb.device)

    pyro.clear_param_store()
    pyro.set_rng_seed(st.seed)
    svi = SVI(model.model, model.guide, ClippedAdam({"lr": f["lr"]}),
              Trace_ELBO(max_plate_nesting=2))
    plateau = EstimandPlateau(tol=f["stop_tol"], window=f["stop_window"],
                              min_steps=min(st.min_steps, st.max_steps // 2))
    pairs = [(a, b) for a in range(D) for b in range(D) if a != b]
    traj: list[dict[str, Any]] = []
    params = pyro.get_param_store()._params
    skipped = 0
    step = 0
    for step in range(1, st.max_steps + 1):
        snapshot = {n: v.detach().clone() for n, v in params.items()}
        loss = svi.step(Yb, obs_mask=mask)
        # A non-finite gradient lands in a parameter silently and surfaces a step later.
        # Roll back and restart the poisoned optimiser moments; give up if it recurs.
        if not math.isfinite(loss) or any(not torch.isfinite(v).all()
                                          for v in params.values()):
            with torch.no_grad():
                for n, v in params.items():
                    if n in snapshot:
                        v.copy_(snapshot[n])
            for prm, o in list(svi.optim.optim_objs.items()):
                if any(torch.is_tensor(x) and not torch.isfinite(x).all()
                       for x in o.state.get(prm, {}).values()):
                    del svi.optim.optim_objs[prm]
            skipped += 1
            if skipped > st.max_steps // 10:
                raise RuntimeError(f"{skipped} non-finite steps out of {step}; the fit "
                                   "does not recover")
        if step % st.probe_every == 0:
            row = {"step": step}
            for a, b in pairs:
                row[f"{a}-{b}"] = list(model.drug_contrast(a, b))
            traj.append(row)
            vs_ref = [row[f"{a}-0"][0] for a in range(1, D)]
            if on_progress is not None:
                on_progress(dict(step=step, total=st.max_steps,
                                 contrasts={conditions[a]: row[f"{a}-0"]
                                            for a in range(1, D)}))
            if plateau.update(step, vs_ref if D > 2 else vs_ref[0]):
                break

    # The estimate is the mean over the plateau window (the iterate orbits its answer),
    # or the last probe if the fit never settled; the width is the mean over the same
    # number of probes, since it oscillates too. This is how the paper reports it.
    n = f["stop_window"]
    contrasts = {}
    for a, b in pairs:
        rows = [r[f"{a}-{b}"] for r in traj[-n:]] or [list(model.drug_contrast(a, b))]
        est = (float(np.mean([r[0] for r in rows])) if plateau.converged_at is not None
               else float(rows[-1][0]))
        contrasts[(conditions[a], conditions[b])] = (est, float(np.mean([r[1] for r in rows])))

    # Whether the width was still moving when the fit stopped, against its own noise.
    sds = [r["1-0"][1] for r in traj[-max(n, 10):]]
    sd_settled = False
    if len(sds) >= max(n, 10):
        drift = float(np.polyfit(range(len(sds)), sds, 1)[0]) * len(sds)
        sd_settled = abs(drift) <= max(float(np.std(np.diff(sds))), 0.02 * float(np.mean(sds)))

    tonic, tonic_contrasts = {}, {}
    if model.tonic_hierarchy:
        tonic = {conditions[d]: v for d, v in model.tonic_posterior().items()}
        tonic_contrasts = {(conditions[a], conditions[b]): model.tonic_contrast(a, b, "alpha")
                           for a, b in pairs}
    arrays = _arrays(model, Yb, mask, D)
    return CohortResult(
        conditions=conditions, reference=ref, animals=c["animals"],
        sessions=c["session_info"], settings=st,
        design={k: (list(v) if isinstance(v, tuple) else v)
                for k, v in model.design_summary().items()},
        contrasts_=contrasts, tonic=tonic, tonic_contrasts_=tonic_contrasts,
        variance_components=model.variance_components(),
        sigma_y=c["sigma_y"],
        sigma_y_sessions=[float(x) for x in (getattr(model, "sigma_y_sessions", []) or [])],
        ar_coeffs=c["ar_coeffs"], kernel=c["kernel"], kernel_length=c["kernel_length"],
        fs=c["fs"], inj_t=[c["pre"]] * len(sessions), steps=step,
        converged_at=plateau.converged_at, sd_settled=bool(sd_settled),
        skipped_steps=skipped, seconds=time.time() - t0, device=str(device),
        trajectory=[{"step": r["step"], **{f"{conditions[a]} - {conditions[b]}": r[f"{a}-{b}"]
                                           for a, b in pairs}} for r in traj],
        **arrays)

Results

photosvi.api.Result dataclass

Result(session, settings, beta0, beta_inj, event_prob, tonic, stopped_at, seconds, device='cpu', beta_mean=None, beta_cov=None, mu_a=None, sigma_a=None, sigma_y=None, ar_coeffs=(), kernel=None)

What one fitted session yields, and the only thing callers should read.

rate_ratio is the estimand: the factor by which the drug changed the transient rate, with a credible interval. event_prob is the per-bin posterior, from which events() picks peaks -- the two are different questions and the interval caveat applies only to the first (see MODEL_CARD.md).

simulate

simulate(n=1, seed=0)

Recordings the fitted model generates: a posterior predictive check.

Each draw samples (beta0, beta_inj) from their joint posterior, events from the intensity, marks from the fitted distribution, convolves them with the kernel and adds the fitted tonic and autoregressive noise. It needs no ground truth, so it applies to experimental recordings: a draw that looks unlike the recording says the fit has not captured it. Returns one dict per draw with the trace y and the number of events n_events.

Source code in src/photosvi/api.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
def simulate(self, n: int = 1, seed: int = 0) -> list[dict[str, Any]]:
    """Recordings the fitted model generates: a posterior predictive check.

    Each draw samples (beta0, beta_inj) from their joint posterior, events from the
    intensity, marks from the fitted distribution, convolves them with the kernel and
    adds the fitted tonic and autoregressive noise. It needs no ground truth, so it
    applies to experimental recordings: a draw that looks unlike the recording says the
    fit has not captured it. Returns one dict per draw with the trace `y` and the
    number of events `n_events`.
    """
    if self.kernel is None or self.mu_a is None or self.sigma_y is None:
        raise ValueError("this result does not carry the fitted model; refit it")
    from photosvi.models.points import AdditiveEmission
    rng = np.random.default_rng(seed)
    T, inj, dt = self.session.n_samples, self.session.inj_t, 1.0 / self.session.fs
    mean = np.asarray(self.beta_mean if self.beta_mean is not None
                      else (self.beta0[0], self.beta_inj[0]), float)
    cov = (np.asarray(self.beta_cov, float) if self.beta_cov is not None
           else np.diag([self.beta0[1] ** 2, self.beta_inj[1] ** 2]))
    post = np.arange(T) >= inj
    em = AdditiveEmission(sigma_y=self.sigma_y, ar_coeffs=list(self.ar_coeffs) or None)
    gen = torch.Generator().manual_seed(int(seed))
    out = []
    for _ in range(n):
        b0, binj = rng.multivariate_normal(mean, cov)
        p = -np.expm1(-np.exp(b0 + binj * post) * dt)
        s = rng.random(T) < p
        a = np.exp(self.mu_a + self.sigma_a * rng.standard_normal(T))
        c = np.convolve(s * a, self.kernel)[:T]
        with torch.no_grad():
            y = em.sample(torch.as_tensor(self.tonic + c, dtype=torch.float32)
                          .reshape(1, -1), generator=gen)["y"]
        out.append(dict(y=y.reshape(-1).numpy(), n_events=int(s.sum())))
    return out

events

events(threshold=None)

Peak-picked events above threshold, after non-maximum suppression.

Source code in src/photosvi/api.py
415
416
417
418
419
420
421
def events(self, threshold: float | None = None) -> dict[str, np.ndarray]:
    """Peak-picked events above `threshold`, after non-maximum suppression."""
    r = self.settings.resolved(fs=self.session.fs)
    return events_from_posterior(
        self.event_prob, fs=self.session.fs,
        threshold=r["event_threshold"] if threshold is None else threshold,
        refractory=r["refractory"])

rate_per_min

rate_per_min(threshold=None)

Observed event rate before and after the injection, in events per minute.

A descriptive counterpart to rate_ratio: this counts detections, while rate_ratio is a parameter of the model. They answer the same question by different routes and are not obliged to agree exactly.

Source code in src/photosvi/api.py
423
424
425
426
427
428
429
430
431
432
433
434
435
436
def rate_per_min(self, threshold: float | None = None) -> dict[str, float]:
    """Observed event rate before and after the injection, in events per minute.

    A descriptive counterpart to `rate_ratio`: this counts detections, while
    `rate_ratio` is a parameter of the model. They answer the same question by
    different routes and are not obliged to agree exactly.
    """
    ev = self.events(threshold)["bins"]
    inj, n, fs = self.session.inj_t, self.session.n_samples, self.session.fs
    pre_min, post_min = inj / fs / 60, (n - inj) / fs / 60
    return dict(
        pre=float((ev < inj).sum()) / pre_min if pre_min > 0 else float("nan"),
        post=float((ev >= inj).sum()) / post_min if post_min > 0 else float("nan"),
    )

save

save(out)

Write a run directory: result.json, events.csv, and the fitted curves.

Files rather than a database, and the same layout the command line writes, so a GUI run and a scripted run are interchangeable downstream.

Source code in src/photosvi/api.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
def save(self, out: Path | str) -> Path:
    """Write a run directory: result.json, events.csv, and the fitted curves.

    Files rather than a database, and the same layout the command line writes, so
    a GUI run and a scripted run are interchangeable downstream.
    """
    out = Path(out)
    out.mkdir(parents=True, exist_ok=True)
    (out / "result.json").write_text(json.dumps(self.to_dict(), indent=2))
    ev = self.events()
    lines = ["bin,time_s,probability"]
    lines += [f"{b},{t:.4f},{p:.6f}"
              for b, t, p in zip(ev["bins"], ev["times_s"], ev["prob"], strict=True)]
    (out / "events.csv").write_text("\n".join(lines) + "\n")
    np.savez_compressed(out / "curves.npz", trace=self.session.trace,
                        event_prob=self.event_prob, tonic=self.tonic)
    return out

photosvi.api.CohortResult dataclass

CohortResult(conditions, reference, animals, sessions, settings, design, contrasts_, tonic, tonic_contrasts_, variance_components, sigma_y, sigma_y_sessions, ar_coeffs, kernel, kernel_length, fs, inj_t, steps, converged_at, sd_settled, skipped_steps, seconds, device, trajectory=list(), y=None, event_prob=None, tonic_session=None, tonic_condition=None, mask=None)

What a cohort fit yields.

contrast(a, b) is the estimand: the difference between conditions a and b in the log rate of transients after the injection, with a 90% interval that carries the between-animal variability. tonic holds each condition's pooled tonic response.

contrast

contrast(a, b=None)

Condition a minus b (default: the reference), with its 90% interval.

estimate, lo and hi are on the log-rate axis; ratio, ratio_lo and ratio_hi are the same as the factor by which the transient rate after the injection differs between the two conditions.

Source code in src/photosvi/cohort_fit.py
115
116
117
118
119
120
121
122
123
124
def contrast(self, a: str, b: str | None = None) -> dict[str, float]:
    """Condition `a` minus `b` (default: the reference), with its 90% interval.

    `estimate`, `lo` and `hi` are on the log-rate axis; `ratio`, `ratio_lo` and
    `ratio_hi` are the same as the factor by which the transient rate after the
    injection differs between the two conditions.
    """
    b = self.reference if b is None else b
    est, sd = self.contrasts_[(a, b)]
    return _interval(est, sd)

tonic_ratio

tonic_ratio(a, b=None)

Ratio of the tonic peak heights, a over b (default: the reference), 90%.

Source code in src/photosvi/cohort_fit.py
126
127
128
129
130
131
132
def tonic_ratio(self, a: str, b: str | None = None) -> dict[str, float]:
    """Ratio of the tonic peak heights, `a` over `b` (default: the reference), 90%."""
    b = self.reference if b is None else b
    est, sd = self.tonic_contrasts_[(a, b)]
    out = _interval(est, sd)
    return dict(ratio=out["ratio"], lo=out["ratio_lo"], hi=out["ratio_hi"],
                level=out["level"])

save

save(out)

Write a run directory: result.json and curves.npz (the [S, T] arrays).

Source code in src/photosvi/cohort_fit.py
153
154
155
156
157
158
159
160
161
162
163
164
def save(self, out: Path | str) -> Path:
    """Write a run directory: result.json and curves.npz (the [S, T] arrays)."""
    out = Path(out)
    out.mkdir(parents=True, exist_ok=True)
    (out / "result.json").write_text(json.dumps(self.to_dict(), indent=1))
    arrays = {k: getattr(self, k) for k in
              ("y", "event_prob", "tonic_session", "tonic_condition", "mask")
              if getattr(self, k) is not None}
    np.savez_compressed(out / "curves.npz", conditions=np.array(self.conditions),
                        session_names=np.array([s["name"] for s in self.sessions]),
                        **arrays)
    return out

photosvi.api.events_from_posterior

events_from_posterior(prob, *, fs, threshold, refractory)

Turn a per-bin event posterior into a list of events.

Separate from Result so that re-thresholding a stored run uses the same rule the fit reported, rather than a second implementation that agrees today.

The posterior is per-bin, so one transient contributes a cluster of adjacent high-probability bins; suppression is what turns that cluster into one event rather than several. The refractory width is a reporting choice, not a biological claim, and it should be stated wherever counts are.

Re-thresholding is cheap and correct: nothing about the fit depends on the threshold. It is a readout of the posterior, applied afterwards. The rate ratio, by contrast, is a parameter of the model and does not move when this does -- which is the whole point of estimating it rather than counting detections.

Source code in src/photosvi/api.py
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
def events_from_posterior(prob, *, fs: float, threshold: float,
                          refractory: int) -> dict[str, np.ndarray]:
    """Turn a per-bin event posterior into a list of events.

    Separate from `Result` so that re-thresholding a stored run uses the same rule
    the fit reported, rather than a second implementation that agrees today.

    The posterior is per-bin, so one transient contributes a cluster of adjacent
    high-probability bins; suppression is what turns that cluster into one event
    rather than several. The refractory width is a reporting choice, not a
    biological claim, and it should be stated wherever counts are.

    Re-thresholding is cheap and correct: nothing about the fit depends on the
    threshold. It is a readout of the posterior, applied afterwards. The rate ratio,
    by contrast, is a parameter of the model and does not move when this does --
    which is the whole point of estimating it rather than counting detections.
    """
    from photosvi.benchmark.detectors import nms, peaks_from_score

    prob = np.asarray(prob, dtype=float)
    t, p = peaks_from_score(prob)
    keep = p >= threshold
    t, p = nms(t[keep], p[keep], refractory=refractory)
    return dict(bins=t, times_s=t / fs, prob=p)

Before a fit

photosvi.api.calibrate_kernel

calibrate_kernel(sessions, *, sensor='dLight1.3b', families=('biphasic', 'bigamma', 'biexp'), folds=5, min_transients=20, maxiter=600, seed=0, **extract_kw)

Fit candidate kernels to a set of recordings and suggest one.

sessions is an api.Session, a list of them, or an api.Study; all must share a sampling rate, since a kernel is a shape in bins once it is built. sensor chooses the starting values (see SENSORS) and labels the result; every family is also started from the other sensors' values. extract_kw go to extract_isolated_transients.

Held-out error is the RMS residual, in units of the transient's peak, of a candidate against the average of the transients it was not fitted to, over folds folds. The two shipped kernels are scored on the same folds without fitting.

Source code in src/photosvi/kernel_calibration.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def calibrate_kernel(
    sessions: Any,
    *,
    sensor: str = "dLight1.3b",
    families: Sequence[str] = ("biphasic", "bigamma", "biexp"),
    folds: int = 5,
    min_transients: int = 20,
    maxiter: int = 600,
    seed: int = 0,
    **extract_kw: Any,
) -> KernelCalibration:
    """Fit candidate kernels to a set of recordings and suggest one.

    `sessions` is an `api.Session`, a list of them, or an `api.Study`; all must share a
    sampling rate, since a kernel is a shape in bins once it is built. `sensor` chooses the
    starting values (see `SENSORS`) and labels the result; every family is also started
    from the other sensors' values. `extract_kw` go to `extract_isolated_transients`.

    Held-out error is the RMS residual, in units of the transient's peak, of a candidate
    against the average of the transients it was not fitted to, over `folds` folds. The
    two shipped kernels are scored on the same folds without fitting.
    """
    sess = list(getattr(sessions, "sessions", None) or
                (sessions if isinstance(sessions, (list, tuple)) else [sessions]))
    if not sess:
        raise ValueError("no recordings to calibrate on")
    rates = {float(s.fs) for s in sess}
    if len(rates) > 1:
        raise ValueError(f"recordings at different sampling rates {sorted(rates)}; "
                         "a kernel is calibrated for one rate")
    fs = rates.pop()
    if sensor not in SENSORS:
        raise ValueError(f"unknown sensor {sensor!r}; known: {sorted(SENSORS)}")
    unknown = set(families) - set(FAMILIES)
    if unknown:
        raise ValueError(f"unknown families {sorted(unknown)}; known: {sorted(FAMILIES)}")

    tr = extract_isolated_transients([s.trace for s in sess], fs,
                                     [s.mask for s in sess], **extract_kw)
    ba = _bandpass(fs)
    pre, post = tr.pre, tr.post
    notes: list[str] = []

    dspec, dlen = _default_kernel(fs)
    fixed = [("default", "shipped default: dLight1.3b, fitted to the paper's recordings (K10)",
              dspec, dlen)]

    enough = tr.n >= min_transients
    if not enough:
        notes.append(
            f"only {tr.n} isolated transients (fewer than {min_transients}): too few to "
            "fit a shape, so the shipped kernel is suggested. Add recordings, or loosen "
            "the isolation if the transients are frequent.")
        warnings.warn(notes[-1], stacklevel=2)
    elif tr.n < 3 * min_transients:
        notes.append(f"{tr.n} isolated transients: enough to fit, few enough that the "
                     "held-out errors are noisy; prefer a shipped kernel unless a fitted "
                     "one is clearly better.")

    k = max(2, min(folds, tr.n // max(1, min_transients // 4))) if enough else 0
    rng = np.random.default_rng(seed)
    order = rng.permutation(tr.n)
    split = np.array_split(order, k) if k else []
    target = tr.mean

    def heldout(g_of_train) -> float:
        errs = []
        for test in split:
            train = np.setdiff1d(order, test)
            g = g_of_train(tr.snippets[train].mean(axis=0))
            errs.append(_rms(tr.snippets[test].mean(axis=0), g))
        return float(np.mean(errs)) if errs else float("nan")

    cands: list[KernelCandidate] = []
    for key, label, spec, n in fixed:
        h = build_kernel(spec, n, 1.0 / fs).detach().cpu().numpy().astype(float)
        g = _template(h, fs, pre, post, ba)
        cands.append(KernelCandidate(
            key=key, label=label, family=spec["family"], spec=dict(spec), kernel_length=n,
            fitted=False, heldout_rms=heldout(lambda _m, g=g: g) if enough else float("nan"),
            train_rms=_rms(target, g) if tr.n else float("nan"),
            shape=_shape(h, fs), kernel=h, template=g))

    if enough:
        sensor_first = [sensor] + [s for s in SENSORS if s != sensor]
        for fam in families:
            starts = [_start(fam, **SENSORS[s]) for s in sensor_first]
            if fam == "bigamma":
                starts.append(dict(K10))
            spec, train = _fit_family(fam, target, starts, fs, pre, post, ba,
                                      maxiter=maxiter)
            # Refitting per fold from the full-data optimum: the start is shared, the
            # fit is not, so each fold's error is of a kernel that never saw its test set.
            def g_of(m, fam=fam, spec=spec):
                s, _ = _fit_family(fam, m, [spec], fs, pre, post, ba,
                                   maxiter=maxiter // 3)
                return _template(_kernel(s, _length(s, fs, final=False), fs),
                                 fs, pre, post, ba)
            # Rounded before the kernel is built, so the spec written to a config builds
            # exactly the kernel that was scored.
            spec = {kk: (round(v, 4) if isinstance(v, float) else v)
                    for kk, v in spec.items()}
            n = _length(spec, fs, final=True)
            try:
                # Through build_kernel, with its checks, because that is how the fit
                # will build it; a kernel the fit would refuse is not a candidate.
                h = build_kernel(spec, n, 1.0 / fs).detach().cpu().numpy().astype(float)
            except ValueError as exc:
                notes.append(f"{fam}: the fitted kernel is not usable ({exc}); dropped.")
                continue
            cands.append(KernelCandidate(
                key=f"fit-{fam}", label=f"{fam}, fitted to these recordings",
                family=fam, spec=spec, kernel_length=n, fitted=True,
                heldout_rms=heldout(g_of), train_rms=train, shape=_shape(h, fs),
                kernel=h, template=_template(h, fs, pre, post, ba)))
        best = min(cands, key=lambda c: c.heldout_rms)
        recommended = best.key
    else:
        recommended = "default"

    return KernelCalibration(transients=tr, candidates=cands, recommended=recommended,
                             sensor=sensor, folds=k, warnings=notes)

photosvi.api.KernelCalibration dataclass

KernelCalibration(transients, candidates, recommended, sensor, folds, warnings=list())

Every candidate kernel, scored on the same held-out transients, and a suggestion.

settings

settings(key=None)

FitSettings fields for a candidate, the suggested one by default.

Source code in src/photosvi/kernel_calibration.py
434
435
436
def settings(self, key: str | None = None) -> dict[str, Any]:
    """`FitSettings` fields for a candidate, the suggested one by default."""
    return self.candidate(key).settings()

config

config(key=None)

The kernel: block of a config file, as configs/toy.yaml writes it.

Source code in src/photosvi/kernel_calibration.py
438
439
440
441
def config(self, key: str | None = None) -> dict[str, Any]:
    """The `kernel:` block of a config file, as `configs/toy.yaml` writes it."""
    c = self.candidate(key)
    return dict(kernel=dict(length=int(c.kernel_length), fit=dict(c.spec)))

to_dict

to_dict(max_points=None)

Everything the interface draws, as plain JSON types.

Source code in src/photosvi/kernel_calibration.py
443
444
445
446
447
448
449
450
451
def to_dict(self, max_points: int | None = None) -> dict[str, Any]:
    """Everything the interface draws, as plain JSON types."""
    tr = self.transients
    return dict(
        sensor=self.sensor, recommended=self.recommended, folds=self.folds,
        warnings=list(self.warnings), fs=tr.fs, n_transients=tr.n,
        n_recordings=int(np.unique(tr.source).size) if tr.n else 0,
        t_s=tr.t_s.tolist(), mean=tr.mean.tolist(), sd=tr.sd.tolist(),
        candidates=[c.to_dict() for c in self.candidates])

plot

plot(path)

The average isolated transient with every candidate drawn over it.

Source code in src/photosvi/kernel_calibration.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def plot(self, path: Path | str) -> None:
    """The average isolated transient with every candidate drawn over it."""
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    tr = self.transients
    fig, (ax, bx) = plt.subplots(1, 2, figsize=(10, 3.8))
    ax.fill_between(tr.t_s, tr.mean - tr.sd, tr.mean + tr.sd, color="#d9d9d9", lw=0)
    ax.plot(tr.t_s, tr.mean, color="#2b2b2b", lw=1.8,
            label=f"isolated transients (n = {tr.n})")
    for c in self.candidates:
        a = float(c.template @ tr.mean / (c.template @ c.template)) if tr.n else 1.0
        lw = 2.2 if c.key == self.recommended else 1.1
        ax.plot(tr.t_s, a * c.template, lw=lw,
                label=f"{c.label}  held-out {c.heldout_rms:.3f}"
                      + ("  (suggested)" if c.key == self.recommended else ""))
        bx.plot(np.arange(c.kernel.size) / tr.fs, c.kernel, lw=lw)
    ax.set_xlabel("time from peak (s)")
    ax.set_ylabel("band-passed signal (peak = 1)")
    ax.legend(fontsize=7, frameon=False)
    bx.axhline(0, color="#8a8a8a", lw=0.8)
    bx.set_xlabel("time (s)")
    bx.set_ylabel("kernel $h$")
    bx.set_xlim(0, min(MAX_KERNEL_S, max(c.kernel.size for c in self.candidates) / tr.fs))
    fig.tight_layout()
    fig.savefig(path, facecolor="white")
    plt.close(fig)

photosvi.api.spectrum

spectrum(session, *, n_per_segment=4096, band=(1.0, 10.0))

Power spectral density of a recording, and whether the transient band survives.

The single most likely silent failure on real data is a trace that has already been low-pass filtered upstream. The model does not error on one: it explains a smooth curve with a point process and returns a rate ratio, and the only symptom is that few events are found -- which looks like a biological result.

The spectrum makes it visible before anything is fitted. The two components live in separate places: the pharmacokinetic carrier below 0.01 Hz, and the transients in a shoulder from about 1 Hz up. band_ratio compares the power inside that shoulder to the power just below it; a trace whose transients have been filtered away has almost none, and one that never had transients looks the same -- so this diagnoses the trace, not the biology, and says so.

Source code in src/photosvi/api.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
def spectrum(session: Session, *, n_per_segment: int = 4096,
             band: tuple[float, float] = (1.0, 10.0)) -> dict[str, Any]:
    """Power spectral density of a recording, and whether the transient band survives.

    The single most likely silent failure on real data is a trace that has already
    been low-pass filtered upstream. The model does not error on one: it explains a
    smooth curve with a point process and returns a rate ratio, and the only symptom
    is that few events are found -- which looks like a biological result.

    The spectrum makes it visible before anything is fitted. The two components live
    in separate places: the pharmacokinetic carrier below 0.01 Hz, and the transients
    in a shoulder from about 1 Hz up. `band_ratio` compares the power inside that
    shoulder to the power just below it; a trace whose transients have been filtered
    away has almost none, and one that never had transients looks the same -- so this
    diagnoses the trace, not the biology, and says so.
    """
    from scipy import signal as _sig

    y = session.trace.astype(np.float64)
    nps = int(min(n_per_segment, y.size))
    freq, psd = _sig.welch(y, fs=session.fs, nperseg=nps)
    lo, hi = band
    inband = (freq >= lo) & (freq <= hi)
    below = (freq >= lo / 10) & (freq < lo)
    ratio = (float(psd[inband].mean() / psd[below].mean())
             if inband.any() and below.any() and psd[below].mean() > 0 else float("nan"))
    # A hard floor rather than a soft hint: the point of the check is to stop a fit
    # that would return a number from a trace with nothing in it to fit.
    suspect = ratio == ratio and ratio < 0.02
    return dict(
        freq=freq.tolist(), psd=psd.tolist(), band=[lo, hi], band_ratio=ratio,
        suspect_filtered=bool(suspect),
        message=(
            f"the {lo}-{hi} Hz band carries {ratio:.1%} of the power just below it; "
            "if this recording was low-pass filtered upstream the transients are "
            "gone and a fit will find almost none"
            if suspect else
            f"the {lo}-{hi} Hz band carries {ratio:.1%} of the power just below it"
        ),
    )

photosvi.api.config_path

config_path(name)

Path of a config shipped with the package, e.g. config_path("toy.yaml").

The configs live inside the package (photosvi/configs/), so they are there after a pip install as well as in a clone, where configs/ at the root links to them.

Source code in src/photosvi/api.py
198
199
200
201
202
203
204
205
206
207
208
def config_path(name: str) -> Path:
    """Path of a config shipped with the package, e.g. `config_path("toy.yaml")`.

    The configs live inside the package (`photosvi/configs/`), so they are there after a
    `pip install` as well as in a clone, where `configs/` at the root links to them.
    """
    from importlib.resources import files
    cand = Path(str(files("photosvi") / "configs" / name))
    if not cand.exists():
        raise FileNotFoundError(f"photosvi ships no config named {name!r}")
    return cand