Skip to content

Experiments

The simulation studies behind the paper. These are entry points for reproducing results, not part of the modelling API.

Cohort simulation

photosvi.experiments.cohort.CohortSpec dataclass

CohortSpec(n_animals=8, design='crossed', mu_drug=(0.2, 1.1, 1.39), sigma_animal=0.25, sigma_cell=0.1, beta0_mean=-2.85, sigma_b0=0.22, sigma_b0_session=0.2, sigma_y=0.1062, mu_a=1.7666, sigma_a=0.212, fs=25, T=60000, inj_t=15000, inj_jitter=1500, tonic_b=-0.3406, tonic_peak=(0.4618802153517006, 3.939445759311477, 3.209953463886826), tonic_k_rise=(0.006, 0.005, 0.014), tonic_k_decay=(0.002, 0.0009, 0.0028), tonic_drift=-7.92, ou_sd=0.0, ou_tau=0.7, ar_rho=0.0, ar_coeffs=None, kernel_length=125, kernel=(lambda: dict(family='biphasic', k_rise_fast=20.0, k_decay_fast=9.0, k_rise_slow=8.0, k_decay_slow=3.5))())

The generative truth for one simulated cohort.

mu_drug is on the log-rate-ratio axis: mu_drug[d] is the mean log ratio of post- to pre-injection event rate under drug d. The estimand of the study is the contrast mu_drug[OPIOID2] - mu_drug[OPIOID1]; mu_drug[SALINE] is the handling response the vehicle sessions control for.

tonic_peak_s

tonic_peak_s(d)

Bateman peak time for drug d, in seconds after injection.

Source code in src/photosvi/experiments/cohort.py
164
165
166
167
def tonic_peak_s(self, d: int) -> float:
    """Bateman peak time for drug `d`, in seconds after injection."""
    kr, kd = self.tonic_k_rise[d], self.tonic_k_decay[d]
    return math.log(kr / kd) / (kr - kd)

indices

indices()

(animal, drug) per session, for whichever design this spec names.

The two designs are the extremes an experimenter actually chooses between, and they differ in what the opioid-versus-opioid contrast is:

  • crossed -- every animal receives every drug. The contrast is within-animal, so the animal effect enters both of its terms and cancels, exactly as it does in a paired test. What is left governing the width is the animal x drug interaction.
  • uncrossed -- every animal receives vehicle and exactly one opioid, alternating which. The contrast is now between-animal: nothing cancels, and the between-animal spread enters it directly. It is also the design in which each animal x drug cell holds a single session, so the interaction and a session residual are the same partition and only one of them can be identified -- _detect_levels is what decides that, from the indices.

Both are generated at the same number of RECORDINGS, which is the thing an experiment pays for: 8 animals x 3 sessions and 12 animals x 2 sessions are both 24. Comparing them at equal animal counts instead would confound the design with the sample size and answer a question nobody is asking.

Source code in src/photosvi/experiments/cohort.py
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
def indices(self) -> tuple[list[int], list[int]]:
    """(animal, drug) per session, for whichever design this spec names.

    The two designs are the extremes an experimenter actually chooses between,
    and they differ in what the opioid-versus-opioid contrast *is*:

    * `crossed` -- every animal receives every drug. The contrast is
      within-animal, so the animal effect enters both of its terms and cancels,
      exactly as it does in a paired test. What is left governing the width is
      the animal x drug interaction.
    * `uncrossed` -- every animal receives vehicle and exactly one opioid,
      alternating which. The contrast is now between-animal: nothing cancels,
      and the between-animal spread enters it directly. It is also the design in
      which each animal x drug cell holds a single session, so the interaction
      and a session residual are the same partition and only one of them can be
      identified -- `_detect_levels` is what decides that, from the indices.

    Both are generated at the same number of RECORDINGS, which is the thing an
    experiment pays for: 8 animals x 3 sessions and 12 animals x 2 sessions are
    both 24. Comparing them at equal animal counts instead would confound the
    design with the sample size and answer a question nobody is asking.
    """
    if self.design == "crossed":
        animal = [a for a in range(self.n_animals) for _ in range(self.n_drugs)]
        drug = [d for _ in range(self.n_animals) for d in range(self.n_drugs)]
        return animal, drug
    if self.design != "uncrossed":
        raise ValueError(f"design must be 'crossed' or 'uncrossed', got {self.design!r}")
    # Alternate which opioid an animal sees, so the two groups are equal in size and
    # neither is confounded with position in the cohort.
    #
    # With TWO conditions there is no vehicle session to add: breaking the crossing
    # means one condition per animal and nothing else, which is exactly what hiding
    # half of a two-condition cohort produces, and is the design the paper's uncrossed
    # arm on the real recordings simulates. The three-drug form keeps the vehicle
    # session because its contrast is between two opioids and vehicle is a third arm.
    animal, drug = [], []
    for a in range(self.n_animals):
        if self.n_drugs == 2:
            animal += [a]
            drug += [a % 2]
        else:
            animal += [a, a]
            drug += [SALINE, OPIOID1 if a % 2 == 0 else OPIOID2]
    return animal, drug

photosvi.experiments.cohort.spec_from_config

spec_from_config(cfg, delta)

Build the cohort truth from the study config and one effect size.

The single definition of the simulated truth. Both arms of the comparison call this; duplicating the construction in each worker is how two arms end up quietly fitting different data while every test still passes, and the resulting comparison would be meaningless in a way nothing downstream could detect.

delta places the second opioid above the first on the log-rate axis, so delta = 0 is the null: both drugs active, indistinguishable from each other.

Two conditions instead of three when the config omits mu_opioid1, which is the design the recordings actually have: a vehicle arm and a treated arm, with delta the difference between them. The three-drug form is kept because the shipped study uses it and its tonic and effect vectors are indexed by drug; a config that names mu_opioid1 gets exactly the cohorts it always did.

Source code in src/photosvi/experiments/cohort.py
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
def spec_from_config(cfg: dict, delta: float) -> CohortSpec:
    """Build the cohort truth from the study config and one effect size.

    **The single definition of the simulated truth.** Both arms of the comparison
    call this; duplicating the construction in each worker is how two arms end up
    quietly fitting different data while every test still passes, and the resulting
    comparison would be meaningless in a way nothing downstream could detect.

    `delta` places the second opioid above the first on the log-rate axis, so
    `delta = 0` is the null: both drugs active, indistinguishable from each other.

    **Two conditions instead of three** when the config omits `mu_opioid1`, which is the
    design the recordings actually have: a vehicle arm and a treated arm, with `delta` the
    difference between them. The three-drug form is kept because the shipped study uses it
    and its tonic and effect vectors are indexed by drug; a config that names `mu_opioid1`
    gets exactly the cohorts it always did.
    """
    c = cfg["cohort"]
    if "mu_opioid1" in c:
        mu_drug = (c["mu_saline"], c["mu_opioid1"], c["mu_opioid1"] + float(delta))
    else:
        mu_drug = (c["mu_saline"], c["mu_saline"] + float(delta))
    # Noise-unit marks (opt-in, experiments.marks): the simulated marks are drawn from the
    # same fixed distribution in units of sigma_y that the fit assumes.
    from photosvi.experiments.marks import noise_unit_generation, noise_unit_mode
    nu = noise_unit_mode(cfg.get("fit"))
    # (A sigma_y of 0 is the real cohort's placeholder, set from the recordings after.)
    if nu is not None and c["sigma_y"] > 0:
        c = dict(c)
        c["mu_a"], c["sigma_a"] = noise_unit_generation(cfg.get("fit"), c["sigma_y"],
                                                        c["mu_a"], c["sigma_a"])
    return CohortSpec(
        n_animals=c["n_animals"],
        # Defaulted, not indexed, because the shipped study is crossed and the
        # uncrossed arm is a variant that names itself: a config that predates the
        # field should keep producing exactly the cohorts it always produced.
        design=c.get("design", "crossed"),
        mu_drug=mu_drug,
        sigma_animal=c["sigma_animal"], sigma_cell=c["sigma_cell"],
        beta0_mean=c["beta0_mean"], sigma_b0=c["sigma_b0"],
        sigma_b0_session=c["sigma_b0_session"], sigma_y=c["sigma_y"],
        # Defaulted rather than indexed, like `design`: the simulated study has no
        # reason to set them and a config that predates the keys should keep producing
        # the cohorts it always did. Real recordings do set them, because the mark
        # scale is in the units of the trace and the shipped value assumes transients
        # tens of times more prominent than a dF/F recording carries.
        mu_a=c.get("mu_a", CohortSpec.mu_a), sigma_a=c.get("sigma_a", CohortSpec.sigma_a),
        T=c["T"], inj_t=c["inj_t"], inj_jitter=c["inj_jitter"],
        # Defaulted rather than required, like the keys above, but it must be READ: a
        # config that names 48 Hz and a 48 Hz kernel length while the spec silently stays
        # at 25 produces recordings at one rate with a basis built for another, and
        # nothing downstream says so. Five errors of exactly this shape have been found
        # in this project already.
        fs=int(c.get("fs", CohortSpec.fs)),
        tonic_b=float(c.get("tonic_b", CohortSpec.tonic_b)),
        tonic_peak=tuple(c["tonic_peak"]),
        ou_sd=c.get("ou_sd", CohortSpec.ou_sd),
        ou_tau=c.get("ou_tau", CohortSpec.ou_tau),
        ar_rho=c.get("ar_rho", CohortSpec.ar_rho),
        ar_coeffs=c.get("ar_coeffs", CohortSpec.ar_coeffs),
        # The transient basis, defaulted rather than indexed so that a config written
        # before 2026-09-30 still produces K5. Exposed because K5 is no longer
        # obviously the right one: it was selected on simulation-side criteria in
        # September, and the first raw recordings put 1.16% of its power above 10 Hz
        # against 0.024% in the data. K7 in scripts/kernel_candidates.py is the same
        # shape with every rate constant scaled by 0.25, which lands at 0.022% --
        # `kernel: {family: biphasic, k_rise_fast: 5.0, k_decay_fast: 2.25,
        # k_rise_slow: 2.0, k_decay_slow: 0.875}` selects it.
        #
        # Within the biphasic family, `kernel_length` does NOT need raising with it,
        # which is worth stating because the opposite seems obvious. The builder sets
        # the slow lobe's scale from the sums over whatever length it is given, so the
        # basis is mean-free at any truncation: measured across 125 to 700 taps, sum(h)
        # stays at 1e-6 and the only thing that moves is the undershoot, from -0.247 to
        # -0.257 at the shortest. Peak, width and high-frequency share are identical
        # to three decimals.
        #
        # `family: bigamma` is the exception, and the default 125 taps is NOT enough for
        # it -- `bigamma_kernel` refuses that length rather than returning a kernel whose
        # undershoot has grown to swallow the transient. At 25 Hz it wants 143 taps and
        # this default gives 125, so a bigamma config must raise `kernel_length` too.
        # K9 in scripts/kernel_candidates.py is the fitted member of that family:
        # `kernel: {family: bigamma, shape_fast: 20.34, rate_fast: 15.65,
        # shape_slow: 15.40, rate_slow: 3.95}` with `kernel_length: 200`.
        kernel=c.get("kernel", CohortSpec().kernel),
        kernel_length=c.get("kernel_length", CohortSpec.kernel_length),
        tonic_k_rise=tuple(c["tonic_k_rise"]),
        tonic_k_decay=tuple(c["tonic_k_decay"]),
        tonic_drift=c["tonic_drift"])

photosvi.experiments.cohort.simulate_cohort

simulate_cohort(spec, seed)

Generate one cohort. Deterministic in (spec, seed).

Returns y [S, T] plus the indices, the injection bins and the per-session truth: the coefficients actually drawn, and the count MLE of beta_inj from the realized onsets -- which is the best any method could do on that recording, and therefore the right reference for a per-session estimate.

Source code in src/photosvi/experiments/cohort.py
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 simulate_cohort(spec: CohortSpec, seed: int) -> dict:
    """Generate one cohort. Deterministic in `(spec, seed)`.

    Returns `y` [S, T] plus the indices, the injection bins and the per-session
    truth: the coefficients actually drawn, and the count MLE of `beta_inj` from the
    realized onsets -- which is the best any method could do on that recording, and
    therefore the right reference for a per-session estimate.
    """
    g = torch.Generator().manual_seed(int(seed))
    animal, drug = spec.indices()
    S, T, dt = spec.n_sessions, spec.T, spec.dt
    kern = build_kernel(dict(spec.kernel), spec.kernel_length, dt)

    # animal-level draws
    z_anim = torch.randn(spec.n_animals, generator=g)
    z_b0 = torch.randn(spec.n_animals, generator=g)
    z_cell = torch.randn(S, generator=g)
    z_b0s = torch.randn(S, generator=g)
    jitter = torch.randint(-spec.inj_jitter, spec.inj_jitter + 1, (S,), generator=g)

    ys, inj_ts, beta_inj_true, beta0_true, mles, n_pre, n_post = [], [], [], [], [], [], []
    for s in range(S):
        a, d = animal[s], drug[s]
        inj = int(spec.inj_t + jitter[s])
        bi = (spec.mu_drug[d]
              + spec.sigma_animal * float(z_anim[a])
              + spec.sigma_cell * float(z_cell[s]))
        b0 = (spec.beta0_mean
              + spec.sigma_b0 * float(z_b0[a])
              + spec.sigma_b0_session * float(z_b0s[s]))
        tonic = TonicBaseline(
            dt=dt, b=spec.tonic_b, peak=spec.tonic_peak[d],
            k_rise=spec.tonic_k_rise[d], k_decay=spec.tonic_k_decay[d],
            drift=spec.tonic_drift)
        x = tonic.baseline(T, inj)
        if spec.ou_sd > 0:
            warnings.warn(
                f"CohortSpec.ou_sd is deprecated: an OU sampled at dt is an AR(1). "
                f"Use sigma_y={spec.ou_sd:g} with "
                f"ar_rho={math.exp(-dt / spec.ou_tau):.5f} instead "
                f"(= exp(-dt/{spec.ou_tau:g})), which puts the same process in the "
                f"emission, where the model can score it.",
                DeprecationWarning, stacklevel=2)
            # Exact discrete OU, not an Euler step: with dt/tau around 0.06 the two
            # differ by a few percent in the stationary variance, and the amplitude is
            # the quantity being calibrated against real recordings.
            rho = math.exp(-dt / spec.ou_tau)
            innov = spec.ou_sd * math.sqrt(1 - rho**2)
            eps = torch.randn(T, generator=g).numpy()
            eps[0] = spec.ou_sd * eps[0] / innov          # stationary first sample
            # lfilter rather than a Python loop: the recursion is the same and 60000
            # steps per session times 24 sessions is a minute of interpreter time.
            ou = lfilter([innov], [1.0, -rho], eps)
            x = x + torch.as_tensor(ou, dtype=x.dtype)
        ex = PhasicEventProcess(kern, beta0=b0, beta_inj=bi, mu_a=spec.mu_a,
                                sigma_a=spec.sigma_a, dt=dt, history=None).sample(T, inj, 1, g)
        y = (AdditiveEmission(sigma_y=spec.sigma_y, ar_coeffs=spec.ar_coeffs)
             if spec.ar_coeffs else
             AdditiveEmission(sigma_y=spec.sigma_y, ar_rho=spec.ar_rho)).sample(
            x + ex["c"], generator=g)["y"][0]
        onsets = ex["s"][0].nonzero().reshape(-1)
        pre = int((onsets < inj).sum())
        post = int((onsets >= inj).sum())
        mle = (torch.log(torch.tensor(
            (post / ((T - inj) * dt)) / (pre / (inj * dt)))).item()
            if pre and post else float("nan"))
        ys.append(y)
        inj_ts.append(inj)
        beta_inj_true.append(bi)
        beta0_true.append(b0)
        mles.append(mle)
        n_pre.append(pre)
        n_post.append(post)

    return {
        "y": torch.stack(ys),
        "animal": animal,
        "drug": drug,
        "inj_t": inj_ts,
        "beta_inj_true": beta_inj_true,
        "beta0_true": beta0_true,
        "mle": mles,
        "n_pre": n_pre,
        "n_post": n_post,
        "seed": int(seed),
        "tonic_peak_s": [spec.tonic_peak_s(d) for d in range(spec.n_drugs)],
    }