Skip to content

Models

photosvi.models.points.SingleTraceModel

SingleTraceModel(phasic, tonic, emission, *, tau=0.5, beta0_prior_loc=None, beta0_prior_scale=1.0, beta_inj_prior_loc=None, beta_inj_prior_scale=1.0, sigma_y_prior_loc=None, sigma_y_prior_scale=0.1, beta_prior='normal', beta_low=-2.0, beta_high=2.0, beta_inj_low=None, beta_inj_high=None, event_guide=None, couple_events=False, analytic_s_kl=True, mark_kl='gated', mark_gate_floor=_MARK_GATE_FLOOR, mark_window=None, beta_guide='fullrank')

Bases: Module

Points-family Pyro program: relaxed-event SVI over the additive-mean joint.

Global parameters (marks mu_a/sigma_a, tonic psi, robustness nu) are MAP-optimized nn.Parameters registered via pyro.module("points", self). The phasic coefficients beta0 / beta_inj are always Bayesian -- under a Normal prior (default) or a Uniform prior on [beta_low, beta_high] (beta_prior="uniform"), each with a matching mean-field posterior in guide (Normal, or a sigmoid-affine-transformed Normal whose support is exactly the prior interval). The emission scale sigma_y is optionally Bayesian: passing sigma_y_prior_loc switches it from a MAP point estimate to a sampled latent under a narrow Normal prior on log sigma_y, anchored on the data's high-frequency noise floor so it can't inflate to absorb tonic misfit. Latent sample sites are therefore the globals beta0, beta_inj (and log_sigma_y when Bayesian) plus the per-bin events s (relaxed) and marks a; the guide covers exactly those.

Parameters:

Name Type Description Default
phasic PhasicEventProcess supplying the intensity GLM, mark params, fixed

kernel and convolve. Must have history_len == 0 for this slice.

required
tonic TonicBaseline supplying the deterministic x_hat(t).
required
emission AdditiveEmission supplying sigma_y (and nu for the robust variant).
required
tau Concrete relaxation temperature lambda.
0.5
beta0_prior_loc prior means for the Bayesian phasic

coefficients (Normal prior on the unconstrained log-rate axis). Default to the phasic block's own beta0 / beta_inj anchors -- pass a value from estimate_log_baseline_rate(y, inj_t) for a data-driven beta0.

None
beta_inj_prior_loc prior means for the Bayesian phasic

coefficients (Normal prior on the unconstrained log-rate axis). Default to the phasic block's own beta0 / beta_inj anchors -- pass a value from estimate_log_baseline_rate(y, inj_t) for a data-driven beta0.

None
beta0_prior_scale prior std-devs (weakly-informative;

~1 log-unit covers a wide event-rate range). Fixed, not data-driven. Only used when beta_prior="normal".

1.0
beta_inj_prior_scale prior std-devs (weakly-informative;

~1 log-unit covers a wide event-rate range). Fixed, not data-driven. Only used when beta_prior="normal".

1.0
beta_prior "normal" (default) or "uniform". Selects the prior family for

BOTH beta0 and beta_inj. "uniform" replaces the informative Normal with a flat prior on [beta_low, beta_high]; the guide switches to a transformed Normal supported on that interval so guide samples can never fall outside the prior's support.

'normal'
beta_low bounds of the Uniform prior on the log-rate axis.

Must bracket the plausible beta range -- values outside are assigned zero prior mass. Only used when beta_prior="uniform".

-2.0
beta_high bounds of the Uniform prior on the log-rate axis.

Must bracket the plausible beta range -- values outside are assigned zero prior mass. Only used when beta_prior="uniform".

-2.0
sigma_y_prior_loc prior mean for the Bayesian emission scale on the

log sigma_y axis. None (default) keeps the legacy MAP point estimate (emission.log_sigma_y); pass a value -- e.g. estimate_log_noise_scale(y, inj_t) -- to make sigma_y Bayesian with a data-driven anchor. Supplying it freezes emission.log_sigma_y.

None
sigma_y_prior_scale prior std-dev on the `log sigma_y` axis (default 0.1).

Narrow on purpose -- this is the anti-inflation knob: a tight prior pins sigma_y near the high-frequency anchor so it can't soak up slow baseline misfit. Only used when sigma_y_prior_loc is given.

0.1
event_guide the block supplying q(s)'s per-bin logits (`event_guides.py`).

None (default) installs FreeEventGuide -- one free variational logit per (sequence, bin). Pass MatchedFilterEventGuide(mf) for the amortized family, whose event ranking is pinned to the matched filter's. The choice changes only the variational family; model is untouched either way.

None
Source code in src/photosvi/models/points/points.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
def __init__(
    self,
    phasic: PhasicEventProcess,
    tonic: TonicBaseline,
    emission: AdditiveEmission,
    *,
    tau: float = 0.5,
    beta0_prior_loc: float | None = None,
    beta0_prior_scale: float = 1.0,
    beta_inj_prior_loc: float | None = None,
    beta_inj_prior_scale: float = 1.0,
    sigma_y_prior_loc: float | None = None,
    sigma_y_prior_scale: float = 0.1,
    beta_prior: str = "normal",
    beta_low: float = -2.0,
    beta_high: float = 2.0,
    beta_inj_low: float | None = None,
    beta_inj_high: float | None = None,
    event_guide: nn.Module | None = None,
    couple_events: bool = False,
    analytic_s_kl: bool = True,
    mark_kl: str = "gated",
    mark_gate_floor: float = _MARK_GATE_FLOOR,
    mark_window: int | None = None,
    # The 2x2 joint Gaussian over (beta0, beta_inj), NOT a mean-field pair.
    #
    # Default since 2026-09-14. The two coefficients trade off by construction --
    # a higher baseline with a smaller injection effect explains the same
    # post-injection rate -- and their posterior correlation is -0.90. A
    # factorised family has to call that zero, and reports 0.46x the exact width
    # against a NUTS reference where the block reports 1.03x.
    #
    # The old default was "meanfield", and it cost the study its whole two-stage
    # arm: `cohort_twostage.py` built this class without naming a guide and 519
    # per-session fits silently took the family we had already rejected. A
    # default that is wrong for every production use is not a neutral choice.
    #
    # It is also free. Measured on a 40-minute trace: 96,017 variational
    # parameters against 96,011, and no time difference outside the noise of a
    # loaded machine. "meanfield" stays reachable because S1 Text compares
    # against it and `linear_response.py` corrects it, not because there is a
    # case for choosing it -- detection reads q(s_t) and never touches these
    # coefficients, so it is identical either way.
    beta_guide: str = "fullrank",
):
    super().__init__()
    if phasic.history_len != 0:
        raise NotImplementedError(
            "SingleTraceModel slice requires history_len == 0 (no FIR self-excitation): "
            "relaxed events feeding back into the intensity is a deferred slice."
        )
    if tau <= 0:
        raise ValueError(f"relaxation temperature tau must be > 0 (got {tau})")
    if beta0_prior_scale <= 0 or beta_inj_prior_scale <= 0:
        raise ValueError("beta prior scales must be > 0")
    if sigma_y_prior_scale <= 0:
        raise ValueError("sigma_y_prior_scale must be > 0")
    if beta_prior not in ("normal", "uniform"):
        raise ValueError(f"beta_prior must be 'normal' or 'uniform' (got {beta_prior!r})")
    if beta_guide not in ("meanfield", "fullrank"):
        raise ValueError(
            f"beta_guide must be 'meanfield' or 'fullrank' (got {beta_guide!r})")
    if beta_low >= beta_high:
        raise ValueError(f"beta_low must be < beta_high (got [{beta_low}, {beta_high}])")
    bi_low = beta_low if beta_inj_low is None else beta_inj_low
    bi_high = beta_high if beta_inj_high is None else beta_inj_high
    if bi_low >= bi_high:
        raise ValueError(f"beta_inj_low must be < beta_inj_high (got [{bi_low}, {bi_high}])")
    self.phasic = phasic
    self.tonic = tonic
    self.emission = emission
    self.event_guide = FreeEventGuide() if event_guide is None else event_guide
    # When False (the default, and the shipped behaviour) the guide's event logits
    # are anchored on a *detached* prior intensity: the rate reaches q(s) only as a
    # constant init, so the event factor and the betas are estimated by separate
    # blocks. When True the anchor is rebuilt at the betas *sampled in the guide* and
    # left differentiable, so q(s) tracks the rate being estimated and the two chase
    # each other. See `guide()`.
    self.couple_events = bool(couple_events)
    if mark_kl not in ("sampled", "analytic", "gated"):
        raise ValueError(f"mark_kl must be 'sampled', 'analytic' or 'gated' (got {mark_kl!r})")
    self.analytic_s_kl = bool(analytic_s_kl)
    self.mark_kl = mark_kl
    if not 0.0 <= mark_gate_floor < 1.0:
        raise ValueError(
            f"mark_gate_floor must be in [0, 1), got {mark_gate_floor!r}")
    self.mark_gate_floor = float(mark_gate_floor)
    # Marks are tied within a window when the event guide is windowed: at most
    # one event per window means at most one mark, so a free mark per bin is
    # W-fold redundant. Picked up from the guide unless given explicitly.
    if mark_window is None:
        mark_window = getattr(self.event_guide, "window", None)
    self.mark_window = int(mark_window) if mark_window else None
    self.tau = float(tau)
    self.beta_prior = beta_prior
    # A mean-field q cannot represent the correlation between beta0 and beta_inj,
    # and those two trade off against each other by construction: raising the
    # baseline and lowering the injection effect explain the same post-injection
    # rate. Measured against NUTS on the same data, the mean-field posterior is
    # 2.2x too narrow; a 2x2 full-rank block is the cheapest thing that could
    # account for it.
    self.beta_guide = beta_guide
    self.beta_low = float(beta_low)
    self.beta_high = float(beta_high)
    # beta0 is a log-rate anchored near the matched filter's estimate; beta_inj is
    # a log-ratio centred near zero. One interval for both has to be wide enough
    # for the union, which either clips a plausible beta_inj or makes beta0's
    # prior far wider than intended -- and a value outside the support scores
    # -inf and fails silently. So they get their own bounds.
    self.beta_inj_low = float(bi_low)
    self.beta_inj_high = float(bi_high)

    # Bayesian phasic GLM coefficients: Normal prior, mean-field posterior
    # (theory/points-inference eq 3), or Uniform prior with an
    # interval-supported transformed-Normal posterior. Prior means default
    # to the phasic anchors (under "uniform" they only seed the guide
    # init); scales are fixed weakly-informative on the log-rate axis.
    loc0 = phasic.beta0 if beta0_prior_loc is None else beta0_prior_loc
    loc_inj = phasic.beta_inj if beta_inj_prior_loc is None else beta_inj_prior_loc
    self.beta0_prior_loc = float(loc0)
    self.beta0_prior_scale = float(beta0_prior_scale)
    self.beta_inj_prior_loc = float(loc_inj)
    self.beta_inj_prior_scale = float(beta_inj_prior_scale)

    # Optional Bayesian emission scale: Normal prior on log sigma_y (= LogNormal
    # on sigma_y), mean-field posterior, same form as the betas
    # (theory/points-inference: Theta priors are Gaussian on the unconstrained
    # transform). `sigma_y_prior_loc is None` keeps the legacy MAP point
    # estimate. A *narrow* prior_scale anchored on the data's high-frequency
    # noise floor is what stops sigma_y inflating to absorb tonic misfit.
    self.bayesian_sigma_y = sigma_y_prior_loc is not None
    self.sigma_y_prior_loc = None if sigma_y_prior_loc is None else float(sigma_y_prior_loc)
    self.sigma_y_prior_scale = float(sigma_y_prior_scale)
    if self.bayesian_sigma_y:
        # sigma_y is now a sampled latent, not a MAP param: freeze the emission's
        # point param so pyro.module doesn't optimize a value the likelihood
        # no longer reads (the model passes the sampled sigma_y instead).
        self.emission.log_sigma_y.requires_grad_(False)

model

model(y, inj_t, tilt=None, obs_mask=None)

Joint p(y, s, a | Theta) with relaxed events.

y is [B, T] observed traces sharing one injection bin inj_t. Samples relaxed events s_t ~ RelaxedBernoulli(tau, p_t) and marks a_t ~ LogNormal(mu_a, sigma_a) in a (sequences x time) plate, forms the deterministic drive u = s a, phasic c = h * u and additive mean m = x_hat + c, then scores y under the emission.

Source code in src/photosvi/models/points/points.py
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def model(self, y: torch.Tensor, inj_t: int, tilt: tuple[float, float] | None = None,
          obs_mask=None):
    """Joint p(y, s, a | Theta) with relaxed events.

    `y` is [B, T] observed traces sharing one injection bin `inj_t`. Samples
    relaxed events s_t ~ RelaxedBernoulli(tau, p_t) and marks
    a_t ~ LogNormal(mu_a, sigma_a) in a (sequences x time) plate, forms the
    deterministic drive u = s a, phasic c = h * u and additive mean
    m = x_hat + c, then scores y under the emission.
    """
    pyro.module("points", self)
    B, T = y.shape
    device, dtype = y.device, y.dtype

    if self.beta_prior == "uniform":
        beta0 = pyro.sample("beta0", dist.Uniform(
            torch.as_tensor(self.beta_low, device=device, dtype=dtype),
            torch.as_tensor(self.beta_high, device=device, dtype=dtype)))
        beta_inj = pyro.sample("beta_inj", dist.Uniform(
            torch.as_tensor(self.beta_inj_low, device=device, dtype=dtype),
            torch.as_tensor(self.beta_inj_high, device=device, dtype=dtype)))
    else:
        beta0 = pyro.sample(
            "beta0",
            dist.Normal(
                torch.as_tensor(self.beta0_prior_loc, device=device, dtype=dtype),
                torch.as_tensor(self.beta0_prior_scale, device=device, dtype=dtype),
            ),
        )
        beta_inj = pyro.sample(
            "beta_inj",
            dist.Normal(
                torch.as_tensor(self.beta_inj_prior_loc, device=device, dtype=dtype),
                torch.as_tensor(self.beta_inj_prior_scale, device=device, dtype=dtype),
            ),
        )

    if tilt is not None:
        # Linear-response tilt. Adding t.theta to the log joint and differentiating
        # the fitted mean recovers the covariance: for the exact posterior
        # dE[theta]/dt IS Var(theta), by the cumulant-generating identity. The
        # claim linear response makes is that a variational fit's *response* to
        # the tilt approximates the exact one even when its own covariance does
        # not -- so this is the whole method, expressed as one extra term.
        pyro.factor("lr_tilt", tilt[0] * beta0 + tilt[1] * beta_inj)

    # optional Bayesian emission scale: sample log sigma_y on the unconstrained
    # (Gaussian) axis, exp into the positive scale used by the emission factor.
    sigma_y = None
    if self.bayesian_sigma_y:
        log_sigma_y = pyro.sample(
            "log_sigma_y",
            dist.Normal(
                torch.as_tensor(self.sigma_y_prior_loc, device=device, dtype=dtype),
                torch.as_tensor(self.sigma_y_prior_scale, device=device, dtype=dtype),
            ),
        )
        sigma_y = log_sigma_y.exp()

    p = self._prior_event_prob(
        T, inj_t, device=device, dtype=dtype, beta0=beta0, beta_inj=beta_inj
    )  # [T]
    x_hat = self.tonic.baseline(T, inj_t)                             # [T]
    tau = torch.as_tensor(self.tau, device=device, dtype=dtype)
    mu_a, sigma_a = self.phasic.mu_a, self.phasic.sigma_a
    if getattr(self.phasic, "mark_prior", None) is not None:
        pyro.factor("mark_prior", self.phasic.mark_prior_logp())

    seq_plate = pyro.plate("sequences", B, dim=-2)
    time_plate = pyro.plate("time", T, dim=-1)

    with seq_plate, time_plate:
        s_dist = dist.RelaxedBernoulli(temperature=tau, probs=p)
        s = pyro.sample("s", s_dist)
        a_dist = dist.LogNormal(mu_a, sigma_a)
        a = pyro.sample("a", a_dist)

    if self.mark_kl != "sampled":
        pyro.factor("a_sampled_logp_undo", -a_dist.log_prob(a).sum())

    if self.analytic_s_kl:
        # Cancel this site's relaxed log p(s). The guide cancels its own log q(s)
        # and adds the analytic Bernoulli KL in their place, so the events'
        # contribution to the ELBO becomes -KL(Bernoulli(q) || Bernoulli(p(beta)))
        # exactly. See the class docstring for why.
        pyro.factor("s_relaxed_logp_undo", -s_dist.log_prob(s).sum())

    u = s * a                          # relaxed drive [B, T]
    c = self.phasic.convolve(u)        # phasic fluorescence [B, T]
    mean = x_hat + c                   # additive mean [B, T]

    # The structural mean, recorded BEFORE the emission so a diagnostic can read it.
    # Under a coloured emission the mean at the `y` site is the CONDITIONAL mean --
    # it carries the previous residual -- so reading that as "the fitted signal"
    # turns every residual diagnostic into a one-step-ahead prediction error, which
    # for a smooth trace is near zero and says nothing. `fitted_mean` prefers this.
    pyro.deterministic("mean_struct", mean)
    with seq_plate, time_plate:
        em = self._emission_dist(mean, sigma_y=sigma_y, obs=y)
        if obs_mask is not None:
            em = em.mask(observed_bins(obs_mask, y.shape, y.device,
                                       len(self.emission.ar_coeffs)))
        pyro.sample("y", em, obs=y)

guide

guide(y, inj_t, tilt=None, obs_mask=None)

Mean-field guide over the per-bin events and marks (free params).

q(s_t) = RelaxedBernoulli(tau, logits=ell_t) and q(a_t) = LogNormal(loc_t, scale_t), with ell, loc, scale free pyro.params of shape [B, T]. The event guide is binary-Concrete at the SAME temperature as the model prior, so the relaxed ELBO is valid.

Source code in src/photosvi/models/points/points.py
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
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
723
724
725
726
727
728
729
def guide(self, y: torch.Tensor, inj_t: int, tilt: tuple[float, float] | None = None,
          obs_mask=None):
    """Mean-field guide over the per-bin events and marks (free params).

    q(s_t) = RelaxedBernoulli(tau, logits=ell_t) and q(a_t) =
    LogNormal(loc_t, scale_t), with ell, loc, scale free `pyro.param`s of
    shape [B, T]. The event guide is binary-Concrete at the SAME temperature as
    the model prior, so the relaxed ELBO is valid.
    """
    B, T = y.shape
    device, dtype = y.device, y.dtype
    tau = torch.as_tensor(self.tau, device=device, dtype=dtype)

    # global beta posterior. Normal-prior path: mean-field Normal on the
    # log-rate axis, loc initialized at the prior mean. Uniform-prior path:
    # the same free (loc, scale) pair lives on an UNCONSTRAINED base axis
    # and is pushed through sigmoid+affine onto (beta_low, beta_high) so
    # q's support matches the prior's; loc is initialized so the
    # transformed guide starts at the anchor. Either way scale starts
    # small-but-free (positive).
    uniform = self.beta_prior == "uniform"
    b0_init = self._beta_guide_init(self.beta0_prior_loc) if uniform else self.beta0_prior_loc
    bi_init = (
        self._beta_guide_init(self.beta_inj_prior_loc, inj=True)
        if uniform
        else self.beta_inj_prior_loc
    )
    b0_loc = pyro.param(
        "q_beta0_loc",
        torch.as_tensor(b0_init, device=device, dtype=dtype),
    )
    b0_scale = pyro.param(
        "q_beta0_scale",
        torch.tensor(0.1, device=device, dtype=dtype),
        constraint=dist.constraints.positive,
    )
    bi_loc = pyro.param(
        "q_beta_inj_loc",
        torch.as_tensor(bi_init, device=device, dtype=dtype),
    )
    bi_scale = pyro.param(
        "q_beta_inj_scale",
        torch.tensor(0.1, device=device, dtype=dtype),
        constraint=dist.constraints.positive,
    )
    if self.beta_guide == "fullrank":
        # One correlated draw for the pair, unpacked onto the model's two sites.
        # The joint is sampled as an auxiliary site so the ELBO takes its log q
        # (including the transform's Jacobian, which is why the transform is
        # applied to the distribution rather than to the sample); the two Delta
        # sites then contribute nothing of their own and simply carry the values
        # to the model.
        loc = pyro.param(
            "q_beta_loc",
            torch.stack([torch.as_tensor(b0_init, device=device, dtype=dtype),
                         torch.as_tensor(bi_init, device=device, dtype=dtype)]),
        )
        tril = pyro.param(
            "q_beta_tril",
            0.1 * torch.eye(2, device=device, dtype=dtype),
            constraint=dist.constraints.lower_cholesky,
        )
        base = dist.MultivariateNormal(loc, scale_tril=tril)
        if uniform:
            lo = torch.tensor([self.beta_low, self.beta_inj_low],
                              device=device, dtype=dtype)
            width = torch.tensor(
                [self.beta_high - self.beta_low,
                 self.beta_inj_high - self.beta_inj_low], device=device, dtype=dtype)
            q_beta = dist.TransformedDistribution(
                base, [dist.transforms.SigmoidTransform(),
                       dist.transforms.AffineTransform(lo, width)])
        else:
            q_beta = base
        pair = pyro.sample("_beta_joint", q_beta, infer={"is_auxiliary": True})
        beta0 = pyro.sample("beta0", dist.Delta(pair[0]))
        beta_inj = pyro.sample("beta_inj", dist.Delta(pair[1]))
    elif uniform:
        beta0 = pyro.sample(
            "beta0", self._beta_guide_dist(b0_loc, b0_scale, device=device, dtype=dtype)
        )
        beta_inj = pyro.sample(
            "beta_inj",
            self._beta_guide_dist(bi_loc, bi_scale, device=device, dtype=dtype, inj=True),
        )
    else:
        beta0 = pyro.sample("beta0", dist.Normal(b0_loc, b0_scale))
        beta_inj = pyro.sample("beta_inj", dist.Normal(bi_loc, bi_scale))

    # mean-field posterior over log sigma_y, mirroring the beta block (only
    # when the Bayesian-scale path is active so model/guide sites match).
    if self.bayesian_sigma_y:
        sy_loc = pyro.param(
            "q_log_sigma_y_loc",
            torch.as_tensor(self.sigma_y_prior_loc, device=device, dtype=dtype),
        )
        sy_scale = pyro.param(
            "q_log_sigma_y_scale",
            torch.tensor(0.1, device=device, dtype=dtype),
            constraint=dist.constraints.positive,
        )
        pyro.sample("log_sigma_y", dist.Normal(sy_loc, sy_scale))

    # event logits are delegated to the pluggable event-guide block (free
    # per-bin by default, or an amortized family).
    if self.couple_events:
        # coupled: the anchor is rebuilt at the betas SAMPLED just above and left
        # differentiable, so a gradient on the rate reshapes q(s). The block then
        # supplies a residual on top of that anchor, hence the zero init -- passing
        # the prior logit here too would double-count it.
        p_live = self._prior_event_prob(
            T, inj_t, device=device, dtype=dtype, beta0=beta0, beta_inj=beta_inj
        )
        anchor = p_live.clamp(1e-9, 1 - 1e-9).logit()
        zeros = torch.zeros(T, device=device, dtype=dtype)
        s_logits = self.event_guide(y, inj_t, prior_logits=zeros) + anchor
    else:
        # decoupled (default): the prior intensity is passed as the init anchor so
        # the free block starts honest, detached because the param-store init must
        # be a leaf, not a function of Theta.
        p0 = self._prior_event_prob(T, inj_t, device=device, dtype=dtype).detach()
        ell0 = p0.clamp(1e-6, 1 - 1e-6).logit()
        s_logits = self.event_guide(y, inj_t, prior_logits=ell0)
    # Per-window marks when the event factor is windowed, per-bin otherwise.
    # The point of tying them is not economy: a mark at a bin with no event is a
    # latent the data cannot speak to, and 60000 of them held only by a
    # divergence against a *fitted* prior is what dragged that prior away.
    # Measured before this change: mu_a fell 1.767 -> 0.368 and sigma_a rose
    # 0.212 -> 0.877, the latter landing on the empty-bin posterior width.
    W = self.mark_window
    mu_a_init = (float(self.phasic.mu_a.detach())
                 if getattr(self.phasic, "q_a_init", "noise") == "prior" else
                 min(float(self.phasic.mu_a.detach()),
                     float(torch.log(self.emission.sigma_y.detach()))))
    if W and W > 1:
        n_win = -(-T // W)
        # Initialised at the NOISE SCALE, capped by the prior. Neither of the
        # obvious choices works in both regimes, and the reason is the same one:
        # what matters is not how the starting mark compares to the prior but how
        # the SPURIOUS DRIVE it creates compares to the noise. q(s_t) is small but
        # not zero at the ~90% of windows holding no event, so every one of them
        # contributes q.E[a] to the fitted mean from step one.
        #
        #   q_a_loc = 0 puts E[a] at 1.0 whatever the units are: 1.7 sigma_y on
        #   simulated cohorts, but 82 sigma_y on real dF/F recordings, where it
        #   drove the marks to E[a] = 8 and the fit never recovered.
        #
        #   q_a_loc = mu_a puts it at the prior: 0.02 (1.7 sigma_y) on real
        #   recordings, which is right, but 6.0 (57 sigma_y) on simulated ones,
        #   where the phasic component reached 10^6 by step 1000 and the loss rose
        #   six orders of magnitude before failing.
        #
        # Starting at the smaller of the two is what both regimes actually want:
        # every mark begins at the level below which it cannot disturb the fit,
        # and the windows that hold an event are raised from there by the data.
        # Measured on a simulated cohort, marks at event windows climb from the
        # noise scale to 4.6 against a true 5.85 within 1000 steps, while the
        # empty ones fall away -- which is the behaviour a gated divergence is
        # supposed to produce and which an anchor at the prior prevents.
        a_loc = pyro.param(
            "q_a_loc", torch.full((B, n_win), mu_a_init, device=device, dtype=dtype)
        ).repeat_interleave(W, dim=-1)[:, :T]
        # The SCALE stays deliberately diffuse and is NOT initialised at
        # sigma_a. A narrow q(a) is a confident claim, and at step zero the claim
        # is wrong wherever a window does hold an event -- the mark there is the
        # prior's, several units above the noise the loc starts at. Confident and
        # wrong together is the combination that kills the fit: measured on a
        # simulated cohort, loc at the noise scale with sigma_a's width failed
        # within 2000 steps, the same loc with a width of 0.5 survived, and the
        # old loc with either width survived. Neither axis does it alone.
        a_scale = pyro.param(
            "q_a_scale",
            _MARK_SCALE_INIT * torch.ones(B, n_win, device=device, dtype=dtype),
            constraint=dist.constraints.interval(0.0, _MARK_SCALE_MAX),
        ).repeat_interleave(W, dim=-1)[:, :T]
    else:
        a_loc = pyro.param(
            "q_a_loc", torch.full((B, T), mu_a_init, device=device, dtype=dtype)
        )
        a_scale = pyro.param(
            "q_a_scale",
            _MARK_SCALE_INIT * torch.ones(B, T, device=device, dtype=dtype),
            constraint=dist.constraints.positive,
        )

    seq_plate = pyro.plate("sequences", B, dim=-2)
    time_plate = pyro.plate("time", T, dim=-1)
    with seq_plate, time_plate:
        q_dist = dist.RelaxedBernoulli(temperature=tau, logits=s_logits)
        s = pyro.sample("s", q_dist)
        qa_dist = dist.LogNormal(a_loc, a_scale)
        a_draw = pyro.sample("a", qa_dist)

    if self.mark_kl != "sampled":
        # A marked point process has marks only where it has points. The model
        # draws a_t at every bin because u_t = s_t * a_t is convenient to write,
        # but where s_t = 0 the mark does not exist -- it is a latent kept for
        # notation. Charging its full divergence at all 60000 bins estimates the
        # mark distribution from ~59700 bins that contain no transient, and the
        # hyperparameters follow: measured, mu_a collapsed 1.767 -> 0.368 and
        # sigma_a inflated 0.212 -> 0.877, the latter landing exactly on the
        # empty-bin posterior width. "gated" weights the divergence by q(s_t),
        # which is what the generative story implies.
        mk = self._lognormal_kl(
            a_loc, a_scale, self.phasic.mu_a, self.phasic.sigma_a
        )
        if self.mark_kl == "gated":
            mk = torch.sigmoid(s_logits).clamp_min(self.mark_gate_floor) * mk
        pyro.factor("a_sampled_logq_undo", -qa_dist.log_prob(a_draw).sum(),
                    has_rsample=True)
        pyro.factor("a_mark_kl", mk.sum(), has_rsample=True)

    if self.analytic_s_kl:
        # A factor here adds to log q, hence subtracts from the ELBO. Undo this
        # site's relaxed log q(s) (so the sampling stays reparameterized for the
        # reconstruction path but stops scoring beta), then charge the analytic
        # Bernoulli KL in its place.
        p_beta = self._prior_event_prob(
            T, inj_t, device=device, dtype=dtype, beta0=beta0, beta_inj=beta_inj
        )
        # has_rsample: both are differentiable functions of reparameterized draws
        # -- `s` from the relaxed guide, and the betas from their Normal posteriors.
        pyro.factor(
            "s_relaxed_logq_undo", -q_dist.log_prob(s).sum(), has_rsample=True
        )
        pyro.factor(
            "s_analytic_kl",
            self._bernoulli_kl(s_logits, p_beta).sum(),
            has_rsample=True,
        )

event_posterior

event_posterior(y, inj_t=None)

Variational event probabilities q(s_t = 1) = sigmoid(ell_t), shape [B, T].

Asks the event-guide block for its fitted logits (call after training). These are the relaxed-Bernoulli means, the model's per-bin belief that an event occurred -- the points family's whole output. Identical readout whichever event-guide family is installed.

Under couple_events the block's logits are only part of q(s): guide() adds the live prior anchor on top, so the block alone is not the posterior. This reconstructs the sum at the posterior-mean betas, which is why inj_t becomes required there -- the anchor is a function of the injection bin. Reading the block alone under coupling silently over-states q by the whole prior log-odds (order 7 logits at these rates), which shows up as a wildly over-confident detector rather than as an error.

Source code in src/photosvi/models/points/points.py
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
@torch.no_grad()
def event_posterior(self, y: torch.Tensor, inj_t: int | None = None) -> torch.Tensor:
    """Variational event probabilities q(s_t = 1) = sigmoid(ell_t), shape [B, T].

    Asks the event-guide block for its fitted logits (call after training).
    These are the relaxed-Bernoulli means, the model's per-bin belief that an
    event occurred -- the points family's whole output. Identical readout
    whichever event-guide family is installed.

    Under `couple_events` the block's logits are only *part* of q(s): `guide()`
    adds the live prior anchor on top, so the block alone is not the posterior.
    This reconstructs the sum at the posterior-mean betas, which is why `inj_t`
    becomes required there -- the anchor is a function of the injection bin.
    Reading the block alone under coupling silently over-states q by the whole
    prior log-odds (order 7 logits at these rates), which shows up as a wildly
    over-confident detector rather than as an error.
    """
    ell = self.event_guide.fitted_logits(y)
    if not self.couple_events:
        return torch.sigmoid(ell)
    if inj_t is None:
        raise ValueError(
            "event_posterior(y, inj_t) requires inj_t when couple_events=True: the "
            "guide's event logits include a prior anchor that depends on it."
        )
    T = y.shape[-1]
    bp = self.beta_posterior()
    b0 = torch.as_tensor(bp["beta0"][0], device=y.device, dtype=y.dtype)
    bi = torch.as_tensor(bp["beta_inj"][0], device=y.device, dtype=y.dtype)
    p_live = self._prior_event_prob(
        T, inj_t, device=y.device, dtype=y.dtype, beta0=b0, beta_inj=bi
    )
    return torch.sigmoid(ell + p_live.clamp(1e-9, 1 - 1e-9).logit())

reconstruct

reconstruct(y, inj_t=None)

The fitted trace, split into its tonic and phasic parts. Call after training.

Returns {"tonic", "phasic", "mean"}, each [B, T], where mean = tonic + phasic is the model's posterior-mean fluorescence -- the recording with the emission noise removed, which is the only part of y the model claims to explain. What is left over, y - mean, is the residual, and a residual that still looks like transients is the diagnostic that says so.

Both parts are posterior means and the split is exact rather than a decomposition chosen afterwards: the tonic is the fitted pharmacokinetic baseline, the phasic is the kernel convolved with the expected drive E[u_t] = q(s_t = 1) . E[a_t]. Expectation passes through the convolution because it is linear, so this is the mean of the model's mean and not a single posterior draw -- it will look smoother than any trace the generative model would produce, which is the point of plotting it against the raw data.

The marks are read from the variational LogNormal, E[a] = exp(loc + scale^2 / 2), and where the event factor is windowed each window's mark applies to all its bins -- the same broadcast guide performs, so the reconstruction is the drive the fit actually used.

Source code in src/photosvi/models/points/points.py
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
@torch.no_grad()
def reconstruct(self, y: torch.Tensor, inj_t: int | None = None) -> dict[str, torch.Tensor]:
    """The fitted trace, split into its tonic and phasic parts. Call after training.

    Returns `{"tonic", "phasic", "mean"}`, each [B, T], where `mean = tonic +
    phasic` is the model's posterior-mean fluorescence -- the recording with the
    emission noise removed, which is the only part of `y` the model claims to
    explain. What is left over, `y - mean`, is the residual, and a residual that
    still looks like transients is the diagnostic that says so.

    Both parts are posterior means and the split is exact rather than a
    decomposition chosen afterwards: the tonic is the fitted pharmacokinetic
    baseline, the phasic is the kernel convolved with the expected drive
    `E[u_t] = q(s_t = 1) . E[a_t]`. Expectation passes through the convolution
    because it is linear, so this is the mean of the model's mean and not a
    single posterior draw -- it will look smoother than any trace the generative
    model would produce, which is the point of plotting it against the raw data.

    The marks are read from the variational LogNormal, `E[a] = exp(loc +
    scale^2 / 2)`, and where the event factor is windowed each window's mark
    applies to all its bins -- the same broadcast `guide` performs, so the
    reconstruction is the drive the fit actually used.
    """
    q = self.event_posterior(y, inj_t)                                  # [B, T]
    B, T = y.shape
    W = self.mark_window
    loc = pyro.param("q_a_loc")
    scale = pyro.param("q_a_scale")
    if W and W > 1:
        loc = loc.repeat_interleave(W, dim=-1)[:, :T]
        scale = scale.repeat_interleave(W, dim=-1)[:, :T]
    a_mean = torch.exp(loc + 0.5 * scale**2).to(device=y.device, dtype=y.dtype)
    phasic = self.phasic.convolve(q * a_mean)
    tonic = self.tonic.baseline(T, inj_t).expand(B, T)
    return dict(tonic=tonic, phasic=phasic, mean=tonic + phasic)

beta_posterior

beta_posterior()

Fitted mean-field posterior over the phasic GLM coefficients.

Returns {"beta0": (loc, scale), "beta_inj": (loc, scale)} read from the Pyro param store (call after training). beta_inj's loc is the inferred post-injection log-rate shift -- the drug-effect-on-event-rate estimate -- and its scale is the posterior std, the credible width on that effect.

Under beta_prior="uniform" the guide params live on the unconstrained base axis, so they are mapped back to the log-rate interval first: loc becomes the exact posterior median (monotone transform), scale a delta-method std about it. Same return shape either way.

Source code in src/photosvi/models/points/points.py
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
@torch.no_grad()
def beta_posterior(self) -> dict[str, float]:
    """Fitted mean-field posterior over the phasic GLM coefficients.

    Returns `{"beta0": (loc, scale), "beta_inj": (loc, scale)}` read from the
    Pyro param store (call after training). `beta_inj`'s loc is the inferred
    post-injection log-rate shift -- the drug-effect-on-event-rate estimate
    -- and its scale is the posterior std, the credible width on that effect.

    Under `beta_prior="uniform"` the guide params live on the unconstrained
    base axis, so they are mapped back to the log-rate interval first: loc
    becomes the exact posterior median (monotone transform), scale a
    delta-method std about it. Same return shape either way.
    """
    if self.beta_guide == "fullrank":
        fr_loc = pyro.param("q_beta_loc").detach()
        fr_cov = pyro.param("q_beta_tril").detach()
        fr_cov = fr_cov @ fr_cov.T
        marg = [(float(fr_loc[i]), float(fr_cov[i, i].sqrt())) for i in range(2)]

    out = {}
    for i, name in enumerate(("beta0", "beta_inj")):
        if self.beta_guide == "fullrank":
            # The marginal of a correlated joint, which is what a credible
            # interval on one coefficient means. The correlation itself is the
            # point of the block and is reported by `beta_correlation`.
            loc, scale = marg[i]
        else:
            loc = float(pyro.param(f"q_{name}_loc").detach())
            scale = float(pyro.param(f"q_{name}_scale").detach())
        if self.beta_prior == "uniform":
            # Each coefficient has its own interval, so each must be read back
            # through its own transform: beta0's bounds track the trace's rate
            # anchor, beta_inj's are centred on zero. Using one pair for both
            # silently reports beta_inj on beta0's axis.
            lo, hi = (
                (self.beta_inj_low, self.beta_inj_high)
                if name == "beta_inj"
                else (self.beta_low, self.beta_high)
            )
            width = hi - lo
            p = 1.0 / (1.0 + math.exp(-loc))
            loc = lo + width * p
            scale = scale * width * p * (1.0 - p)
        out[name] = (loc, scale)
    return out

beta_correlation

beta_correlation()

Posterior correlation between beta0 and beta_inj under the full-rank guide.

The quantity a mean-field guide is forced to set to zero. The two trade off by construction -- a higher baseline and a smaller injection effect explain the same post-injection rate -- so a large negative value here is the correlation whose omission narrows the mean-field marginals.

Source code in src/photosvi/models/points/points.py
877
878
879
880
881
882
883
884
885
886
887
888
889
890
@torch.no_grad()
def beta_correlation(self) -> float:
    """Posterior correlation between beta0 and beta_inj under the full-rank guide.

    The quantity a mean-field guide is forced to set to zero. The two trade off
    by construction -- a higher baseline and a smaller injection effect explain
    the same post-injection rate -- so a large negative value here is the
    correlation whose omission narrows the mean-field marginals.
    """
    if self.beta_guide != "fullrank":
        raise RuntimeError("beta_correlation requires beta_guide='fullrank'")
    tril = pyro.param("q_beta_tril").detach()
    cov = tril @ tril.T
    return float(cov[0, 1] / (cov[0, 0].sqrt() * cov[1, 1].sqrt()))

scale_posterior

scale_posterior()

Fitted mean-field posterior over the emission scale sigma_y.

Only meaningful when the Bayesian-scale path is active (sigma_y_prior_loc was supplied); raises otherwise. Returns {"log_sigma_y_loc", "log_sigma_y_scale", "sigma_y"} read from the Pyro param store (call after training), where sigma_y = exp(log_sigma_y_loc) is the posterior median residual scale. A value that stays near the high-frequency anchor (rather than inflating) is the win this path buys.

Source code in src/photosvi/models/points/points.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
@torch.no_grad()
def scale_posterior(self) -> dict[str, float]:
    """Fitted mean-field posterior over the emission scale sigma_y.

    Only meaningful when the Bayesian-scale path is active
    (`sigma_y_prior_loc` was supplied); raises otherwise. Returns
    `{"log_sigma_y_loc", "log_sigma_y_scale", "sigma_y"}` read from the Pyro
    param store (call after training), where `sigma_y = exp(log_sigma_y_loc)`
    is the posterior median residual scale. A value that stays near the
    high-frequency anchor (rather than inflating) is the win this path buys.
    """
    if not self.bayesian_sigma_y:
        raise RuntimeError(
            "scale_posterior() requires the Bayesian sigma_y path "
            "(pass sigma_y_prior_loc to SingleTraceModel); sigma_y is a MAP point "
            "estimate here -- read emission.sigma_y instead."
        )
    loc = float(pyro.param("q_log_sigma_y_loc").detach())
    scale = float(pyro.param("q_log_sigma_y_scale").detach())
    return {
        "log_sigma_y_loc": loc,
        "log_sigma_y_scale": scale,
        "sigma_y": float(torch.tensor(loc).exp()),
    }

photosvi.models.points.HierarchicalModel

HierarchicalModel(phasic, tonic, emission, *, animal, drug, inj_t, beta0_anchor, n_animals=None, n_drugs=None, levels=None, mu_b0_prior_scale=2.0, sigma_b0_prior_loc=0.5, sigma_b0_prior_scale=0.5, sigma_b0_session_prior_loc=0.25, sigma_b0_session_prior_scale=0.5, mu_drug_prior_scale=1.0, block_init_at_prior=False, sigma_animal_prior_loc=0.5, sigma_animal_prior_scale=0.5, sigma_cell_prior_loc=0.35, sigma_cell_prior_scale=0.5, sigma_session_prior_loc=0.25, sigma_session_prior_scale=0.5, tonic_hierarchy=True, tonic_mu_prior_scale=None, tonic_sigma_prior_loc=None, tonic_sigma_prior_scale=0.5, tonic_block=False, bayesian_offsets=False, offset_prior_scale=None, tau=0.5, event_guide=None, couple_events=False, analytic_s_kl=True, mark_kl='gated', mark_gate_floor=_MARK_GATE_FLOOR, mark_window=None, beta_guide='fullrank_z')

Bases: Module

Crossed animal x drug hierarchy over the phasic rate coefficients.

Parameters:

Name Type Description Default
phasic PhasicEventProcess supplying the kernel, the mark hyperparameters and

convolve. Its own beta0 / beta_inj are unused: the coefficients are latent here. Must have history_len == 0.

required
tonic BatchedTonicBaseline with one parameter row per session.
required
emission AdditiveEmission supplying sigma_y, shared across the cohort.
required
animal length-S integer index, `animal[s]` = which animal recorded session s.
required
drug length-S integer index, `drug[s]` = which drug session s received. A

length-A vector is also accepted as shorthand for the one-drug-per-animal design. Any assignment is allowed; see "Which levels exist" above for what each design can identify.

required
inj_t length-S integer tensor of injection bins, one per session.
required
beta0_anchor prior mean for `mu_b0` on the log-rate axis -- the cohort's

matched-filter baseline estimate. The prior is deliberately wide.

required
n_animals sizes of the two index sets. Inferred from the indices when

omitted, which is right only if every level appears in the data; pass them explicitly when a level can be empty.

None
n_drugs sizes of the two index sets. Inferred from the indices when

omitted, which is right only if every level appears in the data; pass them explicitly when a level can be empty.

None
levels optional override of the detected random-effect levels, as a subset of

("animal", "cell", "session"). Detection is the documented behaviour and an override that asks for an unidentifiable level is an error, not a warning -- the failure mode is silent variance stealing, which no diagnostic catches.

None
tau as in

SingleTraceModel, and with the same defaults -- the fixed model, unchanged. The hierarchy is over the coefficients only.

0.5
event_guide as in

SingleTraceModel, and with the same defaults -- the fixed model, unchanged. The hierarchy is over the coefficients only.

0.5
couple_events as in

SingleTraceModel, and with the same defaults -- the fixed model, unchanged. The hierarchy is over the coefficients only.

0.5
analytic_s_kl as in

SingleTraceModel, and with the same defaults -- the fixed model, unchanged. The hierarchy is over the coefficients only.

0.5
mark_kl as in

SingleTraceModel, and with the same defaults -- the fixed model, unchanged. The hierarchy is over the coefficients only.

0.5
mark_window as in

SingleTraceModel, and with the same defaults -- the fixed model, unchanged. The hierarchy is over the coefficients only.

0.5
Source code in src/photosvi/models/points/hierarchical.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
def __init__(
    self,
    phasic: PhasicEventProcess,
    tonic: BatchedTonicBaseline,
    emission: AdditiveEmission,
    *,
    animal,
    drug,
    inj_t,
    beta0_anchor: float,
    n_animals: int | None = None,
    n_drugs: int | None = None,
    levels: tuple[str, ...] | None = None,
    mu_b0_prior_scale: float = 2.0,
    sigma_b0_prior_loc: float = 0.5,
    sigma_b0_prior_scale: float = 0.5,
    sigma_b0_session_prior_loc: float = 0.25,
    sigma_b0_session_prior_scale: float = 0.5,
    mu_drug_prior_scale: float = 1.0,
    # Seed the block's diagonal for mu_b0 and mu_drug at their prior scales
    # rather than at 0.1. See `_block_init`. Off by default: every cohort
    # result in the paper was fitted from 0.1.
    block_init_at_prior: bool = False,
    sigma_animal_prior_loc: float = 0.5,
    sigma_animal_prior_scale: float = 0.5,
    sigma_cell_prior_loc: float = 0.35,
    sigma_cell_prior_scale: float = 0.5,
    sigma_session_prior_loc: float = 0.25,
    sigma_session_prior_scale: float = 0.5,
    tonic_hierarchy: bool = True,
    tonic_mu_prior_scale: dict | None = None,
    tonic_sigma_prior_loc: dict | None = None,
    tonic_sigma_prior_scale: float = 0.5,
    tonic_block: bool = False,
    bayesian_offsets: bool = False,
    offset_prior_scale: dict | None = None,
    tau: float = 0.5,
    event_guide: nn.Module | None = None,
    couple_events: bool = False,
    analytic_s_kl: bool = True,
    mark_kl: str = "gated",
    mark_gate_floor: float = _MARK_GATE_FLOOR,
    mark_window: int | None = None,
    # The joint block over the globals AND every non-centred effect.
    #
    # Default since 2026-09-14, matching `SingleTraceModel`'s move to "fullrank"
    # and for the same reason: a default that is wrong for every production use
    # is not neutral. Over 24 null crossed cohorts this family reports a contrast
    # interval 0.99x the estimator's realised spread where a block over the
    # globals alone reports 1.57x, and it is the only one that recovers the
    # animal x drug interaction (0.104 against a simulated 0.10). It costs
    # nothing: 37.7 ms/step against 40.2, a 72x72 Cholesky being free beside
    # 2.9 M per-bin latents.
    #
    # `build_cohort_model` reads the config and never falls through to this, so
    # the default only reaches someone constructing the class directly. That is
    # exactly the caller the old default caught out once already.
    #
    # NOT a universal answer: it is calibrated on a CROSSED design, where the
    # animal effect cancels from a drug contrast. It reports sigma_animal at 60%
    # of truth, which is the component an uncrossed design leans on.
    beta_guide: str = "fullrank_z",
):
    super().__init__()
    if phasic.history_len != 0:
        raise NotImplementedError(
            "hierarchical slice requires history_len == 0 (no FIR self-excitation)"
        )
    if tau <= 0:
        raise ValueError(f"relaxation temperature tau must be > 0 (got {tau})")
    if mark_kl not in ("sampled", "analytic", "gated"):
        raise ValueError(f"mark_kl must be 'sampled', 'analytic' or 'gated' (got {mark_kl!r})")
    if beta_guide not in ("meanfield", "fullrank", "fullrank_za", "fullrank_z"):
        raise ValueError(
            "beta_guide must be 'meanfield', 'fullrank', 'fullrank_za' or "
            f"'fullrank_z' (got {beta_guide!r})")
    priors = {
        "b0": (sigma_b0_prior_loc, sigma_b0_prior_scale),
        "animal": (sigma_animal_prior_loc, sigma_animal_prior_scale),
        "cell": (sigma_cell_prior_loc, sigma_cell_prior_scale),
        "session": (sigma_session_prior_loc, sigma_session_prior_scale),
        "b0_session": (sigma_b0_session_prior_loc, sigma_b0_session_prior_scale),
    }
    for name, (loc, scale) in priors.items():
        if loc <= 0 or scale <= 0:
            raise ValueError(f"sigma_{name} prior loc and scale must be > 0")
    if mu_b0_prior_scale <= 0 or mu_drug_prior_scale <= 0:
        raise ValueError("mu prior scales must be > 0")

    a, d, inj, A, D = self._parse_indices(animal, drug, inj_t, n_animals, n_drugs)
    if a.numel() != tonic.n_seq:
        raise ValueError(
            f"tonic carries {tonic.n_seq} sessions but the indices name {a.numel()}"
        )
    cell, n_cells = self._cell_index(a, d)
    detected = self._detect_levels(a, d, cell, n_cells, A)
    if levels is None:
        active = detected
    else:
        active = tuple(x for x in _LEVELS if x in set(levels))
        bad = set(levels) - set(_LEVELS)
        if bad:
            raise ValueError(f"unknown level(s) {sorted(bad)}; choose from {_LEVELS}")
        unidentifiable = set(active) - set(detected)
        if unidentifiable:
            raise ValueError(
                f"level(s) {sorted(unidentifiable)} are not identifiable from this "
                f"design (detected: {detected}). An unidentifiable variance "
                "component absorbs the one below it -- usually sigma_animal, which "
                "is what sets the drug contrast's width."
            )

    self.phasic = phasic
    self.tonic = tonic
    self.emission = emission
    self.event_guide = FreeEventGuide() if event_guide is None else event_guide
    self.register_buffer("animal", a)
    self.register_buffer("drug", d)
    self.register_buffer("cell", cell)
    self.register_buffer("inj_t", inj)
    self.n_sessions = int(a.numel())
    self.n_animals = A
    self.n_drugs = D
    self.n_cells = n_cells
    self.levels = active
    self.detected_levels = detected
    self.level_size = {"animal": A, "cell": n_cells, "session": self.n_sessions,
                       "b0_session": self.n_sessions}
    self.sigma_prior = priors
    self.beta0_anchor = float(beta0_anchor)

    # ---- drug-structured tonic. The per-drug means are anchored on the
    # least-squares pre-fits that built `tonic`, averaged within drug: the same
    # move as anchoring beta0 on the matched filter, and for the same reason --
    # a hard-coded pharmacokinetic constant would eventually sit outside a real
    # drug's range and the fit would start from nowhere.
    self.tonic_hierarchy = bool(tonic_hierarchy)
    # A second full-rank Gaussian block over the per-drug tonic means (alpha, rho,
    # gamma) x drugs, instead of a factorised Normal per coordinate (opt-in,
    # 2026-10-20). Only the means: the per-drug amplitude and rate contrasts are read
    # off them, and the three components of one drug's curve trade against each other
    # in the likelihood (a later, lower peak against an earlier, higher one), which a
    # factorised q calls independent. The tonic scales are sampled on their
    # constrained axis in the model, so blocking them would need a Jacobian term, and
    # the per-session deviations number 3S; both stay factorised.
    # Modes (2026-10-20): "means" (also True) blocks the per-drug means alone;
    # "with_sessions" adds the per-session deviations z^psi_j; and
    # "with_sessions_level_drift" also makes the per-session level b and drift d
    # variational latents (the `bayesian_offsets` sites) inside the same block, instead
    # of MAP point estimates.
    _modes = {False: "off", None: "off", "off": "off", True: "means", "means": "means",
              "with_sessions": "with_sessions",
              "with_sessions_level_drift": "with_sessions_level_drift"}
    if tonic_block not in _modes:
        raise ValueError(f"unknown tonic_block {tonic_block!r}")
    self.tonic_block_mode = _modes[tonic_block] if self.tonic_hierarchy else "off"
    self.tonic_block = self.tonic_block_mode != "off"
    if self.tonic_block_mode == "with_sessions_level_drift":
        bayesian_offsets = True
    # Wide by default: exp(1.0) is a 2.7x amplitude factor and exp(0.5) a 1.6x
    # rate factor, so the prior locates the curve without pinning it.
    self.tonic_mu_prior_scale = {"alpha": 1.0, "rho": 0.5, "gamma": 0.5} | (
        tonic_mu_prior_scale or {})
    self.tonic_sigma_prior_loc = {"alpha": 0.3, "rho": 0.2, "gamma": 0.2} | (
        tonic_sigma_prior_loc or {})
    self.tonic_sigma_prior_scale = float(tonic_sigma_prior_scale)
    # A MAP parameter has zero uncertainty by construction, so its error never
    # reaches the estimand. With one `b` and one `drift` per session that is 2S
    # point estimates whose uncertainty is silently discarded -- a source of
    # posterior overconfidence entirely separate from the mean-field
    # factorization, and worth being able to switch on and off to see which is
    # which. Anchored per session on the least-squares pre-fit, unpooled, because
    # bleaching and fibre placement are properties of the recording.
    self.bayesian_offsets = bool(bayesian_offsets)
    if self.bayesian_offsets and not self.tonic_hierarchy:
        raise ValueError(
            "bayesian_offsets requires tonic_hierarchy: the offsets are sampled "
            "inside the same block that builds the drug-structured carrier, and "
            "silently ignoring the request would make the comparison it exists "
            "for meaningless"
        )
    self.offset_prior_scale = {"b": 0.5, "drift": 0.005} | (offset_prior_scale or {})
    self.offset_anchor = {n: getattr(tonic, n).detach().clone()
                          for n in _TONIC_OFFSETS}
    if self.bayesian_offsets:
        for name in _TONIC_OFFSETS:
            getattr(tonic, name).requires_grad_(False)
    self.tonic_anchor = self._tonic_anchors(tonic, drug_of_session=d, n_drugs=D)
    # The per-session deviation needs a drug with more than one session; with one
    # session per drug it is confounded with the per-drug mean itself.
    self.tonic_session_level = bool(
        self.tonic_hierarchy and (torch.bincount(d, minlength=D) > 1).any())
    if self.tonic_hierarchy:
        # alpha/rho/gamma are now latents. Freeze the module's own copies so
        # pyro.module does not optimise parameters the likelihood no longer reads;
        # b and drift stay trainable, since they remain per-session MAP.
        for name in _TONIC_COMPONENTS:
            getattr(tonic, name).requires_grad_(False)
    self.mu_b0_prior_scale = float(mu_b0_prior_scale)
    self.block_init_at_prior = bool(block_init_at_prior)
    self.mu_drug_prior_scale = float(mu_drug_prior_scale)
    self.tau = float(tau)
    # The single-trace analogue of this block closed the whole gap between the
    # variational and the exact posterior: beta0 and beta_inj correlate at -0.88
    # because a higher baseline with a smaller injection effect explains the same
    # post-injection rate, and a mean-field q must call that zero. `mu_b0` and
    # `mu_drug` trade off here for the same reason, so the block covers exactly
    # those. The variance components stay mean-field until there is evidence they
    # need more -- adding them untested would make a null result uninterpretable.
    self.beta_guide = beta_guide
    self.couple_events = bool(couple_events)
    self.analytic_s_kl = bool(analytic_s_kl)
    self.mark_kl = mark_kl
    if not 0.0 <= mark_gate_floor < 1.0:
        raise ValueError(
            f"mark_gate_floor must be in [0, 1), got {mark_gate_floor!r}")
    self.mark_gate_floor = float(mark_gate_floor)
    if mark_window is None:
        mark_window = getattr(self.event_guide, "window", None)
    self.mark_window = int(mark_window) if mark_window else None

design_summary

design_summary()

What the model read off the indices -- sizes, active levels, and the shape.

within_animal says whether the drug contrast is a within-animal comparison (some animal saw several drugs) or a between-animal one. It is the single fact that most changes how much the cohort can resolve, so a fit should report it.

Source code in src/photosvi/models/points/hierarchical.py
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
def design_summary(self) -> dict:
    """What the model read off the indices -- sizes, active levels, and the shape.

    `within_animal` says whether the drug contrast is a within-animal comparison
    (some animal saw several drugs) or a between-animal one. It is the single fact
    that most changes how much the cohort can resolve, so a fit should report it.
    """
    per_animal_drugs = torch.zeros(self.n_animals, dtype=torch.long)
    for a_i in range(self.n_animals):
        m = self.animal == a_i
        per_animal_drugs[a_i] = int(torch.unique(self.drug[m]).numel()) if m.any() else 0
    return {
        "n_sessions": self.n_sessions,
        "n_animals": self.n_animals,
        "n_drugs": self.n_drugs,
        "n_cells": self.n_cells,
        "levels": self.levels,
        "detected_levels": self.detected_levels,
        "drugs_per_animal": per_animal_drugs.tolist(),
        "within_animal": "cell" in self.detected_levels,
        "tonic_hierarchy": self.tonic_hierarchy,
        "tonic_session_level": self.tonic_session_level,
        "bayesian_offsets": self.bayesian_offsets,
        "beta_guide": self.beta_guide,
    }

session_tonic

session_tonic()

The tonic actually used per session, in constrained units, [S] each.

Distinct from tonic_posterior, which reports the per-drug means. Under a non-centred parameterization the mean and the per-session deviations are only jointly identified, so a drifting mean with compensating deviations looks wrong at the population level while every session is still fitted well. The two readouts have to be compared to tell those cases apart.

Source code in src/photosvi/models/points/hierarchical.py
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
@torch.no_grad()
def session_tonic(self) -> dict[str, list[float]]:
    """The tonic actually used per session, in constrained units, [S] each.

    Distinct from `tonic_posterior`, which reports the per-drug *means*. Under a
    non-centred parameterization the mean and the per-session deviations are only
    jointly identified, so a drifting mean with compensating deviations looks
    wrong at the population level while every session is still fitted well. The
    two readouts have to be compared to tell those cases apart.
    """
    if not self.tonic_hierarchy:
        pk, kd, kr = self.tonic.peak, self.tonic.k_decay, self.tonic.k_rise
    else:
        vals = {}
        for name in _TONIC_COMPONENTS:
            v = self._tonic_mu_moments(name)[0][self.drug]
            if self.tonic_session_level:
                v = v + (pyro.param(f"q_tonic_sigma_{name}_loc").detach().exp()
                         * self._tonic_z_loc(name))
            vals[name] = v
        pk = vals["alpha"].exp()
        kd = vals["rho"].exp()
        kr = kd + vals["gamma"].exp()
    t_peak = (kr / kd).log() / (kr - kd)
    # "peak" is the HEIGHT of the bump in the trace's units, "peak_s" the TIME it
    # occurs at. Both are reported because the pair is what distinguishes the
    # drugs: how much tone the compound puts in, and how fast it gets there.
    return {"peak": [float(x) for x in pk], "k_decay": [float(x) for x in kd],
            "k_rise": [float(x) for x in kr], "peak_s": [float(x) for x in t_peak]}

tonic_scales

tonic_scales()

Posterior median of each tonic variance component.

Source code in src/photosvi/models/points/hierarchical.py
738
739
740
741
742
743
744
@torch.no_grad()
def tonic_scales(self) -> dict[str, float]:
    """Posterior median of each tonic variance component."""
    if not (self.tonic_hierarchy and self.tonic_session_level):
        return {}
    return {n: float(pyro.param(f"q_tonic_sigma_{n}_loc").detach().exp())
            for n in _TONIC_COMPONENTS}

tonic_guide_widths

tonic_guide_widths()

How wide the tonic guide's own posteriors got, and how close to the bound.

The bound of _TONIC_SCALE_RANGE stops a fit from diverging; it does not make the parameter identified. A scale sitting on the ceiling is the ceiling being reported, not something measured, and that has to be visible in the run record rather than reconstructed later -- which it could not be, because nothing was stored and the diverging cohort had to be re-run under instrumentation to find out what ran away.

Source code in src/photosvi/models/points/hierarchical.py
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
@torch.no_grad()
def tonic_guide_widths(self) -> dict[str, float]:
    """How wide the tonic guide's own posteriors got, and how close to the bound.

    The bound of `_TONIC_SCALE_RANGE` stops a fit from diverging; it does not make
    the parameter identified. A scale sitting on the ceiling is the ceiling being
    reported, not something measured, and that has to be visible in the run record
    rather than reconstructed later -- which it could not be, because nothing was
    stored and the diverging cohort had to be re-run under instrumentation to find
    out what ran away.
    """
    if not (self.tonic_hierarchy and self.tonic_session_level):
        return {}
    out: dict[str, float] = {}
    for n in _TONIC_COMPONENTS:
        for kind in ("tonic_sigma", "z_tonic"):
            if kind == "z_tonic" and f"z_{n}" in self._tonic_block_layout():
                continue                       # inside the tonic block, no own scale
            v = pyro.param(f"q_{kind}_{n}_scale").detach()
            out[f"{kind}_{n}_scale_max"] = float(v.max())
    out["at_bound"] = float(
        max(v for k, v in out.items() if k.endswith("_max"))
        >= 0.99 * _TONIC_SCALE_RANGE[1])
    return out

tonic_posterior

tonic_posterior()

Per-drug pharmacokinetics read off the fit, in constrained units.

Returns amplitude, elimination and absorption rates and the Bateman peak time for each drug -- the quantities a per-session tonic fit cannot produce.

Source code in src/photosvi/models/points/hierarchical.py
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
@torch.no_grad()
def tonic_posterior(self) -> dict[str, dict[str, float]]:
    """Per-drug pharmacokinetics read off the fit, in constrained units.

    Returns amplitude, elimination and absorption rates and the Bateman peak time
    for each drug -- the quantities a per-session tonic fit cannot produce.
    """
    if not self.tonic_hierarchy:
        return {}
    out = {}
    mom = {n: self._tonic_mu_moments(n)[0] for n in _TONIC_COMPONENTS}
    for d in range(self.n_drugs):
        a = float(mom["alpha"][d])
        r = float(mom["rho"][d])
        g = float(mom["gamma"][d])
        kd, kr = math.exp(r), math.exp(r) + math.exp(g)
        out[d] = {"peak": math.exp(a), "k_decay": kd, "k_rise": kr,
                  "peak_s": math.log(kr / kd) / (kr - kd)}
    return out

model

model(y, inj_t=None, tilt=None, obs_mask=None)

Joint p(y, z, s, a | Theta) for the cohort. y is [S, T].

inj_t is accepted so the signature matches SingleTraceModel.model; the injection bins are per-session state set at construction, and a value that disagrees with them is an error rather than a silent override.

tilt adds a linear term to the log joint for the linear-response correction, as a mapping from global site name to coefficient: {"mu_drug": [0, -1, 1]} tilts along the drug-2-minus-drug-1 contrast, which is the estimand this model reports. See _apply_tilt.

obs_mask selects which bins contribute to the likelihood. [S] or [S, 1] drops whole sessions, which is what a delete-one-cluster resampling estimate needs: the design, and therefore the identifiable variance components, is left exactly as it was. [S, T] or [T] drops individual bins, which is what the injection handling window needs -- see observed_bins, which also widens the mask by one bin under an AR(1) emission.

Either way it masks the OBSERVATION only, not the latents: a global poutine.mask would broadcast onto the scalar cohort parameters and break their log-probability shapes.

Source code in src/photosvi/models/points/hierarchical.py
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
def model(self, y: torch.Tensor, inj_t=None, tilt=None, obs_mask=None):
    """Joint p(y, z, s, a | Theta) for the cohort. `y` is [S, T].

    `inj_t` is accepted so the signature matches `SingleTraceModel.model`; the injection
    bins are per-session state set at construction, and a value that disagrees
    with them is an error rather than a silent override.

    `tilt` adds a linear term to the log joint for the linear-response correction,
    as a mapping from global site name to coefficient: `{"mu_drug": [0, -1, 1]}`
    tilts along the drug-2-minus-drug-1 contrast, which is the estimand this model
    reports. See `_apply_tilt`.

    `obs_mask` selects which bins contribute to the likelihood. `[S]` or `[S, 1]`
    drops whole sessions, which is what a delete-one-cluster resampling estimate
    needs: the design, and therefore the identifiable variance components, is left
    exactly as it was. `[S, T]` or `[T]` drops individual bins, which is what the
    injection handling window needs -- see `observed_bins`, which also widens the
    mask by one bin under an AR(1) emission.

    Either way it masks the OBSERVATION only, not the latents: a global
    `poutine.mask` would broadcast onto the scalar cohort parameters and break
    their log-probability shapes.
    """
    self._check_inj(inj_t)
    pyro.module("hpoints", self)
    S, T = y.shape
    if S != self.n_sessions:
        raise ValueError(f"y has {S} sequences but the model was built for {self.n_sessions}")
    device, dtype = y.device, y.dtype
    as_t = lambda v: torch.as_tensor(v, device=device, dtype=dtype)  # noqa: E731
    std_normal = dist.Normal(as_t(0.0), as_t(1.0))

    # ---- cohort level
    mu_b0 = pyro.sample("mu_b0", dist.Normal(
        as_t(self.beta0_anchor), as_t(self.mu_b0_prior_scale)))
    sigma_b0 = self._sample_log_scale("b0", guide=False, device=device, dtype=dtype)
    drug_plate = pyro.plate("drug", self.n_drugs, dim=-1)
    with drug_plate:
        mu_drug = pyro.sample("mu_drug", dist.Normal(
            as_t(0.0), as_t(self.mu_drug_prior_scale)))

    if tilt is not None:
        self._apply_tilt(tilt, {"mu_b0": mu_b0, "mu_drug": mu_drug})

    # ---- non-centred random effects, one block per active level
    with pyro.plate("animal", self.n_animals, dim=-1):
        z_b0 = pyro.sample("z_b0", std_normal)
    sigmas, zs = {}, {}
    for lvl in self.levels:
        sigmas[lvl] = self._sample_log_scale(lvl, guide=False, device=device,
                                             dtype=dtype)
        with pyro.plate(f"{lvl}_effect", self.level_size[lvl], dim=-1):
            zs[lvl] = pyro.sample(f"z_{lvl}", std_normal)

    b0_seq, bi_seq = self._session_coeffs(mu_b0, sigma_b0, z_b0, mu_drug, sigmas, zs)

    gate = self._gate(T, device=device, dtype=dtype)
    p = self._prior_event_prob(b0_seq, bi_seq, gate)          # [S, T]
    x_hat = self._tonic_sites(T, guide=False, device=device, dtype=dtype,
                              drug_plate=drug_plate)
    tau = as_t(self.tau)
    mu_a, sigma_a = self.phasic.mu_a, self.phasic.sigma_a
    if getattr(self.phasic, "mark_prior", None) is not None:
        pyro.factor("mark_prior", self.phasic.mark_prior_logp())

    seq_plate = pyro.plate("sequences", S, dim=-2)
    time_plate = pyro.plate("time", T, dim=-1)
    with seq_plate, time_plate:
        s_dist = dist.RelaxedBernoulli(temperature=tau, probs=p)
        s = pyro.sample("s", s_dist)
        a_dist = dist.LogNormal(mu_a, sigma_a)
        a = pyro.sample("a", a_dist)

    if self.mark_kl != "sampled":
        pyro.factor("a_sampled_logp_undo", -a_dist.log_prob(a).sum())
    if self.analytic_s_kl:
        pyro.factor("s_relaxed_logp_undo", -s_dist.log_prob(s).sum())

    mean = x_hat + self.phasic.convolve(s * a)
    # See SingleTraceModel.model: under a coloured emission the mean at the `y` site
    # is the conditional one, so the structural mean is recorded separately.
    pyro.deterministic("mean_struct", mean)
    with seq_plate, time_plate:
        em = self._emission_dist(mean, obs=y)
        if obs_mask is not None:
            em = em.mask(observed_bins(obs_mask, y.shape, y.device,
                                       len(self.emission.ar_coeffs)))
        pyro.sample("y", em, obs=y)

guide

guide(y, inj_t=None, tilt=None, obs_mask=None)

Mean-field guide: Normals on every latent, on their unconstrained axes.

tilt and obs_mask are accepted and ignored: both are terms of the log JOINT, not of q, and Pyro requires the two signatures to match.

Source code in src/photosvi/models/points/hierarchical.py
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
def guide(self, y: torch.Tensor, inj_t=None, tilt=None, obs_mask=None):
    """Mean-field guide: Normals on every latent, on their unconstrained axes.

    `tilt` and `obs_mask` are accepted and ignored: both are terms of the log
    JOINT, not of `q`, and Pyro requires the two signatures to match.
    """
    self._check_inj(inj_t)
    S, T = y.shape
    device, dtype = y.device, y.dtype
    tau = torch.as_tensor(self.tau, device=device, dtype=dtype)

    def free(name, loc_init, scale_init=0.1, shape=()):
        loc = pyro.param(f"q_{name}_loc",
                         torch.full(shape, float(loc_init), device=device, dtype=dtype))
        scale = pyro.param(f"q_{name}_scale",
                           torch.full(shape, float(scale_init), device=device, dtype=dtype),
                           constraint=dist.constraints.positive)
        return loc, scale

    fr = self.beta_guide.startswith("fullrank")
    if fr:
        # One correlated draw, unpacked onto the model's sites. Every coordinate
        # is unconstrained -- the scales because they are sampled through their
        # log -- so no transform and no Jacobian are involved. Including the
        # variance components matters because they correlate with mu_drug: a
        # larger between-animal spread means the cohort mean is less determined,
        # and a factorised q must call that dependence zero.
        n, where = self._block_layout()
        init_loc, init_diag = self._block_init(device, dtype)
        g_loc = pyro.param("q_global_loc", init_loc)
        g_tril = pyro.param("q_global_tril", torch.diag(init_diag),
                            constraint=dist.constraints.lower_cholesky)
        joint = pyro.sample("_global_joint",
                            dist.MultivariateNormal(g_loc, scale_tril=g_tril),
                            infer={"is_auxiliary": True})
        mu_b0 = pyro.sample("mu_b0", dist.Delta(joint[where["mu_b0"]][0]))
    else:
        joint = None
        mu_b0 = pyro.sample("mu_b0", dist.Normal(*free("mu_b0", self.beta0_anchor)))
    # Scales are sampled through their log, where the prior lives, so the guide
    # matches the model's axis and the block can include them untransformed.
    sigma_b0 = self._sample_log_scale(
        "b0", guide=True, device=device, dtype=dtype, joint=joint,
        index=(where["sigma_b0"].start if fr else None))
    drug_plate = pyro.plate("drug", self.n_drugs, dim=-1)
    if fr:
        with drug_plate:
            mu_drug = pyro.sample("mu_drug",
                                  dist.Delta(joint[where["mu_drug"]]))
    else:
        md_loc, md_scale = free("mu_drug", 0.0, 0.1, (self.n_drugs,))
        with drug_plate:
            mu_drug = pyro.sample("mu_drug", dist.Normal(md_loc, md_scale))

    # The non-centred effects join the block only under `fullrank_z`; under
    # `fullrank` they stay factorised, which is what the shipped results used.
    with pyro.plate("animal", self.n_animals, dim=-1):
        if "z_b0" in self._blocked_z():
            z_b0 = pyro.sample("z_b0", dist.Delta(joint[where["z_b0"]]))
        else:
            zb_loc, zb_scale = free("z_b0", 0.0, 0.5, (self.n_animals,))
            z_b0 = pyro.sample("z_b0", dist.Normal(zb_loc, zb_scale))

    sigmas, zs = {}, {}
    for lvl in self.levels:
        sigmas[lvl] = self._sample_log_scale(
            lvl, guide=True, device=device, dtype=dtype, joint=joint,
            index=(where[f"sigma_{lvl}"].start if fr else None))
        with pyro.plate(f"{lvl}_effect", self.level_size[lvl], dim=-1):
            if f"z_{lvl}" in self._blocked_z():
                zs[lvl] = pyro.sample(f"z_{lvl}",
                                      dist.Delta(joint[where[f"z_{lvl}"]]))
            else:
                zl, zsc = free(f"z_{lvl}", 0.0, 0.5, (self.level_size[lvl],))
                zs[lvl] = pyro.sample(f"z_{lvl}", dist.Normal(zl, zsc))

    # Every latent above is reparameterized, so the per-session coefficients they
    # imply carry a gradient to all levels. Use the SAMPLES, not the param medians:
    # the analytic event KL below is the only term that sees the betas, so
    # substituting a point value there would cut the hierarchy off from the data --
    # the variance components would then be estimated by their priors alone.
    b0_seq, bi_seq = self._session_coeffs(mu_b0, sigma_b0, z_b0, mu_drug, sigmas, zs)

    # The tonic latents must be sampled in the guide too, with the same site
    # names and plate structure as the model -- the curve itself is not used
    # here, only the sites.
    self._tonic_sites(T, guide=True, device=device, dtype=dtype,
                      drug_plate=drug_plate)

    # ---- events and marks: identical to the single-trace guide, per session.
    gate = self._gate(T, device=device, dtype=dtype)
    if self.couple_events:
        anchor = self._prior_event_prob(b0_seq, bi_seq, gate).clamp(1e-9, 1 - 1e-9).logit()
        zeros = torch.zeros(S, T, device=device, dtype=dtype)
        s_logits = self.event_guide(y, self.inj_t, prior_logits=zeros) + anchor
    else:
        b0_0 = torch.full((S,), self.beta0_anchor, device=device, dtype=dtype)
        p0 = self._prior_event_prob(b0_0, torch.zeros_like(b0_0), gate).detach()
        s_logits = self.event_guide(
            y, self.inj_t, prior_logits=p0.clamp(1e-6, 1 - 1e-6).logit())

    W = self.mark_window
    # Initialised at the NOISE SCALE, capped by the prior. Neither of the obvious
    # choices works in both regimes, and for the same reason: what matters is not
    # how the starting mark compares to the prior but how the SPURIOUS DRIVE it
    # creates compares to the noise. q(s_t) is small but not zero at the ~90% of
    # windows holding no event, so every one contributes q.E[a] from step one.
    # Zero puts E[a] at 1.0 whatever the units -- 1.7 sigma_y on simulated
    # cohorts, 82 on real dF/F. The prior puts it at 0.02 on real recordings,
    # which is right, and 6.0 (57 sigma_y) on simulated ones, where the phasic
    # component reached 10^6 by step 1000. The smaller of the two is what both
    # regimes want: every mark starts below the level at which it could disturb
    # the fit, and the data raises the ones that hold an event. See the same
    # comment in points.py for the measurements.
    # A tensor, [S, 1] when the marks or the noise are per session (2026-10-20), so
    # each session's q(a) starts at its own min(mu_a, log sigma_y).
    _mu = self.phasic.mu_a.detach().to(device=device, dtype=dtype)
    mu_a_init = (_mu if getattr(self.phasic, "q_a_init", "noise") == "prior" else
                 torch.minimum(_mu, torch.log(self.emission.sigma_y.detach()).to(
                     device=device, dtype=dtype)))
    mu_a_init = torch.broadcast_to(mu_a_init.reshape(-1, 1) if mu_a_init.dim() else mu_a_init,
                                   (S, 1))
    if W and W > 1:
        n_win = -(-T // W)
        a_loc = pyro.param(
            "q_a_loc", mu_a_init.expand(S, n_win).clone()
        ).repeat_interleave(W, dim=-1)[:, :T]
        # The SCALE stays deliberately diffuse and is NOT initialised at
        # sigma_a. A narrow q(a) is a confident claim, and at step zero the claim
        # is wrong wherever a window does hold an event -- the mark there is the
        # prior's, several units above the noise the loc starts at. Confident and
        # wrong together is the combination that kills the fit: measured on a
        # simulated cohort, loc at the noise scale with sigma_a's width failed
        # within 2000 steps, the same loc with a width of 0.5 survived, and the
        # old loc with either width survived. Neither axis does it alone.
        a_scale = pyro.param(
            "q_a_scale",
            _MARK_SCALE_INIT * torch.ones(S, n_win, device=device, dtype=dtype),
            constraint=dist.constraints.interval(0.0, _MARK_SCALE_MAX),
        ).repeat_interleave(W, dim=-1)[:, :T]
    else:
        a_loc = pyro.param(
            "q_a_loc", mu_a_init.expand(S, T).clone())
        a_scale = pyro.param(
            "q_a_scale", _MARK_SCALE_INIT * torch.ones(S, T, device=device, dtype=dtype),
            constraint=dist.constraints.interval(0.0, _MARK_SCALE_MAX))

    seq_plate = pyro.plate("sequences", S, dim=-2)
    time_plate = pyro.plate("time", T, dim=-1)
    with seq_plate, time_plate:
        q_dist = dist.RelaxedBernoulli(temperature=tau, logits=s_logits)
        s = pyro.sample("s", q_dist)
        qa_dist = dist.LogNormal(a_loc, a_scale)
        a_draw = pyro.sample("a", qa_dist)

    if self.mark_kl != "sampled":
        mk = SingleTraceModel._lognormal_kl(a_loc, a_scale, self.phasic.mu_a, self.phasic.sigma_a)
        if self.mark_kl == "gated":
            mk = torch.sigmoid(s_logits).clamp_min(self.mark_gate_floor) * mk
        pyro.factor("a_sampled_logq_undo", -qa_dist.log_prob(a_draw).sum(),
                    has_rsample=True)
        pyro.factor("a_mark_kl", mk.sum(), has_rsample=True)

    if self.analytic_s_kl:
        p_beta = self._prior_event_prob(b0_seq, bi_seq, gate)
        pyro.factor("s_relaxed_logq_undo", -q_dist.log_prob(s).sum(), has_rsample=True)
        pyro.factor("s_analytic_kl",
                    SingleTraceModel._bernoulli_kl(s_logits, p_beta).sum(), has_rsample=True)

drug_posterior

drug_posterior()

(loc, scale) of q(mu_drug[d]) for each drug -- the headline estimand.

Source code in src/photosvi/models/points/hierarchical.py
1235
1236
1237
1238
1239
1240
@torch.no_grad()
def drug_posterior(self) -> dict[int, tuple[float, float]]:
    """(loc, scale) of q(mu_drug[d]) for each drug -- the headline estimand."""
    loc, cov = self._global_moments()
    return {d: (float(loc[1 + d]), float(cov[1 + d, 1 + d].sqrt()))
            for d in range(self.n_drugs)}

tonic_alpha_contrast

tonic_alpha_contrast(d1=1, d2=0)

(loc, sd) of the log-height contrast alpha[d1] - alpha[d2] (see tonic_contrast).

Source code in src/photosvi/models/points/hierarchical.py
1283
1284
1285
1286
@torch.no_grad()
def tonic_alpha_contrast(self, d1: int = 1, d2: int = 0) -> tuple[float, float]:
    """(loc, sd) of the log-height contrast alpha[d1] - alpha[d2] (see tonic_contrast)."""
    return self.tonic_contrast(d1, d2, "alpha")

tonic_contrast

tonic_contrast(d1, d2, name='alpha')

(loc, sd) of the per-drug tonic mean name[d1] - [d2]; alpha is the log height.

Source code in src/photosvi/models/points/hierarchical.py
1301
1302
1303
1304
1305
1306
@torch.no_grad()
def tonic_contrast(self, d1: int, d2: int, name: str = "alpha") -> tuple[float, float]:
    """(loc, sd) of the per-drug tonic mean `name`[d1] - [d2]; alpha is the log height."""
    loc, cov = self._tonic_mu_moments(name)
    var = float(cov[d1, d1] + cov[d2, d2] - 2 * cov[d1, d2])
    return float(loc[d1] - loc[d2]), math.sqrt(max(var, 0.0))

drug_contrast

drug_contrast(d1, d2)

(loc, scale) of mu_drug[d1] - mu_drug[d2] under the mean-field posterior.

The two are independent in q, so the contrast's variance is the sum. This is the quantity the drug comparison reports, and unlike a two-stage difference of per-trace fits its interval carries the between-animal component. How wide it is depends on the design: with one drug per animal the comparison is between animals and sigma_animal sets the floor; when animals receive several drugs the animal effect cancels and the same recordings buy a tighter interval.

Source code in src/photosvi/models/points/hierarchical.py
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
def drug_contrast(self, d1: int, d2: int) -> tuple[float, float]:
    """(loc, scale) of mu_drug[d1] - mu_drug[d2] under the mean-field posterior.

    The two are independent in `q`, so the contrast's variance is the sum. This is
    the quantity the drug comparison reports, and unlike a two-stage difference of
    per-trace fits its interval carries the between-animal component. How wide it
    is depends on the design: with one drug per animal the comparison is between
    animals and `sigma_animal` sets the floor; when animals receive several drugs
    the animal effect cancels and the same recordings buy a tighter interval.
    """
    loc, cov = self._global_moments()
    i, j = 1 + d1, 1 + d2
    # Var(a - b) = Var(a) + Var(b) - 2 Cov(a, b). Under the mean-field guide the
    # covariance is zero by construction and this reduces to the sum; under the
    # full-rank block it does not, and ignoring it would misreport the very
    # quantity the block was added to get right.
    var = float(cov[i, i] + cov[j, j] - 2 * cov[i, j])
    return (float(loc[i] - loc[j]), math.sqrt(max(var, 0.0)))

session_beta_inj

session_beta_inj()

Posterior mean of beta_inj for each session, [S] -- the shrunk estimates.

Source code in src/photosvi/models/points/hierarchical.py
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
@torch.no_grad()
def session_beta_inj(self) -> torch.Tensor:
    """Posterior mean of beta_inj for each session, [S] -- the shrunk estimates."""
    bi = self._global_moments()[0][1:][self.drug]
    for lvl in self.levels:
        if lvl == "b0_session":        # acts on the baseline, not the effect
            continue
        sigma = self._scale_median(lvl)
        bi = bi + sigma * self._z_loc(f"z_{lvl}")[self._index_of(lvl)]
    return bi

animal_beta0

animal_beta0()

Posterior mean of the animal-level baseline log-rate, [A].

Source code in src/photosvi/models/points/hierarchical.py
1351
1352
1353
1354
1355
1356
@torch.no_grad()
def animal_beta0(self) -> torch.Tensor:
    """Posterior mean of the animal-level baseline log-rate, [A]."""
    return (self._global_moments()[0][0]
            + self._scale_median("b0")
            * self._z_loc("z_b0"))

session_beta0

session_beta0()

Posterior mean of the baseline log-rate actually used per session, [S].

The animal's level plus its day-to-day deviation, when the design supports estimating one.

Source code in src/photosvi/models/points/hierarchical.py
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
@torch.no_grad()
def session_beta0(self) -> torch.Tensor:
    """Posterior mean of the baseline log-rate actually used per session, [S].

    The animal's level plus its day-to-day deviation, when the design supports
    estimating one.
    """
    b0 = self.animal_beta0()[self.animal]
    if "b0_session" in self.levels:
        b0 = b0 + (self._scale_median("b0_session")
                   * self._z_loc("z_b0_session"))
    return b0

variance_components

variance_components()

Posterior median of each active variance component, on the log-rate axis.

Which component governs a drug contrast depends on the design, and getting this backwards cost this project a week. In a CROSSED design -- every animal receiving every drug -- sigma_animal cancels from the contrast: the animal effect enters mu_drug[a] and mu_drug[b] identically and subtracts out, exactly as it does in a paired t-test. What remains is sigma_cell, the animal x drug interaction, which is the spread the contrast is actually estimated against and the reason its interval does not shrink with the number of sessions.

In an UNCROSSED design -- each animal receiving one drug -- there is no pairing to exploit, nothing cancels, and sigma_animal governs the contrast directly. The real cohort is partially crossed and sits between the two, so neither component can be read as "the" one without checking design_summary.

This docstring previously named sigma_animal unconditionally, and variants of the guide were then ranked on how well they recovered it -- selecting, on a crossed design, for the one parameter that does not enter the estimand. It was corrected on 2026-09-14.

Source code in src/photosvi/models/points/hierarchical.py
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
@torch.no_grad()
def variance_components(self) -> dict[str, float]:
    """Posterior median of each active variance component, on the log-rate axis.

    **Which component governs a drug contrast depends on the design**, and
    getting this backwards cost this project a week. In a CROSSED design -- every
    animal receiving every drug -- `sigma_animal` *cancels from the contrast*:
    the animal effect enters `mu_drug[a]` and `mu_drug[b]` identically and
    subtracts out, exactly as it does in a paired t-test. What remains is
    `sigma_cell`, the animal x drug interaction, which is the spread the contrast
    is actually estimated against and the reason its interval does not shrink
    with the number of sessions.

    In an UNCROSSED design -- each animal receiving one drug -- there is no
    pairing to exploit, nothing cancels, and `sigma_animal` governs the contrast
    directly. The real cohort is partially crossed and sits between the two, so
    neither component can be read as "the" one without checking `design_summary`.

    This docstring previously named `sigma_animal` unconditionally, and variants
    of the guide were then ranked on how well they recovered it -- selecting, on
    a crossed design, for the one parameter that does not enter the estimand. It was
    corrected on 2026-09-14.
    """
    return {f"sigma_{lvl}": self._scale_median(lvl)
            for lvl in ("b0", *self.levels)}

event_posterior

event_posterior(y)

Per-bin event probabilities q(s_t = 1), [S, T].

Source code in src/photosvi/models/points/hierarchical.py
1408
1409
1410
1411
1412
1413
@torch.no_grad()
def event_posterior(self, y: torch.Tensor) -> torch.Tensor:
    """Per-bin event probabilities q(s_t = 1), [S, T]."""
    if hasattr(self.event_guide, "fitted_logits"):
        return torch.sigmoid(self.event_guide.fitted_logits(y))
    return torch.sigmoid(pyro.param("q_s_logits").detach())

photosvi.models.points.PhasicEventProcess

PhasicEventProcess(kernel, *, beta0=-2.0, beta_inj=0.0, history=None, mu_a=0.0, sigma_a=0.5, dt=1.0 / 25.0)

Bases: Module

Discrete-time marked point process driving phasic fluorescence c_t.

Holds the conditional-intensity GLM parameters (beta0, beta_inj, history FIR w), the log-normal mark parameters (mu_a, sigma_a), and a fixed causal kernel h registered as a buffer (no grad, follows the module's device).

beta0 / beta_inj are buffers, not nn.Parameters: under SingleTraceModel SVI they are latent globals (Normal prior + mean-field posterior), so they are not point-optimized here. The buffer carries the value the generative .sample() / log_intensity path uses, and serves as the default prior-mean anchor SingleTraceModel reads. The marks (mu_a, sigma_a) and FIR w stay MAP nn.Parameters.

Parameters:

Name Type Description Default
kernel 1-D tensor h, the fixed transient shape (e.g. from

bi_exponential_kernel).

required
beta0 baseline log-rate (generative value / prior-mean anchor).
-2.0
beta_inj additive post-injection log-rate shift (anchor).
0.0
history optional FIR coefficients w_1..w_L over own past events; w_l < 0

is refractory, w_l > 0 self-exciting. None / [] disables history.

None
mu_a log-normal mark location and (positive) scale; sigma_a is

stored in log space so it stays positive.

0.0
sigma_a log-normal mark location and (positive) scale; sigma_a is

stored in log space so it stays positive.

0.0
dt bin width in seconds.
1.0 / 25.0
Source code in src/photosvi/models/points/events.py
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
def __init__(
    self,
    kernel: torch.Tensor,
    *,
    beta0: float = -2.0,
    beta_inj: float = 0.0,
    history: list[float] | torch.Tensor | None = None,
    mu_a: float = 0.0,
    sigma_a: float = 0.5,
    dt: float = 1.0 / 25.0,
):
    super().__init__()
    self.dt = float(dt)
    self.register_buffer("kernel", torch.as_tensor(kernel, dtype=torch.float32))

    # latent under SingleTraceModel SVI -> buffers, not learnable params (see docstring)
    self.register_buffer("beta0", torch.tensor(float(beta0)))
    self.register_buffer("beta_inj", torch.tensor(float(beta_inj)))

    w = torch.as_tensor(history if history is not None else [], dtype=torch.float32)
    self.history_len = int(w.numel())
    self.w = nn.Parameter(w) if self.history_len > 0 else None

    self.mu_a = nn.Parameter(torch.tensor(float(mu_a)))
    self.log_sigma_a = nn.Parameter(torch.tensor(float(sigma_a)).log())
    # Prior on the mark distribution, None for none (the behaviour before
    # 2026-10-09). With no prior mu_a and sigma_a are point estimates the optimizer
    # moves freely, and at every SNR tested it trades amplitude for rate: mu_a falls
    # 0.6-1.2 below its simulated value and beta0 rises 0.7-2 above it, since the
    # data fix rate x amplitude^2 far better than either. `set_mark_prior` anchors
    # them on an independent estimate (peak prominences) with a stated width.
    self.mark_prior: tuple[float, float, float, float] | None = None
    # Where q(a)'s location starts: "noise" (min(mu_a, log sigma_y), the shipped
    # rule) or "prior" (mu_a).
    self.q_a_init = "noise"

set_mark_prior

set_mark_prior(mu, sigma, *, mu_sd=0.2, log_sigma_sd=0.3)

mu_a ~ N(mu, mu_sd^2), log sigma_a ~ N(log sigma, log_sigma_sd^2); starts there.

Source code in src/photosvi/models/points/events.py
342
343
344
345
346
347
348
def set_mark_prior(self, mu: float, sigma: float, *, mu_sd: float = 0.2,
                   log_sigma_sd: float = 0.3) -> None:
    """mu_a ~ N(mu, mu_sd^2), log sigma_a ~ N(log sigma, log_sigma_sd^2); starts there."""
    self.mark_prior = (float(mu), float(mu_sd), math.log(float(sigma)), float(log_sigma_sd))
    with torch.no_grad():
        self.mu_a.fill_(float(mu))
        self.log_sigma_a.fill_(math.log(float(sigma)))

mark_prior_logp

mark_prior_logp()

Log density of the mark prior at the current (mu_a, log sigma_a).

Source code in src/photosvi/models/points/events.py
350
351
352
353
354
def mark_prior_logp(self) -> torch.Tensor:
    """Log density of the mark prior at the current (mu_a, log sigma_a)."""
    m, ms, ls, lss = self.mark_prior
    return (-0.5 * ((self.mu_a - m) / ms) ** 2
            - 0.5 * ((self.log_sigma_a - ls) / lss) ** 2)

log_intensity

log_intensity(s, post_injection)

log lambda_t for a given event tensor.

s is [B, T] in {0, 1}; post_injection is the 1[t >= t_inj] mask, broadcastable to [B, T]. Returns log lambda of shape [B, T]. The history term sum_l w_l s_{t-l} is built by shifting s right by each lag l (the events at t-l), so the current bin never feeds its own rate.

Source code in src/photosvi/models/points/events.py
361
362
363
364
365
366
367
368
369
370
371
372
def log_intensity(self, s: torch.Tensor, post_injection: torch.Tensor) -> torch.Tensor:
    """log lambda_t for a given event tensor.

    `s` is [B, T] in {0, 1}; `post_injection` is the 1[t >= t_inj] mask,
    broadcastable to [B, T]. Returns log lambda of shape [B, T]. The history
    term sum_l w_l s_{t-l} is built by shifting `s` right by each lag l
    (the events at t-l), so the current bin never feeds its own rate.
    """
    log_lam = self.beta0 + self.beta_inj * post_injection
    if self.history_len > 0:
        log_lam = log_lam + self._history_term(s)
    return log_lam.expand_as(s) if log_lam.dim() == 0 else log_lam

event_logprob

event_logprob(s, post_injection)

Per-sequence timing log-likelihood log p(s_{1:T} | theta).

sum_t [ s_t log p_t + (1 - s_t) log(1 - p_t) ],
log(1 - p_t) = -lambda_t * dt,  p_t = 1 - exp(-lambda_t * dt).

Uses expm1 for the occupied/empty split so both terms stay stable at small lambda*dt. Returns shape [B] (summed over time).

Source code in src/photosvi/models/points/events.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
def event_logprob(self, s: torch.Tensor, post_injection: torch.Tensor) -> torch.Tensor:
    """Per-sequence timing log-likelihood log p(s_{1:T} | theta).

        sum_t [ s_t log p_t + (1 - s_t) log(1 - p_t) ],
        log(1 - p_t) = -lambda_t * dt,  p_t = 1 - exp(-lambda_t * dt).

    Uses expm1 for the occupied/empty split so both terms stay stable at
    small lambda*dt. Returns shape [B] (summed over time).
    """
    log_lam = self.log_intensity(s, post_injection)
    lam_dt = log_lam.exp() * self.dt
    log_1mp = -lam_dt                  # log(1 - p_t) = -lambda_t dt
    p = -torch.expm1(-lam_dt)          # 1 - exp(-lambda_t dt), stable
    log_p = p.clamp_min(1e-12).log()
    ll = s * log_p + (1.0 - s) * log_1mp
    return ll.sum(dim=-1)

convolve

convolve(u)

c_t = sum_{k=0}^{M-1} h_k u_{t-k}, the causal FIR convolution.

u is the drive [B, T]; returns c [B, T]. Implemented as a conv1d with the kernel flipped and the input left-padded by M-1 so the output is causal (each c_t depends only on u at t and earlier).

Source code in src/photosvi/models/points/events.py
402
403
404
405
406
407
408
409
410
411
412
413
def convolve(self, u: torch.Tensor) -> torch.Tensor:
    """c_t = sum_{k=0}^{M-1} h_k u_{t-k}, the causal FIR convolution.

    `u` is the drive [B, T]; returns c [B, T]. Implemented as a conv1d with
    the kernel flipped and the input left-padded by M-1 so the output is
    causal (each c_t depends only on u at t and earlier).
    """
    M = self.kernel.numel()
    weight = self.kernel.flip(0).view(1, 1, M)
    u_in = F.pad(u, (M - 1, 0)).unsqueeze(1)
    c = F.conv1d(u_in, weight).squeeze(1)
    return c

sample

sample(T, inj_t, batch=1, generator=None)

Forward-generate the phasic block.

Walks t = 0..T-1 sampling s_t ~ Bernoulli(p_t) with the rate built from the events drawn so far (history is sequential), then draws all marks a_t ~ LogNormal at once (marks are independent of timing), forms the drive u_t = s_t a_t, and convolves with h. Returns a dict with s, a, u, c, each [batch, T].

Source code in src/photosvi/models/points/events.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
@torch.no_grad()
# Forward generative process.
def sample(
    self,
    T: int,
    inj_t: int,
    batch: int = 1,
    generator: torch.Generator | None = None,
) -> dict[str, torch.Tensor]:
    """Forward-generate the phasic block.

    Walks t = 0..T-1 sampling s_t ~ Bernoulli(p_t) with the rate built from
    the events drawn so far (history is sequential), then draws all marks
    a_t ~ LogNormal at once (marks are independent of timing), forms the
    drive u_t = s_t a_t, and convolves with h. Returns a dict with `s`, `a`,
    `u`, `c`, each [batch, T].
    """
    device = self.kernel.device
    s = torch.zeros(batch, T, device=device) # event indicator to be filled
    post = (torch.arange(T, device=device) >= inj_t).float() # Sets 1 at and after the injection time

    for t in range(T):
        # Building conditional intensity
        log_lam = self.beta0 + self.beta_inj * post[t] # Indicator for post-injection time
        if self.history_len > 0:
            lo = max(0, t - self.history_len)
            past = s[:, lo:t]  # columns oldest -> newest (lag L .. lag 1)
            if past.shape[1] > 0:
                w_slice = self.w[: past.shape[1]].flip(0)  # align newest -> w_1
                log_lam = log_lam + (past * w_slice).sum(-1)
        lam_dt = log_lam.exp() * self.dt
        p = -torch.expm1(-lam_dt)  # 1 - exp(-lambda_t dt)
        s[:, t] = torch.bernoulli(p.expand(batch), generator=generator)

    eps = torch.randn(batch, T, generator=generator, device=device)
    a = (self.mu_a + self.sigma_a * eps).exp()  # LogNormal marks
    u = s * a                                    # drive
    c = self.convolve(u)                         # phasic fluorescence
    return {"s": s, "a": a, "u": u, "c": c}

photosvi.models.points.TonicBaseline

TonicBaseline(*, b=0.0, peak=1.0, k_rise=0.01, k_decay=0.002, drift=0.0, dt=1.0 / 25.0)

Bases: Module

Deterministic hierarchical-Bateman tonic baseline x_hat(t).

Holds a single animal's tonic parameters in the unconstrained space psi = (b, alpha, rho, gamma, d): the baseline level b and drift d are free reals, while the amplitude A and the rate constants k_decay < k_rise come from the reparameterization so positivity and the ordering are automatic and the sign/swap degeneracy is gone. The constrained (A, k_decay, k_rise) are exposed as read-only properties.

Parameters are given in the constrained space at construction (the natural units) and stored as their unconstrained transforms, mirroring how PhasicEventProcess stores sigma_a in log space.

Parameters:

Name Type Description Default
b baseline level (pre-injection ambient tonic; ~0 on a z-scored trace).
0.0
peak height of the Bateman bump in the units of the trace, must be > 0

(peak = 0 is the saline-like no-response case; pass a small positive value to approximate it). NOT the textbook amplitude A, which is a coordinate the data do not identify -- see the module docstring. A is available as a derived read-only property for anyone who wants it.

1.0
k_rise absorption / elimination rate constants (s^-1), must

satisfy k_rise > k_decay > 0. Both slow (injection timescale) -- this is the timescale separation B1 that keeps the tonic identifiable against the fast phasic kernel.

0.01
k_decay absorption / elimination rate constants (s^-1), must

satisfy k_rise > k_decay > 0. Both slow (injection timescale) -- this is the timescale separation B1 that keeps the tonic identifiable against the fast phasic kernel.

0.01
drift linear drift slope, PER HOUR, a first-order photobleaching / baseline

correction; typically small and negative. Per hour and not per second so that its gradient is on the same scale as the rest of the model -- again, see the module docstring.

0.0
dt bin width in seconds.
1.0 / 25.0
Source code in src/photosvi/models/points/tonic.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def __init__(
    self,
    *,
    b: float = 0.0,
    peak: float = 1.0,
    k_rise: float = 0.01,
    k_decay: float = 0.002,
    drift: float = 0.0,
    dt: float = 1.0 / 25.0,
):
    super().__init__()
    if peak <= 0:
        raise ValueError(
            f"peak must be > 0 (got {peak}); peak=exp(alpha) is positive by construction"
        )
    if not (k_rise > k_decay > 0):
        raise ValueError(
            f"need k_rise > k_decay > 0 (got k_rise={k_rise}, k_decay={k_decay}); "
            "absorption is faster than elimination (Bateman ordering)"
        )
    self.dt = float(dt)

    # Unconstrained psi: peak=exp(alpha), k_decay=exp(rho),
    # k_rise=exp(rho)+exp(gamma) so the gap exp(gamma)>0 enforces the order.
    self.b = nn.Parameter(torch.tensor(float(b)))
    self.alpha = nn.Parameter(torch.tensor(math.log(peak)))
    self.rho = nn.Parameter(torch.tensor(math.log(k_decay)))
    self.gamma = nn.Parameter(torch.tensor(math.log(k_rise - k_decay)))
    self.drift = nn.Parameter(torch.tensor(float(drift)))

peak property

peak

Height of the tonic bump, peak = exp(alpha) > 0, in the trace's units.

A property

A

The textbook Bateman amplitude this fit corresponds to. Derived, not stored.

Kept because it is diagnostic: A is the quantity the recording does not identify, so an ordinary peak alongside an enormous A says the rates have drifted together and the fit is sitting on the flat direction.

k_decay property

k_decay

Elimination rate k_decay = exp(rho) > 0.

k_rise property

k_rise

Absorption rate k_rise = exp(rho) + exp(gamma) > k_decay.

peak_time property

peak_time

Bateman peak time t_max = ln(k_rise/k_decay)/(k_rise - k_decay).

Seconds after injection at which the bump (drift aside) is maximal.

baseline

baseline(T, inj_t)

x_hat(t) over t = 0..T-1 for an injection at bin inj_t.

Returns a length-T tensor: flat at b before injection, then the injection-gated Bateman bump plus linear drift. The post-injection clock tau is clamped at 0 so the masked-off pre-injection region carries no spurious exp(-k*negative) blow-up. Shape [T]; broadcasts against a phasic c of shape [B, T] when forming the additive mean x_hat + c.

Source code in src/photosvi/models/points/tonic.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def baseline(self, T: int, inj_t: int) -> torch.Tensor:
    """x_hat(t) over t = 0..T-1 for an injection at bin `inj_t`.

    Returns a length-T tensor: flat at `b` before injection, then the
    injection-gated Bateman bump plus linear drift. The post-injection clock
    tau is clamped at 0 so the masked-off pre-injection region carries no
    spurious exp(-k*negative) blow-up. Shape [T]; broadcasts against a
    phasic c of shape [B, T] when forming the additive mean x_hat + c.
    """
    t = torch.arange(T, device=self.b.device, dtype=self.b.dtype)
    post = (t >= inj_t).to(self.b.dtype)                 # 1[t >= t_inj]
    tau = (t - inj_t).clamp_min(0).to(self.b.dtype) * self.dt  # post-inj clock, >=0
    bump = self.peak * bateman_shape(tau, self.k_decay, self.k_rise)
    return self.b + post * (bump + self.drift * tau / _DRIFT_SECONDS)

forward

forward(T, inj_t)

Alias for baseline so the module is callable.

Source code in src/photosvi/models/points/tonic.py
238
239
240
def forward(self, T: int, inj_t: int) -> torch.Tensor:
    """Alias for `baseline` so the module is callable."""
    return self.baseline(T, inj_t)

photosvi.models.points.BatchedTonicBaseline

BatchedTonicBaseline(*, n_seq, b=0.0, peak=1.0, k_rise=0.01, k_decay=0.002, drift=0.0, dt=1.0 / 25.0)

Bases: Module

One Bateman baseline per sequence, with per-sequence injection bins.

TonicBaseline holds a single animal's five scalars and takes one injection bin for the whole batch. A cohort is neither: animals differ in ambient tone, drugs differ in pharmacokinetics, and sessions are injected at different times. This class carries the same unconstrained psi = (b, alpha, rho, gamma, d) with a leading sequence dimension, and baseline takes inj_t as a length-S vector.

The parameters stay MAP point estimates, exactly as in the single-trace model. The hierarchy in HierarchicalModel is over the rate coefficients, which are the estimand; pooling the tonic as well would be defensible but adds five more variance components to a model whose identifiability rests on the timescale separation between tonic and phasic, and none of them is the quantity anyone reports. Left as a documented extension rather than a silent choice.

Parameters are given in the constrained space, each as a length-S sequence (or a scalar, broadcast to all S).

Source code in src/photosvi/models/points/tonic.py
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
def __init__(
    self,
    *,
    n_seq: int,
    b=0.0,
    peak=1.0,
    k_rise=0.01,
    k_decay=0.002,
    drift=0.0,
    dt: float = 1.0 / 25.0,
):
    super().__init__()
    if n_seq < 1:
        raise ValueError(f"n_seq must be >= 1 (got {n_seq})")

    def vec(x, name):
        t = torch.as_tensor(x, dtype=torch.get_default_dtype()).reshape(-1)
        if t.numel() == 1:
            t = t.expand(n_seq).clone()
        if t.numel() != n_seq:
            raise ValueError(f"{name} must be a scalar or length {n_seq} (got {t.numel()})")
        return t

    b_, A_, kr_, kd_, d_ = (vec(x, n) for x, n in
                            ((b, "b"), (peak, "peak"), (k_rise, "k_rise"),
                             (k_decay, "k_decay"), (drift, "drift")))
    if (A_ <= 0).any():
        raise ValueError(
            "every peak must be > 0; peak = exp(alpha) is positive by construction"
        )
    if not ((kr_ > kd_) & (kd_ > 0)).all():
        raise ValueError(
            "every sequence needs k_rise > k_decay > 0 (Bateman ordering: absorption "
            "faster than elimination)"
        )
    self.dt = float(dt)
    self.n_seq = int(n_seq)
    self.b = nn.Parameter(b_)
    self.alpha = nn.Parameter(A_.log())
    self.rho = nn.Parameter(kd_.log())
    self.gamma = nn.Parameter((kr_ - kd_).log())
    self.drift = nn.Parameter(d_)

peak property

peak

Bump peak heights = exp(alpha) > 0, [S], in the traces' units.

A property

A

The textbook Bateman amplitudes these fits correspond to, [S]. Derived.

Diagnostic only, as on TonicBaseline: an ordinary peak beside an enormous A is a session whose rates have drifted together.

k_decay property

k_decay

Elimination rates k_decay = exp(rho) > 0, [S].

k_rise property

k_rise

Absorption rates k_rise = exp(rho) + exp(gamma) > k_decay, [S].

baseline_from

baseline_from(b, alpha, rho, gamma, drift, T, inj_t)

x_hat from given unconstrained parameters, [S, T].

The same curve as baseline, but driven by tensors the caller supplies instead of this module's own nn.Parameters. That is what lets the hierarchical model put the pharmacokinetics under a prior: the tonic block stays the place the Bateman curve is defined, and the model passes in values sampled from the drug-level hierarchy rather than re-deriving the algebra.

Each of b, alpha, rho, gamma, drift is [S] on the unconstrained axis, with the same reparameterization the module uses: peak = exp(alpha), k_decay = exp(rho), k_rise = exp(rho) + exp(gamma), so positivity and the Bateman ordering hold for any real input and no constraint is needed on the prior.

Source code in src/photosvi/models/points/tonic.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
def baseline_from(self, b, alpha, rho, gamma, drift, T: int, inj_t) -> torch.Tensor:
    """x_hat from *given* unconstrained parameters, [S, T].

    The same curve as `baseline`, but driven by tensors the caller supplies
    instead of this module's own `nn.Parameter`s. That is what lets the
    hierarchical model put the pharmacokinetics under a prior: the tonic block
    stays the place the Bateman curve is defined, and the model passes in values
    sampled from the drug-level hierarchy rather than re-deriving the algebra.

    Each of `b, alpha, rho, gamma, drift` is [S] on the unconstrained axis, with
    the same reparameterization the module uses: peak = exp(alpha),
    k_decay = exp(rho), k_rise = exp(rho) + exp(gamma), so positivity and the
    Bateman ordering hold for any real input and no constraint is needed on the
    prior.
    """
    post, tau = self._clock(T, inj_t)
    peak = _bounded_exp(alpha, *_PEAK_RANGE).unsqueeze(-1)
    kd = _bounded_exp(rho, *_K_RANGE).unsqueeze(-1)
    kr = kd + _bounded_exp(gamma, *_K_RANGE).unsqueeze(-1)
    bump = peak * bateman_shape(tau, kd, kr)
    return b.unsqueeze(-1) + post * (
        bump + drift.unsqueeze(-1) * tau / _DRIFT_SECONDS)

baseline

baseline(T, inj_t)

x_hat over t = 0..T-1 for per-sequence injection bins. Returns [S, T].

inj_t is a length-S integer tensor (a scalar is broadcast). The post-injection clock is clamped at 0 per sequence so the pre-injection region carries no spurious exp(-k * negative).

Source code in src/photosvi/models/points/tonic.py
525
526
527
528
529
530
531
532
533
def baseline(self, T: int, inj_t: torch.Tensor) -> torch.Tensor:
    """x_hat over t = 0..T-1 for per-sequence injection bins. Returns [S, T].

    `inj_t` is a length-S integer tensor (a scalar is broadcast). The
    post-injection clock is clamped at 0 per sequence so the pre-injection region
    carries no spurious exp(-k * negative).
    """
    return self.baseline_from(self.b, self.alpha, self.rho, self.gamma,
                              self.drift, T, inj_t)

forward

forward(T, inj_t)

Alias for baseline so the module is callable.

Source code in src/photosvi/models/points/tonic.py
535
536
537
def forward(self, T: int, inj_t: torch.Tensor) -> torch.Tensor:
    """Alias for `baseline` so the module is callable."""
    return self.baseline(T, inj_t)

photosvi.models.points.AdditiveEmission

AdditiveEmission(*, sigma_y=0.1, nu=None, ar_rho=0.0, ar_coeffs=None)

Bases: Module

Additive-mean emission y_t ~ Normal / StudentT about m_t = x_hat + c.

Holds the homoscedastic residual scale sigma_y (stored in log space so it stays positive, mirroring PhasicEventProcess's log_sigma_a) and, for the robust variant, the Student-t degrees of freedom nu (also log-stored). The node carries no carrier of its own: callers pass the additive mean m = x_hat + c and the observation y, both broadcastable to [B, T].

Parameters:

Name Type Description Default
sigma_y residual standard deviation, must be > 0. Stored as log_sigma_y.

MAP-optimized by default; SingleTraceModel can instead treat it as a sampled latent under a narrow data-anchored prior (see estimate_log_noise_scale and SingleTraceModel(sigma_y_prior_loc=...)), which freezes this param.

0.1
ar_rho lag-one correlation of the residuals. Zero, the default, is the

independent emission this class had until 2026-09-30 and reproduces every earlier result exactly. A positive value makes the residual an AR(1) process:

y_t = m_t + e_t,   e_t = rho e_{t-1} + sqrt(1 - rho^2) sigma_y eps_t

so the marginal scale stays sigma_y and only the correlation changes. It exists because real recordings do not have white residuals: on the raw .doric files the first differences of the trace correlate at +0.8 where white noise gives -0.5, and the effective sample size of a pre-injection window is about a tenth of its nominal length. An independent emission counts 15,000 observations where there are the information of 1,400, and the direction of that error is over-confidence.

It also replaces, rather than complements, a slow component added to the mean: y = m + AR(1) and y = m + OU + white describe the same distribution, and carrying both would be modelling one mechanism twice. Keeping it in the emission rather than the mean matters for what the fit does with it -- noise is not something the model tries to explain with events.

0.0
nu Student-t degrees of freedom. None selects the Gaussian emission;

a positive value selects the robust Student-t with that nu. Stored as log_nu when present. Small nu (3-7) is heavy-tailed; large nu approaches the Gaussian.

None
Source code in src/photosvi/models/points/emission.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def __init__(self, *, sigma_y=0.1, nu: float | None = None,
             ar_rho: float = 0.0, ar_coeffs=None):
    super().__init__()
    # `sigma_y` is one scale for every sequence, or a sequence of them -- one per
    # session of a cohort, broadcast over its bins (2026-10-20). A float keeps the
    # scalar parameter every earlier fit used.
    sig = torch.as_tensor(sigma_y, dtype=torch.float32)
    if sig.dim() > 1 or not bool((sig > 0).all()):
        raise ValueError(
            f"sigma_y must be > 0 (got {sigma_y}); it is stored as log_sigma_y"
        )
    if ar_coeffs is not None and ar_rho:
        raise ValueError("give ar_rho or ar_coeffs, not both")
    phi = tuple(float(v) for v in (ar_coeffs if ar_coeffs is not None else
                                   ((ar_rho,) if ar_rho else ())))
    if phi and not _ar_is_stationary(phi):
        raise ValueError(
            f"AR coefficients {phi} are not stationary: a root of "
            f"1 - sum phi_k z^-k lies on or inside the unit circle, so the process "
            f"has no marginal variance to scale to sigma_y"
        )
    self.log_sigma_y = nn.Parameter(sig.log())
    self.ar_coeffs = phi
    # kept as the AR(1) name it has been used under everywhere; for a longer AR it
    # is the leading coefficient and NOT the lag-one correlation, so read
    # `ar_order` when what you mean is "is this coloured at all"
    self.ar_rho = phi[0] if len(phi) == 1 else 0.0

    if nu is None:
        self.log_nu = None
    else:
        if nu <= 0:
            raise ValueError(f"nu must be > 0 (got {nu}); Student-t needs positive dof")
        self.log_nu = nn.Parameter(torch.tensor(float(nu)).log())

sigma_y property

sigma_y

Residual scale sigma_y = exp(log_sigma_y) > 0; [S, 1] when per sequence.

per_sequence property

per_sequence

True iff each sequence has its own sigma_y.

nu property

nu

Student-t dof nu = exp(log_nu) > 0, or None in Gaussian mode.

robust property

robust

True iff this is the Student-t (heavy-tailed) emission.

log_prob

log_prob(y, mean)

Emission block of the complete-data log-likelihood, summed over t.

sum_t log p(y_t | m_t),   m_t = x_hat(t) + c_t,

with p the Gaussian or, robustly, the Student-t marginal. y and mean are broadcastable to [B, T]; returns shape [B] (the per-sequence emission log-likelihood, matching the shape of PhasicEventProcess.event_logprob so the two blocks add directly).

Source code in src/photosvi/models/points/emission.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def log_prob(self, y: torch.Tensor, mean: torch.Tensor) -> torch.Tensor:
    """Emission block of the complete-data log-likelihood, summed over t.

        sum_t log p(y_t | m_t),   m_t = x_hat(t) + c_t,

    with p the Gaussian or, robustly, the Student-t marginal. `y` and
    `mean` are broadcastable to [B, T]; returns shape [B]
    (the per-sequence emission log-likelihood, matching the shape of
    PhasicEventProcess.event_logprob so the two blocks add directly).
    """
    if not self.ar_coeffs:
        return self._dist(mean).log_prob(y).sum(dim=-1)
    # AR(p): factorise into conditionals on the observed past. No latent is
    # introduced and the cost per step is unchanged -- the conditional mean just
    # carries the previous residuals. See `ar_conditional`.
    cm, sd = ar_conditional(y, mean, self.sigma_y, self.ar_coeffs)
    return self._dist_at(cm, sd).log_prob(y).sum(dim=-1)

residual

residual(y, mean)

Partial residual r_t = y_t - m_t -- the GAM diagnostic.

Source code in src/photosvi/models/points/emission.py
265
266
267
def residual(self, y: torch.Tensor, mean: torch.Tensor) -> torch.Tensor:
    """Partial residual r_t = y_t - m_t -- the GAM diagnostic."""
    return y - mean

sample

sample(mean, generator=None)

Draw an observed trace y given the additive mean.

Gaussian mode: y = m + sigma_y * eps, eps ~ N(0, 1). Robust mode: the scale mixture -- draw a per-bin precision w_t ~ Gamma(nu/2, nu/2), then y_t ~ N(m_t, sigma_y^2 / w_t); marginalizing w reproduces the StudentT. Returns a dict with y (shape of mean) and w (the auxiliary precisions, or None in Gaussian mode).

generator seeds the Gaussian innovation eps for reproducibility; the Gamma precision draw uses the global RNG (torch.distributions.Gamma takes no generator), so seed with torch.manual_seed for a deterministic robust draw.

Source code in src/photosvi/models/points/emission.py
270
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
@torch.no_grad()
def sample(
    self,
    mean: torch.Tensor,
    generator: torch.Generator | None = None,
) -> dict[str, torch.Tensor]:
    """Draw an observed trace y given the additive mean.

    Gaussian mode: y = m + sigma_y * eps, eps ~ N(0, 1).
    Robust mode: the scale mixture -- draw a per-bin precision
    w_t ~ Gamma(nu/2, nu/2), then y_t ~ N(m_t, sigma_y^2 / w_t); marginalizing
    w reproduces the StudentT. Returns a dict with `y` (shape of
    `mean`) and `w` (the auxiliary precisions, or None in Gaussian mode).

    `generator` seeds the Gaussian innovation eps for reproducibility; the
    Gamma precision draw uses the global RNG (torch.distributions.Gamma takes
    no generator), so seed with torch.manual_seed for a deterministic robust
    draw.
    """
    eps = torch.randn(mean.shape, generator=generator, device=mean.device, dtype=mean.dtype)
    if self.ar_coeffs:
        # The same recursion the density scores, so a trace drawn here is a trace
        # the log_prob above rates highly. lfilter rather than a Python loop:
        # 60000 steps per sequence is a minute of interpreter time otherwise.
        import numpy as np  # noqa: PLC0415
        from scipy.signal import lfilter  # noqa: PLC0415
        if self.log_nu is not None:
            raise NotImplementedError(
                "a coloured emission with the Student-t is not defined here: the "
                "scale mixture and the AR recursion interact and nobody has "
                "decided how")
        phi = np.asarray(self.ar_coeffs, float)
        g = ar_autocovariance(self.ar_coeffs, len(phi) + 1)
        innov = float(g[0] - np.dot(phi, g[1:len(phi) + 1])) ** 0.5
        sig = self.sigma_y.detach().cpu().numpy()   # scalar, or [S, 1] per sequence
        e = eps.detach().cpu().numpy() * sig
        # burn in past the transient rather than trying to draw the first p bins
        # from their joint: 200 time constants of the slowest pole is far cheaper
        # than getting a p-variate stationary draw right, and is exact to
        # machine precision by the time it reaches bin 0.
        burn = 200 * len(phi) + int(
            10 / max(1e-9, -np.log(max(np.abs(np.roots(
                np.concatenate([[1.0], -phi]))))))
        )
        burn = min(max(burn, 100), 20000)
        pad = np.random.default_rng(0).standard_normal(e.shape[:-1] + (burn,)) * sig
        full = lfilter([innov], np.concatenate([[1.0], -phi]),
                       np.concatenate([pad, e], axis=-1), axis=-1)
        noise = torch.as_tensor(full[..., burn:], device=mean.device, dtype=mean.dtype)
        return {"y": mean + noise, "w": None}
    if self.log_nu is None:
        return {"y": mean + self.sigma_y * eps, "w": None}
    half_nu = 0.5 * self.nu
    w = Gamma(half_nu, half_nu).sample(mean.shape).to(device=mean.device, dtype=mean.dtype)
    y = mean + (self.sigma_y / w.sqrt()) * eps
    return {"y": y, "w": w}

Event guides

The variational family over the events is pluggable: each block returns per-bin logits and swapping one for another changes the family without touching the model.

photosvi.models.points.WindowedCategoricalEventGuide

WindowedCategoricalEventGuide(mf, *, window=10, thresh=2.5, gain=2.0)

Bases: Module

Per-bin marginals from a softmax over short windows -- timing alternatives compete.

The blocks above all carry the events as an independent per-bin gate. One real transient produces a kernel-correlation lobe several bins wide, and an independent factor answers that lobe with fractional mass at every bin in it, so the guide's total mass is lobe width x per-bin evidence -- a number with no fixed relation to how many transients there were. Measured on the frozen GT under the K5 kernel: sum(q) = 787 against 318 true onsets.

That inflation is not harmless, because the intensity coefficients are fit against it. With p_t = 1 - exp(-lambda_t dt) ~ lambda_t dt, the ELBO's cross term is a Poisson log-likelihood with the q_t as observations, so the stationary condition is lambda * T = sum(q): the fitted rate is the mass density, and

beta_inj = log(true rate ratio) + log(inflation_post / inflation_pre).

The second term is pure bias, and it is nonzero exactly when the inflation differs either side of the injection -- which it does, because the post-injection lobes overlap more. Measured: +1.24 under the old non-negative kernel, -0.16 under K5.

This block removes the term by construction. Each window of window bins gets one softmax over window + 1 outcomes -- "no onset here", or "onset at position k" -- so the per-bin marginals inside a window sum to at most 1:

pi_w = softmax(z_w),  q_t = pi_w[k(t)],  sum_{t in w} q_t = 1 - pi_w[0] <= 1

The mass becomes a genuine event count and the timing uncertainty moves into the within-window distribution, where it costs entropy and nothing else.

This is a reparameterization of the mean-field family, not a categorical joint. SingleTraceModel.guide still samples one relaxed Bernoulli per bin; what changed is that the marginals are now produced by a competition rather than independently. That keeps the model, the sampling, and the ELBO untouched -- so the bound is on the same quantity and comparisons against the other arms stay valid -- at the cost of the joint still allowing two events in a window. Making the joint categorical needs a custom distribution and is the follow-up if this works.

Choosing window: wide enough to contain the correlation lobe, so the alternatives genuinely compete; narrow enough that two real events rarely share one. Under K5 the lobe is 3 bins (0.12 s) and only 1.6% of true inter-event intervals fall below 0.2 s, so 5 bins is comfortable. Under the old kernel the lobe was 81 bins and no such window existed -- this block only became viable once the kernel was fixed.

Parameters:

Name Type Description Default
mf per-bin matched-filter score, shape [T] (or [1, T]) when every sequence in the

batch shares one trace's warm start, or [B, T] to give each sequence its own. The per-sequence form is what the hierarchical fit needs: a cohort is B different recordings, and expanding one animal's matched filter across all of them would warm-start every session at another animal's transients. The scores go in as gain * (m_t - thresh) against a fixed 0 for "no onset", so the initial softmax reproduces the classical detector's calls.

required
window bins per window. `T` need not divide evenly; the tail window is shorter.
10
Source code in src/photosvi/models/points/event_guides.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def __init__(
    self,
    mf: torch.Tensor,
    *,
    window: int = 10,
    thresh: float = 2.5,
    gain: float = 2.0,
):
    super().__init__()
    if window < 2:
        raise ValueError(f"window must be >= 2 bins (got {window})")
    if gain <= 0:
        raise ValueError(f"gain must be > 0 (got {gain})")
    m = torch.as_tensor(mf, dtype=torch.get_default_dtype())
    if m.dim() == 2 and m.shape[0] == 1:
        m = m[0]
    if m.dim() not in (1, 2):
        raise ValueError(f"mf must be [T], [1, T] or [B, T] (got shape {tuple(m.shape)})")
    self.window = int(window)
    # [T] -> broadcast to every sequence; [B, T] -> one warm start per sequence.
    self.per_sequence = m.dim() == 2
    self.register_buffer("warm_scores", (gain * (m - thresh)).detach().clone())

fitted_logits

fitted_logits(y)

The fitted logits, rebuilt from the fitted scores (call after training).

Source code in src/photosvi/models/points/event_guides.py
326
327
328
329
def fitted_logits(self, y: torch.Tensor) -> torch.Tensor:
    """The fitted logits, rebuilt from the fitted scores (call after training)."""
    B, T = y.shape
    return self._marginals(B, T, y.device, y.dtype).clamp(1e-6, 1 - 1e-6).logit().detach()

photosvi.models.points.FreeEventGuide

Bases: Module

Free per-(sequence, bin) event logits -- the mean-field default.

q_s_logits is a [B, T] pyro.param initialized at the prior intensity so the guide starts honest. Every bin is an independent knob: the family can represent any per-bin belief, which is what makes it flexible and also what lets it drift away from the trace under a long fit.

fitted_logits

fitted_logits(y)

The fitted logits, read back from the param store (call after training).

Source code in src/photosvi/models/points/event_guides.py
55
56
57
def fitted_logits(self, y: torch.Tensor) -> torch.Tensor:
    """The fitted logits, read back from the param store (call after training)."""
    return pyro.param("q_s_logits").detach()

photosvi.models.points.WarmFreeEventGuide

WarmFreeEventGuide(mf, *, thresh=2.5, gain=2.0, hi=6.0, floor=-6.0)

Bases: FreeEventGuide

FreeEventGuide seeded from the matched filter instead of the prior intensity.

Same variational family -- B*T free logits, the same q_s_logits param, the same readout -- so anything that differs from FreeEventGuide is the starting basin, not expressiveness. The warm logits are the classical detector init:

ell_t = clamp(gain * (m_t - thresh), floor, hi)

with m_t a standardized matched-filter score. thresh sets which score counts as evidence for an event, gain how sharply the logit responds either side of it, and the clamp keeps the sigmoid off its saturated tails where gradients die.

Why it exists: MatchedFilterEventGuide is the matched filter, so comparing it against a prior-initialized free guide moves family and initialization together. This block holds initialization fixed so the two contrasts separate.

Parameters:

Name Type Description Default
mf per-bin matched-filter score, shape [T] (or [1, T]). Precomputed by the

caller, typically benchmark.matched_filter_score(y, kernel, inj_t). Must be scored on the same trace and bin grid as the y later passed to the guide.

required
thresh the affine-and-clamp above. Defaults assume `mf` is

standardized, as matched_filter_score returns it.

2.5
gain the affine-and-clamp above. Defaults assume `mf` is

standardized, as matched_filter_score returns it.

2.5
hi the affine-and-clamp above. Defaults assume `mf` is

standardized, as matched_filter_score returns it.

2.5
floor the affine-and-clamp above. Defaults assume `mf` is

standardized, as matched_filter_score returns it.

2.5
Source code in src/photosvi/models/points/event_guides.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __init__(
    self,
    mf: torch.Tensor,
    *,
    thresh: float = 2.5,
    gain: float = 2.0,
    hi: float = 6.0,
    floor: float = -6.0,
):
    super().__init__()
    if gain <= 0:
        raise ValueError(f"gain must be > 0 (got {gain})")
    if floor >= hi:
        raise ValueError(f"floor must be < hi (got [{floor}, {hi}])")
    m = torch.as_tensor(mf, dtype=torch.get_default_dtype())
    if m.dim() == 2 and m.shape[0] == 1:
        m = m[0]
    if m.dim() != 1:
        raise ValueError(f"mf must be [T] or [1, T] (got shape {tuple(m.shape)})")
    warm = (gain * (m - thresh)).clamp(floor, hi)
    self.register_buffer("warm_logits", warm.detach().clone())

photosvi.models.points.MatchedFilterEventGuide

MatchedFilterEventGuide(mf, *, alpha_init=2.0, bias_init=-5.0)

Bases: Module

Amortized event logits ell_t = alpha * m_t + b, with alpha > 0.

m_t is a fixed per-bin matched-filter score (the trace correlated with the transient kernel); SVI tunes only the gain alpha and offset b. The whole family is two scalars, so instead of learning B*T independent beliefs the guide learns how strongly to trust the matched filter.

The positivity constraint on alpha is the load-bearing part. ell is then strictly increasing in m, so q(s_t=1) = sigmoid(ell_t) ranks bins in exactly matched-filter order for any (alpha, b). Detection ranking is therefore invariant to the fit: it cannot erode as SVI runs, which is what the free per-bin family does over a long fit. What the fit can still move is the calibration -- where the sigmoid puts the decision boundary.

Parameters:

Name Type Description Default
mf per-bin matched-filter score, shape [T] (or [1, T]). Precomputed by the

caller, typically benchmark.matched_filter_score(y, kernel, inj_t); stored as a buffer and never updated by the fit. Must be scored on the same trace and bin grid as the y later passed to the guide.

required
alpha_init initial gain (must be > 0). The default assumes `mf` is

standardized, as matched_filter_score returns it.

2.0
bias_init initial offset, on the logit axis. The default is a sparse

prior-ish start: sigmoid(-5) ~ 0.007 event probability at m = 0.

-5.0
Notes

Unlike a conv-net guide, this block has no weight init to draw from the RNG -- alpha and b start at fixed scalars. The fit's basin therefore does not depend on RNG call order at construction time.

Source code in src/photosvi/models/points/event_guides.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def __init__(
    self,
    mf: torch.Tensor,
    *,
    alpha_init: float = 2.0,
    bias_init: float = -5.0,
):
    super().__init__()
    if alpha_init <= 0:
        raise ValueError(f"alpha_init must be > 0 (got {alpha_init})")
    m = torch.as_tensor(mf, dtype=torch.get_default_dtype())
    if m.dim() == 2 and m.shape[0] == 1:
        m = m[0]
    if m.dim() != 1:
        raise ValueError(f"mf must be [T] or [1, T] (got shape {tuple(m.shape)})")
    self.register_buffer("mf", m.detach().clone())
    self.alpha_init = float(alpha_init)
    self.bias_init = float(bias_init)

fitted_logits

fitted_logits(y)

The fitted logits, rebuilt from the fitted alpha/b (call after training).

Source code in src/photosvi/models/points/event_guides.py
189
190
191
192
def fitted_logits(self, y: torch.Tensor) -> torch.Tensor:
    """The fitted logits, rebuilt from the fitted alpha/b (call after training)."""
    B, T = y.shape
    return self._logits(T, y.device, y.dtype).detach().expand(B, T)

gain_posterior

gain_posterior()

The fitted {"alpha", "bias"} -- how much the guide trusts the filter.

alpha is the gain on the standardized matched-filter score and bias the logit offset. Read after training; both are MAP point estimates, not posteriors with a width.

Source code in src/photosvi/models/points/event_guides.py
194
195
196
197
198
199
200
201
202
203
204
205
@torch.no_grad()
def gain_posterior(self) -> dict[str, float]:
    """The fitted `{"alpha", "bias"}` -- how much the guide trusts the filter.

    `alpha` is the gain on the standardized matched-filter score and `bias`
    the logit offset. Read after training; both are MAP point estimates, not
    posteriors with a width.
    """
    return {
        "alpha": float(pyro.param("q_s_alpha").detach()),
        "bias": float(pyro.param("q_s_bias").detach()),
    }

Kernels and anchors

photosvi.models.points.build_kernel

build_kernel(spec, length, dt)

Build a kernel from a config dict, dispatching on family.

{"family": "biexp", "k_rise":, "k_decay":, "normalize":} -> bi_exponential_kernel {"family": "biphasic", "k_rise_fast":, "k_decay_fast":, "k_rise_slow":, "k_decay_slow":} -> biphasic_kernel {"family": "bigamma", "shape_fast":, "rate_fast":, "shape_slow":, "rate_slow":, "undershoot_tol":} -> bigamma_kernel

One factory so the generating and fitted kernels are always built the same way and a config cannot silently disagree with itself about which family it means.

Source code in src/photosvi/models/points/events.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def build_kernel(spec: dict, length: int, dt: float) -> torch.Tensor:
    """Build a kernel from a config dict, dispatching on `family`.

    `{"family": "biexp", "k_rise":, "k_decay":, "normalize":}` -> `bi_exponential_kernel`
    `{"family": "biphasic", "k_rise_fast":, "k_decay_fast":, "k_rise_slow":,
      "k_decay_slow":}` -> `biphasic_kernel`
    `{"family": "bigamma", "shape_fast":, "rate_fast":, "shape_slow":, "rate_slow":,
      "undershoot_tol":}` -> `bigamma_kernel`

    One factory so the generating and fitted kernels are always built the same way and
    a config cannot silently disagree with itself about which family it means.
    """
    fam = spec.get("family", "biexp")
    if fam == "biexp":
        return bi_exponential_kernel(
            length, k_rise=spec["k_rise"], k_decay=spec["k_decay"], dt=dt,
            normalize=spec.get("normalize", "peak"),
        )
    if fam == "biphasic":
        return biphasic_kernel(
            length, k_rise_fast=spec["k_rise_fast"], k_decay_fast=spec["k_decay_fast"],
            k_rise_slow=spec["k_rise_slow"], k_decay_slow=spec["k_decay_slow"], dt=dt,
        )
    if fam == "bigamma":
        return bigamma_kernel(
            length, shape_fast=spec["shape_fast"], rate_fast=spec["rate_fast"],
            shape_slow=spec["shape_slow"], rate_slow=spec["rate_slow"], dt=dt,
            undershoot_tol=spec.get("undershoot_tol", 0.05),
        )
    raise ValueError(
        f"unknown kernel family {fam!r}; known: 'biexp', 'biphasic', 'bigamma'")

photosvi.models.points.biphasic_kernel

biphasic_kernel(length, k_rise_fast, k_decay_fast, k_rise_slow, k_decay_slow, dt=1.0 / 25.0)

Fast positive lobe minus a scaled slower lobe, the scale set so the areas cancel.

h = f - (sum f / sum s) * s, then peak-normalized. Both lobes are ordinary difference-of-exponential transients, so both decay: unlike the "zerosum" normalization of bi_exponential_kernel, which buys sum(h) = 0 with a flat DC offset that runs to the end of the support, this returns to zero and an event's influence genuinely ends.

Why sum(h) = 0 at all: with a non-negative kernel the phasic carrier c_t >= 0, so E[c_t] grows with the event rate and the tonic baseline is identified against the floor of the trace rather than its middle. Worse, that absorbed offset steps up at the injection (E[c_t] scales with lambda_t), landing in the same place as the drug's effect on the tonic and biasing beta_inj. A mean-free basis removes the channel: E[c_t] = 0 for any intensity.

Parameters:

Name Type Description Default
k_rise_fast the positive lobe; must satisfy k_rise > k_decay.
required
k_decay_fast the positive lobe; must satisfy k_rise > k_decay.
required
k_rise_slow the subtracted lobe. Must be genuinely slower

(k_decay_slow < k_decay_fast) or the difference has no positive lobe left.

required
k_decay_slow the subtracted lobe. Must be genuinely slower

(k_decay_slow < k_decay_fast) or the difference has no positive lobe left.

required
Source code in src/photosvi/models/points/events.py
 82
 83
 84
 85
 86
 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
116
117
118
119
120
121
122
123
124
125
126
def biphasic_kernel(
    length: int,
    k_rise_fast: float,
    k_decay_fast: float,
    k_rise_slow: float,
    k_decay_slow: float,
    dt: float = 1.0 / 25.0,
) -> torch.Tensor:
    """Fast positive lobe minus a scaled slower lobe, the scale set so the areas cancel.

    h = f - (sum f / sum s) * s, then peak-normalized. Both lobes are ordinary
    difference-of-exponential transients, so both decay: unlike the "zerosum"
    normalization of `bi_exponential_kernel`, which buys sum(h) = 0 with a flat DC
    offset that runs to the end of the support, this returns to zero and an event's
    influence genuinely ends.

    Why sum(h) = 0 at all: with a non-negative kernel the phasic carrier c_t >= 0, so
    E[c_t] grows with the event rate and the tonic baseline is identified against the
    floor of the trace rather than its middle. Worse, that absorbed offset steps up at
    the injection (E[c_t] scales with lambda_t), landing in the same place as the
    drug's effect on the tonic and biasing beta_inj. A mean-free basis removes the
    channel: E[c_t] = 0 for any intensity.

    Parameters
    ----------
    k_rise_fast, k_decay_fast : the positive lobe; must satisfy k_rise > k_decay.
    k_rise_slow, k_decay_slow : the subtracted lobe. Must be genuinely slower
        (`k_decay_slow < k_decay_fast`) or the difference has no positive lobe left.
    """
    if k_rise_fast <= k_decay_fast:
        raise ValueError(f"fast lobe needs k_rise > k_decay (got {k_rise_fast}, {k_decay_fast})")
    if k_rise_slow <= k_decay_slow:
        raise ValueError(f"slow lobe needs k_rise > k_decay (got {k_rise_slow}, {k_decay_slow})")
    if k_decay_slow >= k_decay_fast:
        raise ValueError(
            f"the subtracted lobe must decay slower than the fast one "
            f"(got k_decay_slow={k_decay_slow} >= k_decay_fast={k_decay_fast})"
        )
    fast = bi_exponential_kernel(length, k_rise_fast, k_decay_fast, dt=dt)
    slow = bi_exponential_kernel(length, k_rise_slow, k_decay_slow, dt=dt)
    h = fast - (fast.sum() / slow.sum()) * slow
    peak = h.max()
    if peak <= 0:
        raise ValueError("no positive lobe survives the subtraction; lobes are too close")
    return h / peak

photosvi.models.points.bi_exponential_kernel

bi_exponential_kernel(length, k_rise, k_decay, dt=1.0 / 25.0, normalize='peak')

Causal difference-of-exponentials transient kernel h.

h_k = exp(-k_decay * kdt) - exp(-k_rise * kdt), the slow minus the fast exponential. Nonnegative and zero at lag 0 exactly when k_rise > k_decay (the clamp_min guards a misconfigured pair). Same bi-exponential shape as the tonic baseline (the double-exponential drug-response curve) but at the transient timescale -- the two uses share no parameters.

length is the kernel support in bins; normalize rescales so the peak is 1 ("peak"), the area is 1 ("sum"), or the area is zero ("zerosum" -- mean-removed, then peak-normalized). Peak-normalization makes the mark a_t read directly as the transient's height; under "zerosum" the mark reads as the height above the kernel's own mean, so mu_a shifts scale slightly.

"zerosum" is not a claim about the sensor -- a real transient does not undershoot. It is an identifiability choice: with Sum(h) != 0 the phasic component is non-negative, so its mean grows with the event rate and the tonic baseline is pushed to the floor of the trace rather than through its middle. Because that absorbed offset steps up at the injection (E[c_t] scales with lambda_t) it lands in the same place as the drug's effect on the tonic, and beta_inj is biased. Sum(h) = 0 removes the channel.

Source code in src/photosvi/models/points/events.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def bi_exponential_kernel(
    length: int,
    k_rise: float,
    k_decay: float,
    dt: float = 1.0 / 25.0,
    normalize: str = "peak",
) -> torch.Tensor:
    """Causal difference-of-exponentials transient kernel h.

    h_k = exp(-k_decay * k*dt) - exp(-k_rise * k*dt), the slow minus the fast
    exponential. Nonnegative and zero at lag 0 exactly when k_rise > k_decay
    (the `clamp_min` guards a misconfigured pair). Same bi-exponential shape as
    the tonic baseline (the double-exponential drug-response curve) but at the *transient*
    timescale -- the two uses share no parameters.

    `length` is the kernel support in bins; `normalize` rescales so the peak is
    1 ("peak"), the area is 1 ("sum"), or the area is *zero* ("zerosum" --
    mean-removed, then peak-normalized). Peak-normalization makes the mark a_t
    read directly as the transient's height; under "zerosum" the mark reads as
    the height above the kernel's own mean, so mu_a shifts scale slightly.

    "zerosum" is not a claim about the sensor -- a real transient does not
    undershoot. It is an *identifiability* choice: with Sum(h) != 0 the phasic
    component is non-negative, so its mean grows with the event rate and the
    tonic baseline is pushed to the floor of the trace rather than through its
    middle. Because that absorbed offset steps up at the injection (E[c_t]
    scales with lambda_t) it lands in the same place as the drug's effect on
    the tonic, and beta_inj is biased. Sum(h) = 0 removes the channel.
    """
    k = torch.arange(length, dtype=torch.float32)
    tau = k * dt
    h = torch.exp(-k_decay * tau) - torch.exp(-k_rise * tau)
    h = h.clamp_min(0.0)
    if normalize == "peak":
        peak = h.max()
        if peak > 0:
            h = h / peak
    elif normalize == "sum":
        total = h.sum()
        if total > 0:
            h = h / total
    elif normalize == "zerosum":
        # Mean-remove, then peak-normalize the positive lobe. Sum(h) == 0 makes the
        # phasic carrier mean-free: E[c_t] = 0 for any intensity, so the event rate
        # no longer contributes to the signal mean and cannot compete with the tonic
        # for it. See the "mean-free phasic basis" note in the README.
        h = h - h.mean()
        peak = h.max()
        if peak > 0:
            h = h / peak
    return h

photosvi.models.points.fit_tonic_baseline

fit_tonic_baseline(y, inj_t, *, dt=1.0 / 25.0, smooth_s=10.0, peak_max=10.0)

Least-squares pre-fit of the Bateman baseline (eq 4) to y, as an SVI init.

A data-driven initializer for the tonic globals psi, the sibling of estimate_log_baseline_rate for the phasic GLM: it lands the smooth carrier near-optimal before relaxed-discrete SVI so the globals start well-conditioned and the seed-to-seed fit is more reproducible. Ported from an earlier double-exponential fit with three upgrades -- the injection bin is known (no t0 search), the linear drift d is included, and the fit target is a median-smoothed trace.

Two design choices, both empirical:

  • Fit the smoothed trend, not the raw trace. The tonic is the slow carrier; fit to raw y it chases the fast phasic spikes it has no events to explain. We median-smooth over a smooth_s-second window first (median, not mean, to shrug off the upward event excursions) and fit the Bateman to that slow trend.
  • Cap the amplitude at a_max. When k_rise ~ k_decay the difference-of-exponentials collapses toward a single-rate shape and only the product A*gap is identified, so an uncapped fit sends A to ~1e3 against a vanishing gap. The cap both regularizes that corner and -- per a 3-seed SVI sweep -- gives the most stable downstream fit (a modest tonic lets the events carry the fast structure).

y is [B, T] or [T]; a batch is averaged over B first (the tonic is shared across an animal's sequences, and the mean cancels phasic events landing at different bins, leaving the common slow trend). The Bateman ordering k_rise > k_decay is enforced inside curve_fit's box bounds via the same gap = exp(gamma) > 0 reparameterization TonicBaseline carries internally (eq 5): we fit (b, A, k_decay, gap, d) and set k_rise = k_decay + gap.

Returns a fresh TonicBaseline built from the fit (constrained units), ready to drop into SingleTraceModel; SVI then refines it. A near-flat trace (a saline non-responder) yields a tiny A and an essentially flat baseline -- the pre-fit does not manufacture a bump.

Parameters:

Name Type Description Default
y observed trace, [B, T] or [T] (z-scored dF/F in practice).
required
inj_t injection bin index.
required
dt bin width in seconds (sampling period); the smoothing window and the

Bateman time axis are both in seconds.

1.0 / 25.0
smooth_s median-smoothing window in seconds (~30s strips phasic events).
10.0
peak_max cap on the height of the fitted bump, in the units of the trace.

Was a cap on the raw amplitude A, where it did nothing useful: A is the unidentified half of the old parameterization, so capping it bounded a coordinate rather than the curve, and one real recording sat on the cap while producing an entirely ordinary tonic.

10.0
Source code in src/photosvi/models/points/tonic.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
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
def fit_tonic_baseline(
    y: torch.Tensor,
    inj_t: int,
    *,
    dt: float = 1.0 / 25.0,
    smooth_s: float = 10.0,
    peak_max: float = 10.0,
) -> TonicBaseline:
    """Least-squares pre-fit of the Bateman baseline (eq 4) to `y`, as an SVI init.

    A data-driven initializer for the tonic globals psi, the sibling of
    `estimate_log_baseline_rate` for the phasic GLM: it lands the smooth carrier
    near-optimal *before* relaxed-discrete SVI so the globals start
    well-conditioned and the seed-to-seed fit is more reproducible. Ported from
    an earlier double-exponential fit with three upgrades -- the injection bin is known (no t0 search), the linear drift
    `d` is included, and the fit target is a *median-smoothed* trace.

    Two design choices, both empirical:

    - **Fit the smoothed trend, not the raw trace.** The tonic is the *slow*
      carrier; fit to raw `y` it chases the fast phasic spikes it has no events
      to explain. We median-smooth over a `smooth_s`-second window first
      (median, not mean, to shrug off the upward event excursions) and fit the
      Bateman to that slow trend.
    - **Cap the amplitude at `a_max`.** When k_rise ~ k_decay the
      difference-of-exponentials collapses toward a single-rate shape and only
      the product A*gap is identified, so an uncapped fit sends A to ~1e3
      against a vanishing gap. The cap both regularizes that corner and -- per a
      3-seed SVI sweep -- gives the most *stable* downstream fit (a modest tonic
      lets the events carry the fast structure).

    `y` is [B, T] or [T]; a batch is averaged over B first (the tonic is shared
    across an animal's sequences, and the mean cancels phasic events landing at
    different bins, leaving the common slow trend). The Bateman ordering
    k_rise > k_decay is enforced inside `curve_fit`'s box bounds via the same
    gap = exp(gamma) > 0 reparameterization `TonicBaseline` carries internally
    (eq 5): we fit (b, A, k_decay, gap, d) and set k_rise = k_decay + gap.

    Returns a fresh `TonicBaseline` built from the fit (constrained units), ready
    to drop into `SingleTraceModel`; SVI then refines it. A near-flat trace (a saline
    non-responder) yields a tiny A and an essentially flat baseline -- the
    pre-fit does not manufacture a bump.

    Parameters
    ----------
    y : observed trace, [B, T] or [T] (z-scored dF/F in practice).
    inj_t : injection bin index.
    dt : bin width in seconds (sampling period); the smoothing window and the
        Bateman time axis are both in seconds.
    smooth_s : median-smoothing window in seconds (~30s strips phasic events).
    peak_max : cap on the height of the fitted bump, in the units of the trace.
        Was a cap on the raw amplitude A, where it did nothing useful: A is the
        unidentified half of the old parameterization, so capping it bounded a
        coordinate rather than the curve, and one real recording sat on the cap
        while producing an entirely ordinary tonic.
    """
    import numpy as np
    from scipy.optimize import curve_fit
    from scipy.signal import medfilt

    Y = y.unsqueeze(0) if y.dim() == 1 else y          # [B, T]
    trace = Y.mean(dim=0).detach().cpu().numpy()       # shared slow target, [T]
    T = trace.shape[0]
    t_s = np.arange(T) * float(dt)                     # seconds
    t_inj_s = float(inj_t) * float(dt)

    # median-smooth (~smooth_s) to strip the fast phasic events: the tonic should
    # see only the slow injection-locked trend. Odd window length for medfilt.
    win = int(round(smooth_s / float(dt))) // 2 * 2 + 1
    y_smooth = medfilt(trace, kernel_size=win) if win >= 3 else trace

    def _bateman(t, b, peak, k_decay, gap, d):
        # x_hat(t), reparameterized k_rise = k_decay + gap so a box bound gap > 0
        # enforces the Bateman ordering, and normalized to peak 1 so `peak` is the
        # height of the bump rather than a coefficient multiplying it. Same factored
        # expm1 form as `bateman_shape`, for the same reason: with gap small the
        # naive difference of exponentials is rounding error.
        k_rise = k_decay + gap
        tau = np.clip(t - t_inj_s, 0.0, None)
        post = (t >= t_inj_s).astype(float)
        t_pk = np.log(k_rise / k_decay) / gap
        f = np.exp(-k_decay * tau) * (-np.expm1(-gap * tau))
        f_pk = np.exp(-k_decay * t_pk) * (-np.expm1(-gap * t_pk))
        return b + post * (peak * f / max(f_pk, 1e-12) + d * tau / 3600.0)

    # Data-driven init: pre-injection median for b, post-injection swing for the
    # peak. That swing was always the right starting value -- it is the height of the
    # bump -- and under the old parameterization it was handed to A, which is the
    # height only when the rates are far apart. The optimizer then had a flat
    # direction to leave along, and left.
    b0 = float(np.median(y_smooth[:inj_t])) if inj_t >= 1 else float(np.median(y_smooth))
    swing = float(y_smooth[inj_t:].max() - b0) if inj_t < T else 0.0
    peak0 = float(np.clip(swing, 1e-4, peak_max * 0.99))
    #       b    peak   k_decay  gap    d       (k_rise = k_decay + gap)
    p0 = [b0,   peak0,  2e-3,    3e-3,  0.0]
    lo = [-np.inf, 1e-6, 1e-6, 1e-6, -np.inf]   # peak, k_decay, gap strictly > 0
    hi = [np.inf,  peak_max, np.inf, np.inf, np.inf]

    # Two passes, because the linear drift and the bump compete. `d * tau / 3600` is a
    # ramp, and over this window a SMALL Bateman is close enough to a ramp that the
    # optimizer can hand the whole post-injection rise to the drift and walk the peak
    # onto its lower bound -- returning exactly zero. Measured: with the bump at 303
    # noise standard deviations the pre-fit recovers it on every session of every seed;
    # at 15, which is what the recordings carry, it returns zero on at least one session
    # of every seed and on half the sessions of one. Those sessions then enter SVI with
    # no slow component and never recover.
    #
    # So fit the bump first with the drift pinned at zero, where it has no competitor,
    # and only then release the drift from that solution. If releasing it collapses the
    # peak onto the bound anyway, keep the pass that found a bump.
    def _no_drift(t, b, peak, k_decay, gap):
        return _bateman(t, b, peak, k_decay, gap, 0.0)

    popt4, _ = curve_fit(_no_drift, t_s, y_smooth, p0=p0[:4],
                         bounds=(lo[:4], hi[:4]), maxfev=40000)
    popt, _ = curve_fit(_bateman, t_s, y_smooth,
                        p0=[*popt4, 0.0], bounds=(lo, hi), maxfev=40000)
    b_f, peak_f, kdec_f, gap_f, d_f = (float(v) for v in popt)
    # "Collapsed" rather than "small": a bump genuinely absent in the data should come
    # back as a bump the model can shrink, not as the bound itself.
    if peak_f <= 10.0 * lo[1]:
        b_f, peak_f, kdec_f, gap_f = (float(v) for v in popt4)
        d_f = 0.0

    return TonicBaseline(
        b=b_f, peak=peak_f, k_rise=kdec_f + gap_f, k_decay=kdec_f, drift=d_f, dt=dt,
    )

photosvi.models.points.stack_tonic_baselines

stack_tonic_baselines(blocks)

Assemble per-trace fit_tonic_baseline pre-fits into one batched block.

The pre-fit stays per-trace -- it is a least-squares initializer, and each recording has its own bleaching and its own pharmacokinetic bump. This just stacks the results so SVI refines all of them together.

Source code in src/photosvi/models/points/tonic.py
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
def stack_tonic_baselines(blocks: list[TonicBaseline]) -> BatchedTonicBaseline:
    """Assemble per-trace `fit_tonic_baseline` pre-fits into one batched block.

    The pre-fit stays per-trace -- it is a least-squares initializer, and each
    recording has its own bleaching and its own pharmacokinetic bump. This just
    stacks the results so SVI refines all of them together.
    """
    if not blocks:
        raise ValueError("need at least one TonicBaseline to stack")
    dts = {b.dt for b in blocks}
    if len(dts) != 1:
        raise ValueError(f"all blocks must share one dt (got {sorted(dts)})")
    g = lambda f: torch.stack([f(b).detach().reshape(()) for b in blocks])  # noqa: E731
    return BatchedTonicBaseline(
        n_seq=len(blocks),
        b=g(lambda b: b.b),
        # `b.peak`, NOT `b.A` -- since the reparameterization, `A` is a DERIVED
        # textbook amplitude and feeding it back in as the stored parameter would
        # rescale every pre-fit by its own peak factor.
        peak=g(lambda b: b.peak),
        k_rise=g(lambda b: b.k_rise),
        k_decay=g(lambda b: b.k_decay),
        drift=g(lambda b: b.drift),
        dt=blocks[0].dt,
    )

photosvi.models.points.estimate_log_baseline_rate

estimate_log_baseline_rate(y, inj_t, *, dt=1.0 / 25.0, threshold=2.0, min_rate=0.001)

Data-driven anchor for beta0: the empirical pre-injection log event-rate.

A coarse proxy for the baseline log-intensity beta0 used to seed the prior mean (and guide loc) of SingleTraceModel's Bayesian phasic GLM. It counts the pre-injection transients of y -- local maxima rising more than threshold above the pre-injection median (the trace is z-scored dF/F, so threshold is in z-units) -- and converts the count to a rate:

r_hat = n_peaks / (B * n_pre_bins * dt),   beta0 ~ log(max(r_hat, min_rate)).

y is [B, T] or [T]; only bins t < inj_t are used. With multiple sequences the peaks are counted per sequence and pooled over the total pre-injection duration B * n_pre_bins * dt -- not on the averaged trace, which would cancel events landing at different bins across sequences. Each event is assumed to raise one peak, so overlapping transients undercount -- fine for an init anchor, not a fit. min_rate floors an empty pre-window so the log is finite. Returns a Python float (the log-rate).

Note this makes the beta0 prior weakly empirical-Bayes (its location is read off the data); the prior scale stays a fixed weakly-informative choice set on SingleTraceModel.

Source code in src/photosvi/models/points/events.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
def estimate_log_baseline_rate(
    y: torch.Tensor,
    inj_t: int,
    *,
    dt: float = 1.0 / 25.0,
    threshold: float = 2.0,
    min_rate: float = 1e-3,
) -> float:
    """Data-driven anchor for beta0: the empirical pre-injection log event-rate.

    A coarse proxy for the baseline log-intensity beta0 used to seed the prior
    mean (and guide loc) of SingleTraceModel's Bayesian phasic GLM. It counts the
    pre-injection *transients* of `y` -- local maxima rising more than
    `threshold` above the pre-injection median (the trace is z-scored dF/F, so
    `threshold` is in z-units) -- and converts the count to a rate:

        r_hat = n_peaks / (B * n_pre_bins * dt),   beta0 ~ log(max(r_hat, min_rate)).

    `y` is [B, T] or [T]; only bins t < inj_t are used. With multiple sequences
    the peaks are counted **per sequence and pooled** over the total
    pre-injection duration `B * n_pre_bins * dt` -- *not* on the averaged trace,
    which would cancel events landing at different bins across sequences. Each
    event is assumed to raise one peak, so overlapping transients undercount --
    fine for an *init* anchor, not a fit. `min_rate` floors an empty pre-window
    so the log is finite. Returns a Python float (the log-rate).

    Note this makes the beta0 prior weakly **empirical-Bayes** (its location is
    read off the data); the prior *scale* stays a fixed weakly-informative
    choice set on SingleTraceModel.
    """
    Y = y.unsqueeze(0) if y.dim() == 1 else y  # [B, T]
    pre = Y[:, :inj_t]                         # [B, n_pre]
    if pre.shape[1] < 3:
        return float(torch.log(torch.tensor(min_rate)))
    level = pre - pre.median(dim=1, keepdim=True).values  # detrend each sequence
    # interior local maxima above threshold: y_t > y_{t-1} and y_t >= y_{t+1}
    up = level[:, 1:-1] > level[:, :-2]
    down = level[:, 1:-1] >= level[:, 2:]
    is_peak = up & down & (level[:, 1:-1] > threshold)
    n_peaks = int(is_peak.sum().item())
    duration = pre.shape[0] * pre.shape[1] * float(dt)  # pooled over sequences
    rate = max(n_peaks / duration, float(min_rate))
    return float(torch.log(torch.tensor(rate)))

photosvi.models.points.estimate_log_noise_scale

estimate_log_noise_scale(y, inj_t=None, *, min_scale=0.001, ar_coeffs=None)

Data-driven anchor for sigma_y: the high-frequency noise floor of y.

A coarse proxy for the residual scale sigma_y used to seed the prior mean (and guide loc) of SingleTraceModel's optional Bayesian emission scale -- the sigma_y sibling of estimate_log_baseline_rate. It is the robust scale of the successive differences of y (the DAUB / Gasser-Sroka-Jennen-Steinmetz white-noise estimator):

d_t = y_t - y_{t-1},   sigma_hat = MAD(d) / (0.6745 * sqrt(2)),
sigma_y ~ log(max(sigma_hat, min_scale)).

Differencing is a high-pass filter, so the slow tonic structure the single -Bateman baseline can't represent is removed before the estimate -- the anchor tracks genuine measurement noise, not baseline misfit. The MAD makes it robust to the sparse phasic events (and the smooth convolved bumps they produce barely move the difference signal anyway), so it is not inflated by real signal. The /sqrt(2) undoes the variance doubling of differencing two independent noise samples; 0.6745 converts the MAD to a Gaussian std.

That /sqrt(2) assumes the noise is WHITE, and silently ruins the estimate if it is not: for an AR residual var(y_t - y_{t-1}) is 2 sigma^2 (1 - rho_1), so this returns sigma * sqrt(1 - rho_1). On the AR(2) fitted to the recordings rho_1 is 0.998 and the factor is 0.045 -- a 22-fold underestimate, which would hand the fit a trace it believes is almost noiseless. Pass ar_coeffs and the correction is divided out.

y is [B, T] or [T]; differences are taken along time and pooled over the batch. When inj_t is given, only the pre-injection window t < inj_t is used (the cleanest noise window -- no drug transient), mirroring estimate_log_baseline_rate. min_scale floors an empty/degenerate window so the log is finite. Returns a Python float (the log-scale).

Like the rate anchor this makes the sigma_y prior weakly empirical-Bayes (its location is read off the data); the prior scale stays a fixed narrow choice set on SingleTraceModel -- the knob that keeps sigma_y from inflating.

Source code in src/photosvi/models/points/emission.py
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
def estimate_log_noise_scale(
    y: torch.Tensor,
    inj_t: int | None = None,
    *,
    min_scale: float = 1e-3,
    ar_coeffs=None,
) -> float:
    """Data-driven anchor for sigma_y: the high-frequency noise floor of `y`.

    A coarse proxy for the residual scale sigma_y used to seed the prior mean
    (and guide loc) of SingleTraceModel's optional Bayesian emission scale -- the
    sigma_y sibling of `estimate_log_baseline_rate`. It is the robust scale of
    the **successive differences** of `y` (the DAUB / Gasser-Sroka-Jennen-Steinmetz
    white-noise estimator):

        d_t = y_t - y_{t-1},   sigma_hat = MAD(d) / (0.6745 * sqrt(2)),
        sigma_y ~ log(max(sigma_hat, min_scale)).

    Differencing is a high-pass filter, so the slow tonic structure the single
    -Bateman baseline can't represent is removed before the estimate -- the
    anchor tracks genuine measurement noise, not baseline misfit. The MAD makes
    it robust to the sparse phasic events (and the smooth convolved bumps they
    produce barely move the difference signal anyway), so it is not inflated by
    real signal. The `/sqrt(2)` undoes the variance doubling of differencing two
    independent noise samples; `0.6745` converts the MAD to a Gaussian std.

    That `/sqrt(2)` assumes the noise is WHITE, and silently ruins the estimate if it is
    not: for an AR residual var(y_t - y_{t-1}) is 2 sigma^2 (1 - rho_1), so this returns
    sigma * sqrt(1 - rho_1). On the AR(2) fitted to the recordings rho_1 is 0.998 and the
    factor is 0.045 -- a 22-fold underestimate, which would hand the fit a trace it
    believes is almost noiseless. Pass `ar_coeffs` and the correction is divided out.

    `y` is [B, T] or [T]; differences are taken along time and **pooled** over
    the batch. When `inj_t` is given, only the pre-injection window `t < inj_t`
    is used (the cleanest noise window -- no drug transient), mirroring
    `estimate_log_baseline_rate`. `min_scale` floors an empty/degenerate window
    so the log is finite. Returns a Python float (the log-scale).

    Like the rate anchor this makes the sigma_y prior weakly **empirical-Bayes**
    (its location is read off the data); the prior *scale* stays a fixed
    narrow choice set on SingleTraceModel -- the knob that keeps sigma_y from
    inflating.
    """
    Y = y.unsqueeze(0) if y.dim() == 1 else y  # [B, T]
    if inj_t is not None:
        Y = Y[:, :inj_t]
    if Y.shape[1] < 2:
        return float(math.log(min_scale))
    d = (Y[:, 1:] - Y[:, :-1]).reshape(-1)            # pooled successive differences
    med = d.median()
    mad = (d - med).abs().median()
    sigma_hat = float(mad.item()) * _MAD_TO_SIGMA / math.sqrt(2.0)
    if ar_coeffs:
        # undo the white-noise assumption: var(dy) = 2 sigma^2 (1 - rho_1)
        rho1 = float(ar_autocovariance(list(ar_coeffs), 2)[1])
        sigma_hat = sigma_hat / math.sqrt(max(1.0 - rho1, 1e-12))
    return float(math.log(max(sigma_hat, float(min_scale))))

Calibrating the kernel

photosvi.kernel_calibration.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.kernel_calibration.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.kernel_calibration.extract_isolated_transients

extract_isolated_transients(traces, fs, masks=None, *, prominence_sd=4.0, floor_sd=3.0, neighbour_frac=0.5, isolation_s=4.0, pre_s=1.0, post_s=4.0)

Find the transients that stand alone, and cut them out aligned on their maxima.

A transient is kept when its prominence exceeds prominence_sd robust standard deviations of the band-passed trace and no other peak lies within isolation_s of it on either side, counting as a neighbour any peak that is itself selectable and has at least neighbour_frac of the transient's prominence. floor_sd is the detection threshold for peaks at all. Smaller neighbours are let through on purpose: the noise's own maxima clear three standard deviations every few seconds, so counting them would disqualify nearly everything, and they land at random lags where the average washes them out. This is the selection the shipped kernel was fitted to (a 4 s exclusion among peaks above four standard deviations), with the larger neighbour required to be absent rather than merely smaller.

masks mark the bins that count, as in api.Session.mask. A transient whose window, or the second either side of it, touches a masked bin is dropped: the band-pass spreads an artefact into its neighbourhood, and the injection's handling artefact is exactly the kind of excursion this would otherwise select.

Source code in src/photosvi/kernel_calibration.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def extract_isolated_transients(
    traces: np.ndarray | Sequence[np.ndarray],
    fs: float,
    masks: Sequence[np.ndarray | None] | None = None,
    *,
    prominence_sd: float = 4.0,
    floor_sd: float = 3.0,
    neighbour_frac: float = 0.5,
    isolation_s: float = 4.0,
    pre_s: float = 1.0,
    post_s: float = 4.0,
) -> IsolatedTransients:
    """Find the transients that stand alone, and cut them out aligned on their maxima.

    A transient is kept when its prominence exceeds `prominence_sd` robust standard
    deviations of the band-passed trace and no other peak lies within `isolation_s` of it
    on either side, counting as a neighbour any peak that is itself selectable and has at
    least `neighbour_frac` of the transient's prominence. `floor_sd` is the detection
    threshold for peaks at all. Smaller neighbours are let through on purpose: the noise's
    own maxima clear three standard deviations every few seconds, so counting them would
    disqualify nearly everything, and they land at random lags where the average washes
    them out. This is the selection the shipped kernel was fitted to (a 4 s exclusion
    among peaks above four standard deviations), with the larger neighbour required to
    be absent rather than merely smaller.

    `masks` mark the bins that count, as in `api.Session.mask`. A transient whose window,
    or the second either side of it, touches a masked bin is dropped: the band-pass spreads
    an artefact into its neighbourhood, and the injection's handling artefact is exactly
    the kind of excursion this would otherwise select.
    """
    if isinstance(traces, np.ndarray) and traces.ndim == 1:
        traces = [traces]
    traces = [np.asarray(y, float).reshape(-1) for y in traces]
    if masks is None:
        masks = [None] * len(traces)
    if len(masks) != len(traces):
        raise ValueError(f"{len(masks)} masks for {len(traces)} recordings")
    b, a = _bandpass(fs)
    pre, post = int(round(pre_s * fs)), int(round(post_s * fs))
    guard, iso = int(round(1.0 * fs)), int(round(isolation_s * fs))
    width = max(1, int(0.04 * fs))

    snips, times, src = [], [], []
    for r, (y, m) in enumerate(zip(traces, masks)):
        keep = np.ones(y.size, bool) if m is None else np.asarray(m, bool).reshape(-1)
        if keep.size != y.size:
            raise ValueError(f"recording {r}: mask has {keep.size} bins, trace {y.size}")
        if y.size < 3 * max(pre + post, 64):
            continue
        z = filtfilt(b, a, detrend(y, type="linear"))
        # The noise scale from the bins that count only, so a masked artefact cannot
        # inflate it and raise the threshold for the whole recording.
        sd = float(np.median(np.abs(z[keep] - np.median(z[keep]))) / 0.6745)
        if sd <= 0:
            continue
        pk, props = find_peaks(z, prominence=floor_sd * sd, width=width)
        prom = props["prominences"]
        for i, p in enumerate(pk):
            if prom[i] < prominence_sd * sd:
                continue
            lo, hi = p - pre, p + post
            if lo - guard < 0 or hi + guard > y.size:
                continue
            if not keep[lo - guard:hi + guard].all():
                continue
            near = ((np.abs(pk - p) < iso)
                    & (prom >= max(prominence_sd * sd, neighbour_frac * prom[i])))
            if near.sum() > 1:
                continue
            snips.append(z[lo:hi] / z[p])
            times.append(p / fs)
            src.append(r)

    return IsolatedTransients(
        snippets=np.asarray(snips, float).reshape(-1, pre + post),
        times_s=np.asarray(times, float), source=np.asarray(src, int),
        fs=float(fs), pre=pre, post=post)