Python API¶
photosvi.api is the part of the package meant to be used from outside it: loading a
recording, fitting it and reading the result. Its interfaces stay stable within a major
version. The pages under Internals document the model and inference code behind it,
which can change between versions.
Recordings¶
photosvi.api.Session
dataclass
¶
Session(trace, fs, inj_t, name='session', metadata=dict(), mask=None)
One recording: a trace, when the injection happened, and who it came from.
trace is corrected dF/F, one dimension. Preprocessing -- isosbestic correction,
bleaching, dF/F -- happens upstream of this package.
metadata carries the experimental design: animal, drug, dose, and whatever else
the study records. It is free-form here and becomes the index vectors the
hierarchical model reads, so a pilot that only fits single recordings should still
fill it in -- it costs nothing now and is the difference between having a cohort
later and having a pile of unlabelled traces.
from_channels
classmethod
¶
from_channels(signal, isosbestic, fs, *, inj_s, inj_end_s=None, mask_min_s=0.0, als_lambda=None, name='session', **metadata)
A Session from the raw sensor and isosbestic channels, corrected to dF/F.
The correction is the one applied to Doric files: the isosbestic channel is
scaled onto the sensor's baseline over the stretch before the injection and
divided out (photosvi.data.preprocess.correct_isosbestic). One second is trimmed
from each end, so inj_t of the result is shifted accordingly. The handling
window, from inj_s to the later of inj_end_s and inj_s + mask_min_s, is
masked from the likelihood.
Source code in src/photosvi/api.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
photosvi.api.Study
dataclass
¶
Study(sessions)
A set of sessions fitted together. One session is a legitimate study.
photosvi.api.load_doric_session ¶
load_doric_session(path, *, inj_start_s=None, inj_end_s=None, event=None, mask_min_s=0.0, als_lambda=None, name=None, **metadata)
A Doric recording as a Session: isosbestic-corrected dF/F, injection and its mask.
The injection is the user's inj_start_s (and inj_end_s, the end of the handling
window) when given; otherwise the file's injection event -- event by name, or the
last one recorded -- and an error if there is neither. Bins from the injection to the
later of inj_end_s and inj_start_s + mask_min_s are excluded from the likelihood:
handling moves the fibre and produces transient-shaped artefacts at the moment the rate
is meant to change. Returns the Session and a dict saying where the times came from.
Source code in src/photosvi/api.py
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 | |
photosvi.api.load_session ¶
load_session(path, *, fs, inj_t=None, inj_s=None, column=None, isosbestic_column=None, name=None, **metadata)
Read one recording from .csv, .txt, .npy or .npz.
Without isosbestic_column the trace (column) must already be corrected dF/F. With
it, column is the raw sensor channel and isosbestic_column the control, and the
two are corrected to dF/F as a Doric file is (see Session.from_channels); one
second is then trimmed from each end and inj_t of the result is shifted with it.
inj_s is accepted as well as inj_t because an injection is recorded in
seconds by whoever ran the experiment, and converting by hand is a good way to be
off by a factor of the sampling rate.
Source code in src/photosvi/api.py
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 | |
photosvi.api.read_manifest ¶
read_manifest(table, *, mask_min_s=0.0, fs=None)
The sessions a table lists, and for each where its injection times came from.
Source code in src/photosvi/cli/manifest.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
Fitting¶
photosvi.api.FitSettings
dataclass
¶
FitSettings(steps=None, max_steps=None, threads=4, device='auto', seed=0, event_threshold=None, refractory=None, lr=None, tau=None, window=None, sigma_y=None, ar_coeffs=None, mu_a=None, sigma_a=None, mark_prior_sd=None, mark_noise_units=None, mark_gate_floor=None, kernel_length=None, kernel=None)
Everything a caller may reasonably want to change, with defended defaults.
None means "use the shipped value" and is the default for every model
hyperparameter, so a caller that changes nothing gets the paper's single-trace model:
the configuration of PRODUCTION_CONFIG, with the noise scale, the AR coefficients
and the mark distribution read off the recording as the paper reads them, and the
mark prior and gate floor of REAL_DATA_CONFIG. Only the operational fields -- how
long to run, how many threads, which device -- have literals here, because those are
properties of the machine rather than of the model.
resolved ¶
resolved(fs=None)
Every value this fit will actually use, with the shipped defaults filled in.
Durations the config gives in bins (kernel support, refractory window) are
rescaled from its sampling rate to fs; without fs they are quoted at the
config's own rate. Values read off the recording (sigma_y, ar_coeffs, mu_a,
sigma_a) stay None here and are filled in by fit_session.
Source code in src/photosvi/api.py
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | |
photosvi.api.fit_session ¶
fit_session(session, settings=None, *, on_progress=None, probe_every=250)
Fit one recording and return its readouts.
The model is built through PointsSetup, the same path the paper's benchmark
uses, so this cannot drift from the validated configuration -- and stopping uses
the same plateau rule, so it converges rather than running a fixed number of
steps that happens to be too few.
on_progress is called every probe_every steps with the step number, the
running ELBO and the current estimate. A forty-minute recording is ten minutes of
fitting on four CPU threads, so anything with a user in front of it needs a
progress channel rather than a return value.
Source code in src/photosvi/api.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 | |
photosvi.api.fit_study ¶
fit_study(study, settings=None, **kw)
Fit each session independently.
Deliberately NOT the hierarchical model. Fitting a cohort jointly is a different
estimand -- a population contrast rather than a per-session effect -- and giving
it the same name here would let a caller believe they had one when they had the
other. The joint fit is fit_cohort, with its own return type.
Source code in src/photosvi/api.py
881 882 883 884 885 886 887 888 889 890 | |
photosvi.api.CohortSettings
dataclass
¶
CohortSettings(min_steps=50000, max_steps=100000, probe_every=1000, device='auto', seed=0, pre_s=600.0, levels=None, ar_coeffs=None, kernel=None, kernel_fs=None, mark_gate_floor=None, config=COHORT_CONFIG)
What a caller may change in a cohort fit. None means the shipped value.
The defaults are the paper's real-cohort fit: at least 50,000 and at most 100,000 steps,
the contrast probed every 1,000 steps and the fit stopped once it no longer drifts, a
window of 10 minutes before the injection, the levels of DEFAULT_LEVELS that the
design identifies, and the kernel of the single-trace model.
photosvi.api.fit_cohort ¶
fit_cohort(study, settings=None, *, reference=None, condition_keys=('condition', 'drug'), animal_keys=('animal',), on_progress=None)
Fit a cohort jointly with the hierarchical model.
study is a Study, or a list of Session, one per recording; each session's
metadata names its animal (animal) and its condition (condition, or drug). The
contrasts are differences between conditions in the log rate of transients after the
injection; reference is the condition the others are compared against (by default
the first in alphabetical order), usually the vehicle.
All sessions must have the same sampling rate. Each is cut to the same window around
its injection: settings.pre_s before it, and as much after it as every session has.
Bins where Session.mask is False (the handling window) are left out of the
likelihood.
on_progress is called at every probe with the step, the maximum number of steps and
the current contrasts against the reference. The paper's cohort, 13 forty-minute
recordings, takes about half an hour on a GPU.
Source code in src/photosvi/cohort_fit.py
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | |
Results¶
photosvi.api.Result
dataclass
¶
Result(session, settings, beta0, beta_inj, event_prob, tonic, stopped_at, seconds, device='cpu', beta_mean=None, beta_cov=None, mu_a=None, sigma_a=None, sigma_y=None, ar_coeffs=(), kernel=None)
What one fitted session yields, and the only thing callers should read.
rate_ratio is the estimand: the factor by which the drug changed the transient
rate, with a credible interval. event_prob is the per-bin posterior, from which
events() picks peaks -- the two are different questions and the interval caveat
applies only to the first (see MODEL_CARD.md).
simulate ¶
simulate(n=1, seed=0)
Recordings the fitted model generates: a posterior predictive check.
Each draw samples (beta0, beta_inj) from their joint posterior, events from the
intensity, marks from the fitted distribution, convolves them with the kernel and
adds the fitted tonic and autoregressive noise. It needs no ground truth, so it
applies to experimental recordings: a draw that looks unlike the recording says the
fit has not captured it. Returns one dict per draw with the trace y and the
number of events n_events.
Source code in src/photosvi/api.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | |
events ¶
events(threshold=None)
Peak-picked events above threshold, after non-maximum suppression.
Source code in src/photosvi/api.py
415 416 417 418 419 420 421 | |
rate_per_min ¶
rate_per_min(threshold=None)
Observed event rate before and after the injection, in events per minute.
A descriptive counterpart to rate_ratio: this counts detections, while
rate_ratio is a parameter of the model. They answer the same question by
different routes and are not obliged to agree exactly.
Source code in src/photosvi/api.py
423 424 425 426 427 428 429 430 431 432 433 434 435 436 | |
save ¶
save(out)
Write a run directory: result.json, events.csv, and the fitted curves.
Files rather than a database, and the same layout the command line writes, so a GUI run and a scripted run are interchangeable downstream.
Source code in src/photosvi/api.py
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | |
photosvi.api.CohortResult
dataclass
¶
CohortResult(conditions, reference, animals, sessions, settings, design, contrasts_, tonic, tonic_contrasts_, variance_components, sigma_y, sigma_y_sessions, ar_coeffs, kernel, kernel_length, fs, inj_t, steps, converged_at, sd_settled, skipped_steps, seconds, device, trajectory=list(), y=None, event_prob=None, tonic_session=None, tonic_condition=None, mask=None)
What a cohort fit yields.
contrast(a, b) is the estimand: the difference between conditions a and b in the
log rate of transients after the injection, with a 90% interval that carries the
between-animal variability. tonic holds each condition's pooled tonic response.
contrast ¶
contrast(a, b=None)
Condition a minus b (default: the reference), with its 90% interval.
estimate, lo and hi are on the log-rate axis; ratio, ratio_lo and
ratio_hi are the same as the factor by which the transient rate after the
injection differs between the two conditions.
Source code in src/photosvi/cohort_fit.py
115 116 117 118 119 120 121 122 123 124 | |
tonic_ratio ¶
tonic_ratio(a, b=None)
Ratio of the tonic peak heights, a over b (default: the reference), 90%.
Source code in src/photosvi/cohort_fit.py
126 127 128 129 130 131 132 | |
save ¶
save(out)
Write a run directory: result.json and curves.npz (the [S, T] arrays).
Source code in src/photosvi/cohort_fit.py
153 154 155 156 157 158 159 160 161 162 163 164 | |
photosvi.api.events_from_posterior ¶
events_from_posterior(prob, *, fs, threshold, refractory)
Turn a per-bin event posterior into a list of events.
Separate from Result so that re-thresholding a stored run uses the same rule
the fit reported, rather than a second implementation that agrees today.
The posterior is per-bin, so one transient contributes a cluster of adjacent high-probability bins; suppression is what turns that cluster into one event rather than several. The refractory width is a reporting choice, not a biological claim, and it should be stated wherever counts are.
Re-thresholding is cheap and correct: nothing about the fit depends on the threshold. It is a readout of the posterior, applied afterwards. The rate ratio, by contrast, is a parameter of the model and does not move when this does -- which is the whole point of estimating it rather than counting detections.
Source code in src/photosvi/api.py
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 | |
Before a fit¶
photosvi.api.calibrate_kernel ¶
calibrate_kernel(sessions, *, sensor='dLight1.3b', families=('biphasic', 'bigamma', 'biexp'), folds=5, min_transients=20, maxiter=600, seed=0, **extract_kw)
Fit candidate kernels to a set of recordings and suggest one.
sessions is an api.Session, a list of them, or an api.Study; all must share a
sampling rate, since a kernel is a shape in bins once it is built. sensor chooses the
starting values (see SENSORS) and labels the result; every family is also started
from the other sensors' values. extract_kw go to extract_isolated_transients.
Held-out error is the RMS residual, in units of the transient's peak, of a candidate
against the average of the transients it was not fitted to, over folds folds. The
two shipped kernels are scored on the same folds without fitting.
Source code in src/photosvi/kernel_calibration.py
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 | |
photosvi.api.KernelCalibration
dataclass
¶
KernelCalibration(transients, candidates, recommended, sensor, folds, warnings=list())
Every candidate kernel, scored on the same held-out transients, and a suggestion.
settings ¶
settings(key=None)
FitSettings fields for a candidate, the suggested one by default.
Source code in src/photosvi/kernel_calibration.py
434 435 436 | |
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.api.spectrum ¶
spectrum(session, *, n_per_segment=4096, band=(1.0, 10.0))
Power spectral density of a recording, and whether the transient band survives.
The single most likely silent failure on real data is a trace that has already been low-pass filtered upstream. The model does not error on one: it explains a smooth curve with a point process and returns a rate ratio, and the only symptom is that few events are found -- which looks like a biological result.
The spectrum makes it visible before anything is fitted. The two components live
in separate places: the pharmacokinetic carrier below 0.01 Hz, and the transients
in a shoulder from about 1 Hz up. band_ratio compares the power inside that
shoulder to the power just below it; a trace whose transients have been filtered
away has almost none, and one that never had transients looks the same -- so this
diagnoses the trace, not the biology, and says so.
Source code in src/photosvi/api.py
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 | |
photosvi.api.config_path ¶
config_path(name)
Path of a config shipped with the package, e.g. config_path("toy.yaml").
The configs live inside the package (photosvi/configs/), so they are there after a
pip install as well as in a clone, where configs/ at the root links to them.
Source code in src/photosvi/api.py
198 199 200 201 202 203 204 205 206 207 208 | |