mc
mc
¶
Bayesian model comparison for SCRIBE.
This module provides scalable, fully Bayesian model comparison tools based on out-of-sample predictive accuracy. It implements two complementary criteria:
- WAIC (Widely Applicable Information Criterion): a fast, analytical approximation to LOO-CV computed entirely from the posterior samples already available after fitting.
- PSIS-LOO (Pareto-Smoothed Importance Sampling LOO): a more reliable criterion that applies Pareto smoothing to the raw IS weights, with a per-observation diagnostic k̂.
In addition, the module provides:
- Gene-level comparison: per-gene elpd differences between two models, with standard errors and z-scores.
- Model stacking: optimal predictive ensemble weights via convex optimization of the LOO log-score.
- Goodness-of-fit diagnostics: per-gene randomized quantile residuals (RQR) that assess how well a single fitted model describes each gene's count distribution, with expression-scale-invariant summary statistics.
- PPC-based goodness-of-fit: full posterior predictive checks that compare observed histograms to PPC credible bands, producing calibration failure rates and L1 density distances for higher-resolution gene filtering.
Quick start
from scribe.mc import compare_models mc = compare_models( ... [results_nbdm, results_hierarchical], ... counts=counts, ... model_names=["NBDM", "Hierarchical"], ... gene_names=gene_names, ... compute_gene_liks=True, ... ) print(mc.summary()) # ranked comparison table print(mc.diagnostics()) # PSIS k̂ diagnostics mc.rank() # pandas DataFrame mc.gene_level_comparison("NBDM", "Hierarchical") # per-gene DataFrame
Class hierarchy
ScribeModelComparisonResults— stores raw log-likelihood matrices and provides lazy-computed WAIC, PSIS-LOO, stacking, and gene-level methods.
Factory
compare_models()— accepts a list of fitted results objects, computes log-likelihoods for each model, and returns aScribeModelComparisonResults.
Low-level functions
waic()/compute_waic_stats()— JAX-accelerated WAIC.compute_psis_loo()— NumPy/SciPy PSIS-LOO with Pareto fitting.gene_level_comparison()— per-gene elpd differences.compute_stacking_weights()— stacking weight optimization.compute_quantile_residuals()— randomized quantile residuals.goodness_of_fit_scores()— per-gene fit diagnostics from residuals.compute_gof_mask()— boolean gene mask from fit quality.ppc_goodness_of_fit_scores()— PPC-based per-gene calibration and L1 scoring.compute_ppc_gof_mask()— PPC-based boolean gene mask with gene batching.
See paper/_model_comparison.qmd and paper/_goodness_of_fit.qmd
for full mathematical derivations.
ScribeModelComparisonResults
dataclass
¶
ScribeModelComparisonResults(model_names, log_liks_cell, log_liks_gene=None, gene_names=None, n_cells=0, n_genes=0, active_components=None, dtype=float64)
Structured results for Bayesian model comparison across K models.
Stores raw posterior log-likelihood matrices for each model and provides methods for computing WAIC, PSIS-LOO, model ranking, and gene-level comparisons. All expensive computations are performed lazily and cached.
| PARAMETER | DESCRIPTION |
|---|---|
model_names
|
Human-readable names for the K models in the comparison.
TYPE:
|
log_liks_cell
|
List of K arrays, each of shape
TYPE:
|
log_liks_gene
|
List of K arrays of shape
TYPE:
|
gene_names
|
Names for the G genes. Used in gene-level comparison output.
TYPE:
|
n_cells
|
Number of cells (observations).
TYPE:
|
n_genes
|
Number of genes.
TYPE:
|
active_components
|
Per-model boolean masks recording which mixture components survived the
dead-component pruning step (see :func:
TYPE:
|
dtype
|
Precision used for PSIS-LOO computations.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
K |
Number of models.
TYPE:
|
Examples:
>>> from scribe.mc import compare_models
>>> mc = compare_models(
... [results_nbdm, results_hierarchical],
... counts=counts,
... model_names=["NBDM", "Hierarchical"],
... gene_names=gene_names,
... compute_gene_liks=True,
... )
>>> mc.rank()
>>> mc.summary()
>>> mc.gene_level_comparison("NBDM", "Hierarchical")
waic
¶
Compute WAIC statistics for one or all models.
Results are cached after the first call; repeated calls are free.
| PARAMETER | DESCRIPTION |
|---|---|
model_idx
|
If provided, return WAIC statistics only for model
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict or list of dict
|
Each dict contains keys: |
Examples:
Source code in src/scribe/mc/results.py
psis_loo
¶
Compute PSIS-LOO statistics for one or all models.
PSIS-LOO is computed using NumPy/SciPy (Pareto fitting is not JIT- compilable). Results are cached after the first call.
| PARAMETER | DESCRIPTION |
|---|---|
model_idx
|
If provided, return PSIS-LOO statistics only for model
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict or list of dict
|
Each dict contains: |
Examples:
Source code in src/scribe/mc/results.py
stacking_weights
¶
Compute optimal stacking weights from PSIS-LOO estimates.
The stacking weights maximize the LOO log predictive score of the model ensemble. They are computed once and cached.
| PARAMETER | DESCRIPTION |
|---|---|
n_restarts
|
Number of random restarts for the convex optimization.
TYPE:
|
seed
|
Random seed.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
np.ndarray, shape ``(K,)``
|
Optimal stacking weights summing to 1. |
Source code in src/scribe/mc/results.py
rank
¶
Rank models by predictive performance.
Produces a summary DataFrame analogous to arviz.compare(), with
columns for elpd, effective parameter count, elpd difference from the
best model, standard error of the difference, and model weights.
| PARAMETER | DESCRIPTION |
|---|---|
criterion
|
Criterion to use for ranking. One of:
-
TYPE:
|
include_stacking
|
If
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Rows are models, sorted by elpd descending (best first). Columns:
|
Examples:
Source code in src/scribe/mc/results.py
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 | |
gene_level_comparison
¶
Compare two models gene by gene.
Computes per-gene elpd differences, standard errors, and z-scores using gene-level log-likelihoods (summed over cells).
Requires that :func:compare_models was called with
compute_gene_liks=True, otherwise raises RuntimeError.
| PARAMETER | DESCRIPTION |
|---|---|
model_A
|
Index or name of model A in the comparison.
TYPE:
|
model_B
|
Index or name of model B.
TYPE:
|
gene_names
|
Override the stored gene names.
TYPE:
|
criterion
|
WAIC variant to use for per-gene elpd.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
Per-gene comparison table from
:func: |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If gene-level log-likelihoods are not available. |
Examples:
Source code in src/scribe/mc/results.py
diagnostics
¶
Format PSIS-LOO diagnostics (k̂ summary) for one or all models.
| PARAMETER | DESCRIPTION |
|---|---|
model_idx
|
If provided, show diagnostics only for model
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Multi-line diagnostic summary. |
Source code in src/scribe/mc/results.py
summary
¶
Format a ranked comparison table as a string.
| PARAMETER | DESCRIPTION |
|---|---|
criterion
|
Ranking criterion:
TYPE:
|
include_stacking
|
Whether to include stacking weights.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted comparison table. |
Examples:
Source code in src/scribe/mc/results.py
__repr__
¶
Concise representation of the model comparison.
When dead-component pruning was applied, the repr shows the original
and surviving component counts per model, e.g. 'ZINBVCP(4→2)'.
Source code in src/scribe/mc/results.py
compare_models
¶
compare_models(results_list, counts, model_names=None, gene_names=None, n_samples=1000, rng_key=None, batch_size=None, posterior_sample_chunk_size=8, compute_gene_liks=False, ignore_nans=False, component_threshold=0.0, r_floor=1e-06, p_floor=1e-06, dtype_lik=float32, dtype_psis=float64)
Create a model comparison results object from a list of fitted models.
For each model, this function:
- Ensures posterior samples are available (calls
get_posterior_samplesif needed for SVI models). - Computes the per-cell log-likelihood matrix of shape
(S, C)using the model'slog_likelihoodmethod. - Optionally computes per-gene log-likelihood matrices of shape
(S, G)whencompute_gene_liks=True. - Returns a :class:
ScribeModelComparisonResultsthat provides lazy WAIC, PSIS-LOO, stacking, and gene-level comparison methods.
| PARAMETER | DESCRIPTION |
|---|---|
results_list
|
List of K fitted model objects to compare.
TYPE:
|
counts
|
Observed count matrix (cells × genes).
TYPE:
|
model_names
|
Human-readable names for each model. Defaults to
TYPE:
|
gene_names
|
Gene names for gene-level comparisons.
TYPE:
|
n_samples
|
Number of posterior samples to draw for SVI models that do not yet
have
TYPE:
|
rng_key
|
Random key for SVI posterior sampling. Defaults to
TYPE:
|
batch_size
|
Mini-batch size for log-likelihood computation.
TYPE:
|
posterior_sample_chunk_size
|
Posterior-sample chunk size passed to
TYPE:
|
compute_gene_liks
|
If
TYPE:
|
ignore_nans
|
If
TYPE:
|
component_threshold
|
Dead-component pruning threshold for mixture models. Any mixture
component whose posterior-mean mixing weight is strictly below
this fraction is removed before log-likelihood computation; the
remaining weights are renormalized to sum to one. This prevents dead
components from inflating Implementation note:
Component pruning currently relies on runtime tensor-shape inference
plus explicit mixture metadata from
TYPE:
|
r_floor
|
Minimum value clamped onto the NB dispersion parameter
TYPE:
|
p_floor
|
Epsilon applied to the success probability Two float32 degenerate cases this guards against:
Set to
TYPE:
|
dtype_lik
|
Precision for log-likelihood computation.
TYPE:
|
dtype_psis
|
Precision for PSIS-LOO computation. Double precision is recommended for reliable Pareto fitting.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ScribeModelComparisonResults
|
Structured comparison results with lazy-computed WAIC, PSIS-LOO, and stacking weights. |
Examples:
>>> from scribe.mc import compare_models
>>> mc = compare_models(
... [results_nbdm, results_hierarchical],
... counts=counts,
... model_names=["NBDM", "Hierarchical"],
... gene_names=gene_names,
... compute_gene_liks=True,
... )
>>> print(mc.summary())
>>> print(mc.diagnostics())
Source code in src/scribe/mc/results.py
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 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 | |
compute_waic_stats
¶
JIT-compiled computation of all WAIC statistics.
Computes lppd, both versions of the effective parameter count, and both WAIC variants from a log-likelihood matrix in a single forward pass.
| PARAMETER | DESCRIPTION |
|---|---|
log_liks
|
Log-likelihoods for each posterior sample
TYPE:
|
aggregate
|
If
TYPE:
|
dtype
|
Floating-point precision for all computations.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with keys:
|
Source code in src/scribe/mc/_waic.py
waic
¶
Compute WAIC statistics from a posterior log-likelihood matrix.
This is the public entry point. All JIT-compiled computation is delegated
to :func:compute_waic_stats.
| PARAMETER | DESCRIPTION |
|---|---|
log_liks
|
Matrix of log-likelihoods: rows are posterior samples, columns are
observations (cells when
TYPE:
|
aggregate
|
If
TYPE:
|
dtype
|
Floating-point precision.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Keys: |
Examples:
>>> import jax.numpy as jnp
>>> from scribe.mc._waic import waic
>>> log_liks = jnp.ones((500, 1000)) * -2.0 # (S=500, n=1000)
>>> stats = waic(log_liks)
>>> print(stats["waic_2"])
4000.0
Source code in src/scribe/mc/_waic.py
pseudo_bma_weights
¶
Compute pseudo-BMA model weights from an array of WAIC values.
The pseudo-BMA weight for model k is
w_k ∝ exp(-0.5 * (WAIC_k - min_k WAIC_k))
which mimics the AIC weight formula and provides a simple summary of relative model quality.
| PARAMETER | DESCRIPTION |
|---|---|
waic_values
|
WAIC values (on deviance scale, lower is better) for K models.
TYPE:
|
dtype
|
Floating-point precision.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
jnp.ndarray, shape ``(K,)``
|
Normalized model weights summing to 1. |
Examples:
>>> import jax.numpy as jnp
>>> from scribe.mc._waic import pseudo_bma_weights
>>> w = pseudo_bma_weights(jnp.array([200.0, 210.0, 215.0]))
>>> print(w.sum())
1.0
Source code in src/scribe/mc/_waic.py
compute_psis_loo
¶
Compute PSIS-LOO statistics from a posterior log-likelihood matrix.
For each observation i, applies Pareto-smoothed importance sampling to approximate the LOO predictive density without refitting the model. The Pareto shape parameter k̂_i serves as a per-observation reliability diagnostic.
| PARAMETER | DESCRIPTION |
|---|---|
log_liks
|
Log-likelihood matrix: rows are posterior samples, columns are observations (cells). Can be a JAX or NumPy array; internally converted to NumPy for Pareto fitting.
TYPE:
|
dtype
|
Numerical precision. Double precision is recommended for PSIS-LOO because the Pareto fitting can be sensitive to precision.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Keys:
|
Examples:
>>> import numpy as np
>>> from scribe.mc._psis_loo import compute_psis_loo
>>> rng = np.random.default_rng(0)
>>> log_liks = rng.normal(-3.0, 0.5, size=(500, 200))
>>> result = compute_psis_loo(log_liks)
>>> print(result["k_hat"].max())
Source code in src/scribe/mc/_psis_loo.py
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 | |
psis_loo_summary
¶
Format a human-readable summary of PSIS-LOO diagnostics.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
Output of :func:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
A multi-line summary string. |
Examples:
Source code in src/scribe/mc/_psis_loo.py
gene_level_comparison
¶
gene_level_comparison(log_liks_A, log_liks_B, gene_names=None, label_A='A', label_B='B', criterion='waic_2')
Compute per-gene model comparison statistics between two models.
For each gene g, computes the pointwise elpd difference between model A and model B. The difference is positive when model A provides better predictions than model B for gene g.
The standard error of the total elpd difference follows from the CLT applied to the pointwise gene-level differences (see @eq-mc-se-delta-elpd in the paper):
SE(delta_elpd) = sqrt(sum_g (d_g - d_bar)^2)
where d_g = elpd_g(A) - elpd_g(B) is the per-gene difference.
| PARAMETER | DESCRIPTION |
|---|---|
log_liks_A
|
Gene-level log-likelihoods for model A. Each entry is the total log p(all counts for gene g | theta^s) = sum_c log p(u_{gc}|theta^s). Rows are posterior samples, columns are genes.
TYPE:
|
log_liks_B
|
Gene-level log-likelihoods for model B. Must match
TYPE:
|
gene_names
|
Names for the G genes. If
TYPE:
|
label_A
|
Human-readable label for model A.
TYPE:
|
label_B
|
Human-readable label for model B.
TYPE:
|
criterion
|
Which WAIC variant to use for pointwise elpd values. Must be one of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with one row per gene and columns:
|
Notes
The per-gene SE is computed from the cell-level pointwise differences
within each gene. However, since log_liks_A/B are already summed
over cells (shape (S, G)), the only variability captured here is
across posterior samples. The reported elpd_diff_se is therefore
the posterior standard deviation of the per-gene elpd difference, not
a frequentist SE. It correctly reflects model uncertainty but not
sampling variability across cells.
Source code in src/scribe/mc/_gene_level.py
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 80 81 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 127 128 129 130 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 | |
format_gene_comparison_table
¶
Format a gene-level comparison DataFrame as a human-readable table.
| PARAMETER | DESCRIPTION |
|---|---|
df
|
Output of :func:
TYPE:
|
top_n
|
Number of top genes to display. Displays all genes if
TYPE:
|
sort_by
|
Column to sort by (descending by absolute value for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted table string. |
Source code in src/scribe/mc/_gene_level.py
compute_stacking_weights
¶
Compute optimal model stacking weights via convex optimization.
Solves the stacking problem:
w* = argmax_{w in Delta^{K-1}} sum_i log sum_k w_k * exp(loo_i_k)
using scipy's SLSQP solver with multiple random restarts to guard against local solutions (though the problem is strictly convex so local = global).
| PARAMETER | DESCRIPTION |
|---|---|
loo_log_densities
|
List of K arrays, each of shape
TYPE:
|
n_restarts
|
Number of random initializations. The best solution across restarts is returned.
TYPE:
|
seed
|
Random seed for reproducibility.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
np.ndarray, shape ``(K,)``
|
Optimal stacking weights, summing to 1. A weight near 0 means the corresponding model contributes negligibly to the optimal ensemble. |
Examples:
>>> import numpy as np
>>> from scribe.mc._stacking import compute_stacking_weights
>>> rng = np.random.default_rng(0)
>>> K, n = 3, 200
>>> # Model 1 is better; it has higher LOO densities
>>> loo1 = rng.normal(-2.0, 0.3, n)
>>> loo2 = rng.normal(-2.5, 0.3, n)
>>> loo3 = rng.normal(-3.0, 0.3, n)
>>> w = compute_stacking_weights([loo1, loo2, loo3])
>>> print(w) # Should be concentrated on model 1
Source code in src/scribe/mc/_stacking.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 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 | |
stacking_summary
¶
Format a human-readable summary of stacking weights.
| PARAMETER | DESCRIPTION |
|---|---|
weights
|
Stacking weights.
TYPE:
|
model_names
|
Names for the K models.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted summary string. |
Source code in src/scribe/mc/_stacking.py
compute_quantile_residuals
¶
Compute randomized quantile residuals for NB or NB-mixture models.
For each cell-gene pair, the observed count is mapped through the model's predictive CDF (randomized for discrete data) and then through the inverse normal CDF. Under a correctly specified model the residuals are i.i.d. standard normal.
| PARAMETER | DESCRIPTION |
|---|---|
counts
|
Observed UMI count matrix. Rows are cells, columns are genes.
TYPE:
|
r
|
NB dispersion parameter.
TYPE:
|
p
|
NB success probability.
TYPE:
|
rng_key
|
JAX PRNG key for the uniform randomization step.
TYPE:
|
mixing_weights
|
Mixture component weights.
TYPE:
|
epsilon
|
Clipping bound: PIT values are clamped to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
jnp.ndarray, shape ``(C, G)``
|
Randomized quantile residuals. Under the true model, each entry is approximately drawn from N(0, 1). |
Source code in src/scribe/mc/_goodness_of_fit.py
goodness_of_fit_scores
¶
Compute per-gene goodness-of-fit summary statistics from residuals.
Under a correctly specified model the residuals are i.i.d. N(0, 1) for each gene. These statistics measure departures from that reference.
| PARAMETER | DESCRIPTION |
|---|---|
residuals
|
Randomized quantile residual matrix (output of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with per-gene arrays of shape
|
Notes
Computational cost is O(C * G) for mean, variance, and tail excess. The KS distance additionally requires sorting each gene's residuals, adding an O(C log C * G) term, which is subdominant for typical single-cell dataset sizes.
Source code in src/scribe/mc/_goodness_of_fit.py
compute_gof_mask
¶
compute_gof_mask(counts, results, component=None, rng_key=None, counts_for_map=None, min_variance=0.5, max_variance=1.5, max_ks=None, epsilon=1e-06)
Build a per-gene goodness-of-fit boolean mask from a fitted model.
This is the high-level entry point analogous to
scribe.de.compute_expression_mask. It extracts MAP parameters
from the results object, computes randomized quantile residuals, and
returns a boolean mask indicating which genes are adequately described
by the model.
Under a correctly specified model, per-gene residual variance is approximately 1. Variance substantially above 1 indicates the model underestimates gene variability (e.g., missing zero-inflation or overdispersion); variance substantially below 1 indicates the model overestimates variability (e.g., prior too diffuse).
| PARAMETER | DESCRIPTION |
|---|---|
counts
|
Observed UMI count matrix used for residual computation.
TYPE:
|
results
|
Fitted model results object. Must support
TYPE:
|
component
|
For mixture models, if specified, slice to a single component
before computing MAP. If
TYPE:
|
rng_key
|
JAX PRNG key for the randomization step. If
TYPE:
|
counts_for_map
|
Count matrix to pass to
TYPE:
|
min_variance
|
Lower bound on the residual variance per gene. Genes with
TYPE:
|
max_variance
|
Upper bound on the residual variance per gene. Genes with
TYPE:
|
max_ks
|
If provided, upper bound on the KS distance per gene. Genes
exceeding this are also masked out. If
TYPE:
|
epsilon
|
Clipping bound for the PIT values (see
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
np.ndarray, shape ``(G,)``
|
Boolean mask: |
Source code in src/scribe/mc/_goodness_of_fit.py
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 | |
ppc_goodness_of_fit_scores
¶
Compute PPC-based per-gene goodness-of-fit scores.
For each gene the function compares the observed count histogram to posterior-predictive credible bands and produces two complementary metrics.
| PARAMETER | DESCRIPTION |
|---|---|
ppc_samples
|
Posterior predictive count samples.
TYPE:
|
obs_counts
|
Observed UMI count matrix for the same cells and genes.
TYPE:
|
credible_level
|
Width of the pointwise credible band (percentage). Default: 95.
TYPE:
|
max_bin
|
If set, histogram bins above this value are collapsed. Helps bound computation for heavy-tailed genes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with per-gene arrays of shape
|
See Also
compute_ppc_gof_mask : High-level mask builder that wraps this scorer. goodness_of_fit_scores : RQR-based alternative. scribe.stats.histogram.compute_histogram_credible_regions : Underlying credible-region computation.
Source code in src/scribe/mc/_goodness_of_fit.py
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 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 | |
compute_ppc_gof_mask
¶
compute_ppc_gof_mask(counts, results, component=None, n_ppc_samples=500, gene_batch_size=50, rng_key=None, counts_for_ppc=None, cell_mask=None, max_calibration_failure=0.5, max_l1_distance=None, credible_level=95, cell_batch_size=500, max_bin=None, verbose=True, return_scores=False)
Build a per-gene PPC goodness-of-fit boolean mask.
This is the high-level entry point for PPC-based gene filtering. It generates posterior predictive samples in gene batches, scores each batch against the observed counts, and applies user-specified thresholds to produce a boolean mask.
| PARAMETER | DESCRIPTION |
|---|---|
counts
|
Observed UMI counts for the cells classified into this model (or component). Used both for histogram comparison and for amortized capture models.
TYPE:
|
results
|
Fitted model results object. Must expose
TYPE:
|
component
|
For mixture models, which component to evaluate. If
TYPE:
|
n_ppc_samples
|
Number of posterior draws. Default: 500.
TYPE:
|
gene_batch_size
|
Number of genes per batch. Controls peak memory. Default: 50.
TYPE:
|
rng_key
|
JAX PRNG key. Defaults to
TYPE:
|
counts_for_ppc
|
Full count matrix
TYPE:
|
cell_mask
|
Boolean mask
TYPE:
|
max_calibration_failure
|
Upper bound on calibration failure rate. Genes exceeding this are masked out. Default: 0.5.
TYPE:
|
max_l1_distance
|
Upper bound on L1 density distance. If
TYPE:
|
credible_level
|
Credible band width (percentage) for calibration scoring. Default: 95.
TYPE:
|
cell_batch_size
|
Cell batch size passed to
TYPE:
|
max_bin
|
Cap on histogram bin count (see
TYPE:
|
verbose
|
Print progress messages. Default:
TYPE:
|
return_scores
|
If
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray or tuple[ndarray, dict]
|
Boolean mask of shape |
See Also
ppc_goodness_of_fit_scores : Low-level scorer. compute_gof_mask : RQR-based alternative.
Source code in src/scribe/mc/_goodness_of_fit.py
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 | |