Continuous marks¶
The per-spike diagnostics, with the predictive p-value by Monte Carlo, for marks that cannot be enumerated, such as the waveform features of clusterless decoding.
continuous_marks
¶
Per-event diagnostics of events whose marks are continuous or intractable.
A marked point-process observation model gives every event a mark (for
clusterless decoding, the event's waveform features) and a joint intensity
lambda(x, y) of events with mark y at state x. Its ground intensity
Lambda(x) = integral of lambda(x, y) dy is the total event rate at x, and
lambda(x, y) / Lambda(x) is the distribution of an event's mark given the
state.
With a finite set of marks, such as the units of spike-sorted data, the
predictive check is a finite sum; use :func:~statespacecheck.mark_predictive_pvalue
and :func:~statespacecheck.event_diagnostics. When the marks are continuous or
too many to enumerate, :func:monte_carlo_mark_pvalue evaluates the same check
by simulation, from a :class:MarkModel: a function that evaluates the log of
the joint intensity of given marks at every state (:data:LogMarkIntensity), a
function that draws a mark for an event at a given state (:data:MarkSampler),
and the ground intensity. The intensity is taken as its log because densities of
many-dimensional marks are often too small to represent: the density of a mark
with 32 waveform features can be exp(-140), below the smallest float32, in
which some decoders compute, and more features or distant marks go below the
smallest float64 (about exp(-745)).
:func:clusterless_event_diagnostics computes all three per-event diagnostics
(HPD overlap, KL divergence and this p-value) from the same :class:MarkModel.
State-bin indices passed to a :data:MarkSampler are flat indices into the
state grid, in the C order of its spatial axes (as reshape(n, -1) flattens
them).
Attributes¶
LogMarkIntensity
module-attribute
¶
Log of the joint intensity of marks at every state.
Called with marks of shape (n, *mark_shape); returns log lambda(x, y) for
each mark at every state bin as float64, shape (n, *spatial_shape): finite, or
-inf where the intensity is zero. Compute it in log space (for example with
scipy.stats.norm.logpdf); exponentiating first can underflow. Observed marks
are passed read-only; copy them before modifying them.
MarkSampler
module-attribute
¶
Draws one mark for an event at each given state bin.
Called with flat state-bin indices of shape (n,) and a random number
generator; returns marks of shape (n, *mark_shape), each drawn from
lambda(x, y) / Lambda(x) at its bin. It must draw only from the generator it
is given, so that seeded results are reproducible. The indices are read-only.
Classes¶
MarkModel
¶
Bases: NamedTuple
A marked point-process observation model, as the continuous-mark functions take it.
The three parts must describe the same model: ground_intensity is the
integral of exp(log_intensity) over marks, and sample draws from
exp(log_intensity) / ground_intensity at each state. Bundling them keeps
one model's parts together; it cannot check that they agree, and a mismatch
biases the p-values.
Attributes:
| Name | Type | Description |
|---|---|---|
log_intensity |
LogMarkIntensity
|
Log joint intensity |
sample |
MarkSampler
|
Draws a mark for an event at each given state bin. |
ground_intensity |
(ndarray, shape(...))
|
Total event intensity |
MarkPredictiveCheck
¶
Bases: NamedTuple
Result of :func:monte_carlo_mark_pvalue.
Attributes:
| Name | Type | Description |
|---|---|---|
pvalue |
(ndarray, shape(n_events))
|
Monte Carlo predictive p-value of each event's observed mark. |
observed_log_density |
(ndarray, shape(n_events))
|
Log predictive density of the observed mark, |
simulated_log_density |
np.ndarray, shape (n_events, n_samples), or None
|
Log predictive density of each replicated mark, if requested. |
Functions:¶
monte_carlo_mark_pvalue
¶
monte_carlo_mark_pvalue(state_dist: ArrayLike, model: MarkModel, observed_marks: ArrayLike, *, n_samples: int = 1000, rng: Generator | int | None = None, return_samples: bool = False, batch_size: int = DEFAULT_MONTE_CARLO_BATCH_SIZE) -> MarkPredictiveCheck
Monte Carlo predictive p-value of each event's observed mark.
The rank-based predictive p-value of the paper, for marks that cannot be enumerated. The predictive mark density of an event is
f_pred(y) = sum_x lambda(x, y) P(x) / sum_x Lambda(x) P(x),
and the p-value is the probability that a mark Y drawn from f_pred
is no more probable than the observed mark:
p = Pr[f_pred(Y) <= f_pred(y_obs)]. It is estimated from n_samples
replicated marks per event: each draws a state from the event-weighted
predictive distribution (:func:~statespacecheck.event_weighted_predictive),
then a mark at that state with model.sample. The comparison is made on
log densities with a tolerance for their rounding error,
16 * eps * (n_bins + M), where M bounds the magnitudes of the log
terms that affect each sum (log P, log lambda and log Lambda,
before they cancel), so marks with equal predictive density count as ties
at any scale of the inputs (compare the tie tolerance of
:func:~statespacecheck.mark_predictive_pvalue). Small values mean the
observed mark was unexpected given the prediction; an impossible mark
gives 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dist
|
(ndarray, shape(n_events, ...))
|
Predictive state distribution for each event, where |
required |
model
|
MarkModel
|
The observation model: the log joint intensity |
required |
observed_marks
|
(ndarray, shape(n_events, *mark_shape))
|
The mark of each event. |
required |
n_samples
|
int
|
Replicated marks per event. Default is 1000; the p-value's Monte Carlo
standard error is |
1000
|
rng
|
np.random.Generator, int, or None
|
Random number generator or seed. Default is None (fresh entropy). |
None
|
return_samples
|
bool
|
Also return the log predictive density of every replicated mark. Default is False. |
False
|
batch_size
|
int
|
Events processed at a time. Peak memory is about
|
DEFAULT_MONTE_CARLO_BATCH_SIZE
|
Returns:
| Type | Description |
|---|---|
MarkPredictiveCheck
|
The p-values, the log predictive density of each observed mark, and the replicated log densities if requested. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If shapes are inconsistent, inputs are negative, non-finite or masked,
|
See Also
mark_predictive_pvalue : The exact p-value for a finite set of marks. predictive_pvalue : A Monte Carlo p-value from a user-supplied sampler of whole time bins.
Notes
Results are reproducible: the same integer seed and the same
batch_size give identical p-values. Changing batch_size changes
which random numbers each event receives, so p-values then differ within
Monte Carlo error.
The p-value is r / B: the fraction of B = n_samples replicated marks at most as
probable as the observation. It estimates the predictive tail probability,
with standard error sqrt(p (1 - p) / B). A rank test at a finite B
would use (r + 1) / (B + 1) instead, computed from the returned p as
(p * B + 1) / (B + 1). It is valid in finite samples when the observation
and the replicates are exchangeable under the model, and possibly conservative:
it is never below 1 / (B + 1), and its level equals alpha only when
alpha (B + 1) is an integer and there are no ties.
Examples:
Two marks, whose exact p-values :func:~statespacecheck.mark_predictive_pvalue
also gives:
>>> import numpy as np
>>> from statespacecheck import MarkModel, mark_predictive_pvalue, monte_carlo_mark_pvalue
>>> state = np.array([[0.6, 0.3, 0.1], [0.6, 0.3, 0.1]])
>>> rates = np.array([[4.0, 1.0], [1.0, 1.0], [1.0, 4.0]]) # (n_bins, n_marks)
>>> def log_mark_intensity(marks):
... return np.log(rates[:, marks].T)
>>> def sample_marks(bins, rng): # mark 1 with probability rates[x, 1] / Lambda(x)
... return (rng.random(len(bins)) < rates[bins, 1] / rates[bins].sum(axis=1)).astype(
... int
... )
>>> model = MarkModel(log_mark_intensity, sample_marks, rates.sum(axis=1))
>>> check = monte_carlo_mark_pvalue(state, model, np.array([0, 1]), n_samples=2000, rng=0)
>>> check.pvalue.round(1)
array([1. , 0.3])
>>> mark_predictive_pvalue(state, rates, np.array([0, 1])).round(3)
array([1. , 0.317])
Source code in src/statespacecheck/continuous_marks.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 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 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 | |
clusterless_event_diagnostics
¶
clusterless_event_diagnostics(predictive: ArrayLike, model: MarkModel, event_time_ind: ArrayLike, event_marks: ArrayLike, *, coverage: float = DEFAULT_COVERAGE, n_samples: int = 1000, rng: Generator | int | None = None, return_likelihood: bool = False, batch_size: int = DEFAULT_MONTE_CARLO_BATCH_SIZE) -> EventDiagnostics
Compute HPD overlap, KL divergence, and predictive p-value for events with any marks.
The per-event diagnostics of :func:~statespacecheck.event_diagnostics for
marks that cannot be enumerated, such as the waveform features of
clusterless decoding; they apply to any mark space the model can sample.
Each event is compared with the one-step predictive distribution P of
its time bin:
- The single-event likelihood is the joint intensity of the observed mark
normalized over states,
Q(x) = lambda(x, y_obs) / sum_u lambda(u, y_obs)(computed in log space); HPD overlap and KL divergence compare it withP. - The predictive p-value is :func:
monte_carlo_mark_pvalue's, from the predictive mark densityf_pred(y) = sum_x lambda(x, y) P(x) / sum_x Lambda(x) P(x).
With a finite set of marks, such as the units of spike-sorted data, use
:func:~statespacecheck.event_diagnostics: its p-value is exact. Written
as a :class:MarkModel of integer marks whose log_intensity is
np.log of the same (float64) intensity table, those marks give the same HPD
overlap, KL divergence and likelihood bit for bit, and the same p-values
within Monte Carlo error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictive
|
(ndarray, shape(n_time, ...))
|
One-step predictive state distribution |
required |
model
|
MarkModel
|
The observation model: the log joint intensity |
required |
event_time_ind
|
(ndarray, shape(n_events))
|
Time-bin index of each event. Events that share a time bin are each compared with that bin's predictive distribution. |
required |
event_marks
|
(ndarray, shape(n_events, *mark_shape))
|
The mark of each event, for example its waveform features. |
required |
coverage
|
float
|
Coverage probability of the HPD regions. |
0.95
|
n_samples
|
int
|
Replicated marks per event for the p-value; its Monte Carlo standard
error is |
1000
|
rng
|
np.random.Generator, int, or None
|
Random number generator or seed. Default is None (fresh entropy). |
None
|
return_likelihood
|
bool
|
If True, also return each event's normalized likelihood,
shape |
False
|
batch_size
|
int
|
Events processed at a time; see :func: |
8
|
Returns:
| Type | Description |
|---|---|
EventDiagnostics
|
Per-event |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If shapes are inconsistent, |
See Also
event_diagnostics : The exact diagnostics for a finite set of marks. monte_carlo_mark_pvalue : The p-value alone, for given state distributions.
Notes
The p-values are :func:monte_carlo_mark_pvalue's for
predictive[event_time_ind]: the same seed and batch_size give
identical results. HPD overlap, KL divergence and the likelihood do not
depend on the seed. They depend on batch_size only in the last bit,
and only if model.log_intensity computes a mark's values differently
depending on how many marks it is called with (a matrix product can).
The returned likelihood is exponentiated after normalizing in log space, so
it is exactly 0 at states where its log is more than about 745 below the
largest (a ratio below the smallest float64, about 5e-324). The KL
divergence at such states is computed from the log intensity, so it is
+inf only where the prediction has mass and the intensity is zero
(disjoint supports).
Examples:
Two units' place fields written as a model of integer marks, whose exact
diagnostics :func:~statespacecheck.event_diagnostics also gives:
>>> import numpy as np
>>> from statespacecheck import MarkModel, clusterless_event_diagnostics, event_diagnostics
>>> predictive = np.array([[0.7, 0.2, 0.1], [0.1, 0.2, 0.7]]) # (n_time, n_bins)
>>> place_fields = np.array([[5.0, 0.1], [1.0, 1.0], [0.1, 5.0]]) # (n_bins, n_marks)
>>> def log_mark_intensity(marks):
... return np.log(place_fields[:, marks].T)
>>> def sample_marks(bins, rng): # unit 1 with probability place_fields[x, 1] / Lambda(x)
... unit_1 = place_fields[bins, 1] / place_fields[bins].sum(axis=1)
... return (rng.random(len(bins)) < unit_1).astype(int)
>>> model = MarkModel(log_mark_intensity, sample_marks, place_fields.sum(axis=1))
>>> time_ind, marks = np.array([0, 1]), np.array([0, 0])
>>> result = clusterless_event_diagnostics(
... predictive, model, time_ind, marks, n_samples=5000, rng=0
... )
>>> result.predictive_pvalue.round(2)
array([1. , 0.17])
>>> exact = event_diagnostics(predictive, place_fields, time_ind, marks)
>>> exact.predictive_pvalue.round(3)
array([1. , 0.172])
>>> bool(np.array_equal(result.kl_divergence, exact.kl_divergence))
True
Source code in src/statespacecheck/continuous_marks.py
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 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 | |