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 |
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 |
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 |
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 |
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 |
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 |
-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 |
-2.0
|
sigma_y_prior_loc
|
prior mean for the Bayesian emission scale on the
|
|
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 |
0.1
|
event_guide
|
the block supplying q(s)'s per-bin logits (`event_guides.py`).
|
None (default) installs |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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
|
|
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
|
|
0.5
|
event_guide
|
as in
|
|
0.5
|
couple_events
|
as in
|
|
0.5
|
analytic_s_kl
|
as in
|
|
0.5
|
mark_kl
|
as in
|
|
0.5
|
mark_window
|
as in
|
|
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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
|
|
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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. |
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 | |
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.
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 | |
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 | |
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 | |
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.
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 | |
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 | |
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 | |
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; |
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:
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
It also replaces, rather than complements, a slow component added to the mean:
|
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 | |
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 | |
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 | |
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 | |
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 |
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 | |
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 | |
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 | |
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 |
required |
thresh
|
the affine-and-clamp above. Defaults assume `mf` is
|
standardized, as |
2.5
|
gain
|
the affine-and-clamp above. Defaults assume `mf` is
|
standardized, as |
2.5
|
hi
|
the affine-and-clamp above. Defaults assume `mf` is
|
standardized, as |
2.5
|
floor
|
the affine-and-clamp above. Defaults assume `mf` is
|
standardized, as |
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 | |
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 |
required |
alpha_init
|
initial gain (must be > 0). The default assumes `mf` is
|
standardized, as |
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 | |
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 | |
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 | |
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 | |
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
|
( |
required |
k_decay_slow
|
the subtracted lobe. Must be genuinely slower
|
( |
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 | |
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 | |
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
yit chases the fast phasic spikes it has no events to explain. We median-smooth over asmooth_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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |