API reference
Once you know which function you need, you can look up its arguments, defaults and errors here. The guides explain when to use each: Methods for generation and Evaluation for scoring.
Import every function, and every class you construct, from pyplasmode; the functions in
pyplasmode.metrics are the exception. A few conventions hold throughout:
- Matrices have one row per observation and one column per feature.
feature_idsgives one unique name per column, because selections and recovery targets refer to features by name. - Generated arrays are read-only, so that a dataset cannot change after its calibration
checks have run. Copy an array with
np.array(...)before changing it. - Results are dataclasses.
dataclasses.asdictturns one into a plain dictionary, for example to save it as a row of a results table.
To keep source rows separate between training, validation and test samples, call
partition_population then generate_partitioned. The outcome values are in outcome.values
for binary, continuous and count outcomes, outcome.codes for ordered categories, and
outcome.time and outcome.event for time to event. Times are in days. The latent event time
(latent_event_time) and independent censoring time (censoring_time) are drawn before
applying the end of follow-up. Either is infinite if the corresponding event or censoring does
not occur by the last risk time.
Populations and sampling
Split feature data into disjoint pools and sample whole rows with source indices.
Population
dataclass
Store a non-empty feature matrix for sampling.
| Attributes: |
|
|---|
Use NaN for missing measurements. Infinite values raise ValueError.
sample_count
property
sample_count: int
Return the number of rows.
feature_count
property
feature_count: int
Return the number of columns.
ResampledPopulation
dataclass
Whole rows drawn from a feature matrix.
| Attributes: |
|
|---|
as_population
as_population() -> Population
Return a Population without the source indices.
PopulationPartition
dataclass
Disjoint fitting, tuning and test pools with identical columns.
| Attributes: |
|
|---|
Every original row index occurs once.
partition_population
partition_population(population: Population, *, training_fraction: float, validation_fraction: float, seed: int) -> PopulationPartition
Randomly split feature rows into disjoint training, validation and test pools.
The training and validation sizes are their fractions times the row count, rounded down. The remaining rows go to the test pool.
| Parameters: |
|
|---|
| Raises: |
|
|---|
resample_population
resample_population(population: Population, sample_size: int, rng: Generator) -> ResampledPopulation
Sample whole rows uniformly with replacement and return their zero-based source indices.
sample_population
sample_population(population: Population, sample_size: int, rng: Generator, *, method: SamplingMethod = 'with_replacement') -> ResampledPopulation
Draw whole rows uniformly and return them with zero-based source indices.
| Parameters: |
|
|---|
| Raises: |
|
|---|
Generation
Simulate outcomes on sampled rows, optionally in separate training, validation and test sets.
Plasmode
dataclass
Sampled features paired with simulated outcomes.
| Attributes: |
|
|---|
PartitionSampleSizes
dataclass
Positive row counts for drawing separate datasets.
| Attributes: |
|
|---|
PartitionedPlasmode
dataclass
Simulated datasets for fitting, tuning and testing drawn from separate source pools.
| Attributes: |
|
|---|
Indices can repeat within a dataset. Each Plasmode.source_indices refers to its pool.
generate
generate(population: Population, *, truth: TruthSpec, outcome: OutcomeSpec, sample_size: int, seed: int, sampling_method: SamplingMethod = 'with_replacement', feature_sets: FeatureSets | None = None) -> Plasmode
Draw feature rows, compute the generating score and simulate one outcome per row.
Returns the sampled rows, their outcomes, the generating score and the source row indices together.
| Parameters: |
|
|---|
| Raises: |
|
|---|
generate_partitioned
generate_partitioned(partition: PopulationPartition, *, truth: TruthSpec, outcome: OutcomeSpec, sample_sizes: PartitionSampleSizes, seed: int, sampling_method: SamplingMethod = 'with_replacement', feature_sets: FeatureSets | None = None) -> PartitionedPlasmode
Simulate outcomes on samples drawn from separate training, validation and test pools.
When generating features are chosen automatically, use the training pool. Pool the sampled rows in training, validation and test order for imputation, standardisation and calibration. Return three datasets with source-row indices and shared calibration diagnostics. Outcome targets apply to the pooled sample. Split-level summaries can differ.
| Parameters: |
|
|---|
| Raises: |
|
|---|
Signal specifications
Define the generating score, which outcomes are simulated from, and the recovery targets.
RecoveryGroup
dataclass
A group counted as found when at least one member is selected.
| Attributes: |
|
|---|
FeatureWeight
dataclass
A signed feature weight whose magnitude counts towards weighted recovery.
| Attributes: |
|
|---|
MaterializedTruth
dataclass
The generating score, one number per row, and the targets for scoring feature selection.
| Attributes: |
|
|---|
Unused target tuples are empty. For a score built by materialize_truth,
center and scale are both zero in the null case.
NullTruth
dataclass
A zero generating score.
SparseTruth
dataclass
Use a weighted sum of selected standardised features as the generating score.
Specify either feature IDs or a count. Automatic selection searches in seeded random
order and raises ValueError if it cannot find enough features within the correlation limit.
| Attributes: |
|
|---|
CorrelatedTruth
dataclass
Define the generating score as a weighted sum of contributions from disjoint groups.
A selection finds a group if it contains any member. The input data determines the correlations.
| Attributes: |
|
|---|
ModuleTruth
dataclass
Define a generating score as a weighted sum over a named set of standardised features.
| Attributes: |
|
|---|
Weighted recovery divides the sum of selected absolute weights by the total absolute weight.
InteractionTruth
dataclass
Define a generating score that depends jointly on two standardised features.
| Attributes: |
|
|---|
CustomSignal
dataclass
Supply a user-defined generating score and optional targets for feature selection.
| Attributes: |
|
|---|
All target feature IDs must occur in the input columns.
CustomTruth
dataclass
Define the generating score with a user-supplied function.
| Attributes: |
|
|---|
The callback must return the same CustomSignal contents for the same inputs and seed.
materialize_truth
materialize_truth(truth: TruthSpec, population: Population, *, seed: int, feature_sets: FeatureSets | None = None) -> MaterializedTruth
Compute the generating score and record the feature-selection targets.
Built-in specifications median-impute and standardise the feature columns they use. Non-null generating scores are standardised to mean zero and unit population standard deviation. Null scores are zero on every row.
| Parameters: |
|
|---|
| Raises: |
|
|---|
Outcome specifications and results
Specify and simulate binary, continuous, count, ordinal and time-to-event outcomes.
OutcomeSpecificationError
Bases: ValueError
Invalid outcome settings, such as out-of-range probabilities or conflicting effects.
CalibrationError
Bases: RuntimeError
The outcome model cannot use the supplied score or attain the requested targets.
RealizationError
Bases: RuntimeError
A simulated summary differs from its target by more than the sampling tolerance.
Duration
dataclass
A positive time interval, stored in days.
| Attributes: |
|
|---|
BinaryOutcome
dataclass
Specify a binary outcome with a target average event probability.
Set exactly one effect or AUC target. Effects are per standard deviation increase in the generating score. An AUC target sets an odds ratio of at least one.
| Attributes: |
|
|---|
ContinuousOutcome
dataclass
Specify a Gaussian outcome with a target mean and standard deviation.
Set exactly one of effect and variance_explained. Non-zero effects require a varying
generating score.
| Attributes: |
|
|---|
CountOutcome
dataclass
Specify event counts with an exposure-adjusted rate that depends on the generating score.
| Attributes: |
|
|---|
A ratio of one gives Poisson counts. A higher ratio gives overdispersed counts (NB1).
OrdinalOutcome
dataclass
Specify an ordered categorical outcome using a proportional odds model.
| Attributes: |
|
|---|
The odds ratio is per standard deviation increase in the generating score.
RiskPoint
dataclass
A cumulative probability of having an event or being censored by a given time.
| Attributes: |
|
|---|
TimeToEventOutcome
dataclass
Specify time-to-event outcomes with target cumulative event and censoring risks.
Pass risk curves as mappings from Duration to nondecreasing probabilities in [0, 1).
Set exactly one of hazard_ratio and target_auc. Hazards are constant between
risk points and zero after the final point.
| Attributes: |
|
|---|
The cutoff must cover all event-risk points. By default, AUC is evaluated at the last event-risk time strictly before the cutoff, or at half the cutoff if none precedes it. AUC uses the model's event probabilities with censoring removed.
CalibrationCheck
dataclass
A simulated summary checked against its target.
| Attributes: |
|
|---|
CalibrationResult
dataclass
Parameters and diagnostics for the model used to simulate outcomes.
| Attributes: |
|
|---|
Expected AUC compares risks over independent case-control draws, with half credit for ties.
For survival it uses uncensored risks at the AUC horizon. It is None when unavailable,
including when the model implies zero probability of a case or control.
parameter_dict
property
parameter_dict: dict[str, ParameterValue]
Return a fresh dictionary of model parameters.
BinaryGeneratedOutcome
dataclass
Simulated binary outcomes for the input rows.
| Attributes: |
|
|---|
ContinuousGeneratedOutcome
dataclass
Simulated continuous outcomes for the input rows.
| Attributes: |
|
|---|
CountGeneratedOutcome
dataclass
Simulated event counts and their exposures.
| Attributes: |
|
|---|
OrdinalGeneratedOutcome
dataclass
Simulated ordered categories for the input rows.
| Attributes: |
|
|---|
SurvivalGeneratedOutcome
dataclass
Simulated event times, censoring times and observed follow-up.
| Attributes: |
|
|---|
The read-only arrays follow input row order.
duration
duration(value: float, unit: Literal['days', 'weeks', 'years']) -> Duration
Convert a positive duration to days (7 per week, 365.25 per year).
days
days(value: float) -> Duration
Create a positive duration from a day count.
years
years(value: float) -> Duration
Convert a positive year count using 365.25 days per year.
generate_outcome
generate_outcome(spec: OutcomeSpec, signal: NDArray[float64], rng: Generator) -> GeneratedOutcome
Calibrate the model and draw one outcome per input row.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Feature sets and graphs
Feature sets, graphs and alignment to measured columns.
StructureAlignment
dataclass
Feature IDs shared by or unique to a declaration and a feature matrix.
| Attributes: |
|
|---|
FeatureSet
dataclass
A named set of features.
name is non-empty with no surrounding whitespace; members is a non-empty tuple of unique
feature IDs.
FeatureSets
dataclass
Store named feature groups for defining the generating score.
| Attributes: |
|
|---|
Groups may overlap. CorrelatedTruth requires its chosen groups to be disjoint.
get
get(name: str) -> FeatureSet
Return the feature set with the given name or raise ValueError if it is unknown.
align
align(population: Population) -> StructureAlignment
Report which IDs are in both the sets and the population, and which are in only one.
FeatureEdge
dataclass
An undirected connection between two features.
| Attributes: |
|
|---|
FeatureGraph
dataclass
Undirected graph for scoring feature recovery.
| Attributes: |
|
|---|
align
align(population: Population) -> StructureAlignment
Report which IDs are in both the graph and the population, and which are in only one.
Ranking and prediction evaluation
Feature recovery, prediction and ranking stability evaluation.
evaluate_ranking
evaluate_ranking(ranking: tuple[str, ...], truth: MaterializedTruth, *, depths: tuple[int, ...]) -> RankingEvaluation
Measure how many of the signal's exact targets appear in the top features of a ranking.
The exact targets are truth.direct_features. Each depth gets the count found, precision,
recall and false discovery fraction.
| Parameters: |
|
|---|
| Raises: |
|
|---|
evaluate_groups
evaluate_groups(ranking: tuple[str, ...], truth: MaterializedTruth, *, depths: tuple[int, ...]) -> GroupEvaluation
Count target groups with at least one member among the top-ranked features.
| Parameters: |
|
|---|
| Raises: |
|
|---|
evaluate_module
evaluate_module(ranking: tuple[str, ...], truth: MaterializedTruth, *, depths: tuple[int, ...]) -> ModuleEvaluation
Measure the share of total absolute weight carried by the top features of a ranking.
At each depth, the selected absolute weights in truth.weights are divided by their total.
| Parameters: |
|
|---|
| Raises: |
|
|---|
evaluate_graph_region
evaluate_graph_region(ranking: tuple[str, ...], graph: FeatureGraph, *, region: tuple[str, ...], depths: tuple[int, ...]) -> GraphRegionEvaluation
Measure how much of a set of graph nodes the top features of a ranking contain.
At each depth, node coverage is the fraction of region nodes selected. Edge coverage is the
fraction of edges joining two region nodes with both ends selected, counting every edge
equally. Weighted edge coverage is the same fraction by edge weight: the summed weight of
those recovered edges divided by the summed weight of all such edges. Edge coverage is None
if the region has no such edges, and weighted edge coverage is also None if their weights
sum to zero.
| Parameters: |
|
|---|
| Returns: |
|
|---|
evaluate_signal_reconstruction
evaluate_signal_reconstruction(X: ArrayLike, feature_ids: tuple[str, ...], *, selected_features: tuple[str, ...], signal: ArrayLike, development_indices: ArrayLike, evaluation_indices: ArrayLike) -> SignalReconstructionEvaluation
Test how well a panel of selected features predicts the generating score on held-out rows.
A linear model is fitted on the fitting rows; R-squared and RMSE are computed on the held-out rows.
Fill missing values with fitting-row medians. Drop columns that are entirely missing in the
fitting rows. If the panel is non-empty but every column is dropped, raise ValueError.
An empty panel predicts the mean generating score of the fitting rows.
| Parameters: |
|
|---|
| Raises: |
|
|---|
evaluate_prediction
evaluate_prediction(target: ArrayLike, prediction: ArrayLike, *, metric: PredictionMetric) -> PredictionEvaluation
Score predictions against observed outcomes with one metric.
| Parameters: |
|
|---|
| Raises: |
|
|---|
evaluate_panel
evaluate_panel(target: ArrayLike, reference_prediction: ArrayLike, panel_prediction: ArrayLike, *, metric: PredictionMetric) -> PanelEvaluation
Compare a panel model's predictions with a reference model's on the same observations.
Returns both metric values and their difference, the panel value minus the reference value.
| Parameters: |
|
|---|
rank_stability
rank_stability(rankings: tuple[tuple[str, ...], ...], *, depth: int, persistence: float = 0.9) -> RankStabilityEvaluation
Measure how closely two or more complete rankings of the same features agree.
Every pair of rankings is compared and the results averaged: Jaccard overlap and shared-feature count at each depth, with the overlap expected from independent random rankings, and Spearman correlation and rank-biased overlap over the complete rankings.
| Parameters: |
|
|---|
summarize_replicates
summarize_replicates(values: ArrayLike, *, failure_count: int = 0) -> ReplicateSummary
Summarise estimates from independent simulations with a 95% t interval for the mean.
| Parameters: |
|
|---|
compare_paired_replicates
compare_paired_replicates(left_ids: tuple[str, ...], left_values: Sequence[float | None], right_ids: tuple[str, ...], right_values: Sequence[float | None], *, allow_unmatched: bool = False) -> PairedReplicateComparison
Compare procedures on the same simulated datasets using right-minus-left differences.
Use only jointly successful pairs. Selective failures can bias the overall comparison.
| Parameters: |
|
|---|
| Raises: |
|
|---|
Tied selections and matched references
When features tie at the cutoff of a selection, these functions split the remaining places among them. They also compute the recovery expected by chance, from random selections that keep the observed selection probabilities within each matching group (Matched chance recovery).
Feature selections with tied scores and recovery against matched random selection.
FractionalNomination
dataclass
A feature selection that splits the last slots equally among features tied at the cutoff.
| Attributes: |
|
|---|
The probabilities sum to the smaller of the requested slots and the positive-score count.
achieved_size
property
achieved_size: int
Count features with positive selection probability.
selected_features
property
selected_features: tuple[str, ...]
Return the IDs with positive selection probability, in input order.
A tie at the cutoff gives more IDs than the requested depth.
membership_budget
property
membership_budget: float
Sum the selection probabilities.
nomination_from_scores
nomination_from_scores(feature_ids: tuple[str, ...], scores: ArrayLike, *, depth: int) -> FractionalNomination
Select the highest positive scores, splitting the remaining slots equally at a tie.
| Parameters: |
|
|---|
| Returns: |
|
|---|
evaluate_fractional_recovery
evaluate_fractional_recovery(nomination: FractionalNomination, truth: MaterializedTruth, *, estimand: RecoveryEstimand, allow_subset: bool = False) -> FractionalRecovery
Score how well a selection finds known targets, averaging over uniform tie-breaking.
| Parameters: |
|
|---|
| Raises: |
|
|---|
sample_matched_nominations
sample_matched_nominations(nomination: FractionalNomination, *, strata: tuple[str, ...], draws: int, seed: int) -> tuple[FractionalNomination, ...]
Draw random selections that match the observed one within each matching group (strata).
Each draw keeps the number of positive scores and the selection probabilities assigned within every group.
| Parameters: |
|
|---|
| Raises: |
|
|---|
evaluate_matched_recovery
evaluate_matched_recovery(nomination: FractionalNomination, truth: MaterializedTruth, *, estimand: RecoveryEstimand, strata: tuple[str, ...], allow_subset: bool = False) -> MatchedRecovery
Measure recovery above chance: observed recovery minus that of matched random selection.
Returns the observed recovery, its expectation under matched random selection and their difference, which is negative when the selection does worse than chance.
Calculate chance recovery analytically by reassigning positive-score status and selection
probabilities within each matching group (strata), preserving their counts and values.
| Parameters: |
|
|---|
| Raises: |
|
|---|
evaluate_outcome_specificity
evaluate_outcome_specificity(nomination: FractionalNomination, own_truth: MaterializedTruth, foreign_truths: tuple[MaterializedTruth, ...], *, estimand: RecoveryEstimand, strata: tuple[str, ...], allow_subset: bool = False) -> OutcomeSpecificity
Compare recovery above chance for the outcome's own targets and alternative targets.
Recovery above chance is observed minus expected recovery under matched random selection. Use the same selection and matching groups for every set of targets. Return the outcome's recovery above chance, the mean over alternatives and the difference between the two.
| Parameters: |
|
|---|
| Raises: |
|
|---|
Evaluation results
Results returned by prediction, feature-recovery and stability evaluators.
RankingAtDepth
dataclass
Exact-target recovery for the leading features of a ranking.
| Attributes: |
|
|---|
RankingEvaluation
dataclass
Results for finding exact target features in a ranking.
| Attributes: |
|
|---|
GroupAtDepth
dataclass
Group recovery at one depth.
| Attributes: |
|
|---|
GroupEvaluation
dataclass
Group recovery across depths.
| Attributes: |
|
|---|
ModuleAtDepth
dataclass
Weight recovered by the leading features of a ranking.
| Attributes: |
|
|---|
ModuleEvaluation
dataclass
Weighted recovery across depths.
| Attributes: |
|
|---|
GraphRegionAtDepth
dataclass
Recovery of a graph region by the first depth features of a ranking.
| Attributes: |
|
|---|
GraphRegionEvaluation
dataclass
Graph region recovery across depths.
| Attributes: |
|
|---|
SignalReconstructionEvaluation
dataclass
Held-out performance of a linear model that predicts the generating score from a panel.
| Attributes: |
|
|---|
PredictionEvaluation
dataclass
Metric name, metric value and number of observations scored.
PanelEvaluation
dataclass
Prediction scores for a panel and a reference model.
| Attributes: |
|
|---|
RankStabilityEvaluation
dataclass
Agreement averaged over pairs of feature rankings.
| Attributes: |
|
|---|
ReplicateSummary
dataclass
Mean and uncertainty across independent successful simulations.
| Attributes: |
|
|---|
PairedReplicateComparison
dataclass
Differences between two procedures evaluated on the same simulated datasets.
| Attributes: |
|
|---|
FractionalRecovery
dataclass
Recovery averaged over ties at the selection cutoff.
| Attributes: |
|
|---|
Exact recovery averages selection probability over targets. Group recovery averages the chance of any hit over groups. Module recovery divides expected selected absolute weight by total absolute weight. Interaction recovery is the chance of selecting both targets.
MatchedRecovery
dataclass
Feature recovery compared with random selection within matching groups.
| Attributes: |
|
|---|
OutcomeSpecificity
dataclass
Recovery above chance for the outcome's targets compared with alternatives.
| Attributes: |
|
|---|
Selection agreement and censored discrimination
Selection agreement, censoring-aware discrimination and participant uncertainty.
Rankings and predictions must already share feature or participant identities.
SelectionStability
dataclass
Agreement of feature selections across refits after accounting for chance.
| Attributes: |
|
|---|
The score is None when every refit selects nothing or every refit selects all features.
ConsensusRanking
dataclass
Ordering by mean selection probability, then median rank.
| Attributes: |
|
|---|
BootstrapDifference
dataclass
Paired bootstrap difference and percentile interval.
| Attributes: |
|
|---|
DiscriminationGap
dataclass
Difference in AUC between the generating model and a fitted model on the same outcomes.
| Attributes: |
|
|---|
selection_stability
selection_stability(nominations: Sequence[FractionalNomination]) -> SelectionStability
Measure how consistently refits select the same features above chance.
The Nogueira score is one minus the mean across features of the sample variance of their
selection indicators across refits, divided by p * (1 - p), where p is the mean fraction of
features selected per refit.
It averages over independent uniform resolutions of ties at each cutoff. It is negative
when observed variance exceeds chance. Unequal numbers of slots cap the score below one.
| Parameters: |
|
|---|
rank_biased_overlap
rank_biased_overlap(left_ranks: ArrayLike, right_ranks: ArrayLike, *, persistence: float = 0.9, tie_method: Literal['webber', 'independent'] = 'webber') -> float
Measure agreement between two rankings, giving the top positions more weight.
| Parameters: |
|
|---|
| Returns: |
|
|---|
consensus_ranking
consensus_ranking(feature_ids: tuple[str, ...], scores: ArrayLike, *, depth: int) -> ConsensusRanking
Combine the feature selections of several refits into one ranking.
Features are ordered by mean selection probability across refits. Ties are broken by median within-refit rank over the refits in which the feature had positive selection probability.
Positive ties at the cutoff share the remaining slots equally.
| Parameters: |
|
|---|
cumulative_dynamic_auc
cumulative_dynamic_auc(training_time: ArrayLike, training_event: ArrayLike, time: ArrayLike, event: ArrayLike, risk: ArrayLike, *, horizon: float, tied_tolerance: float = 0.0) -> float
Measure how well risk scores separate events by a cutoff from known event-free observations.
Cases have an observed event by the cutoff. Controls have follow-up beyond it. Censoring by the cutoff is excluded. Under independent censoring, each case is weighted by the inverse probability of remaining uncensored at its event time, estimated by reverse Kaplan-Meier on the training rows. Administrative follow-up must extend beyond the evaluation horizon.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
paired_bootstrap_difference
paired_bootstrap_difference(participants: int | Sequence[str] | NDArray[str_], statistic: Callable[[NDArray[int64]], tuple[float, float] | None], *, resamples: int = 1000, confidence_level: float = 0.95, seed: int = 0) -> BootstrapDifference
Estimate uncertainty for a metric difference using shared participant resamples.
Draw the original number of rows with replacement and return the right-minus-left metric difference with a percentile interval over successful draws. For uncertainty on fixed models, keep fitted models and training data fixed. Recompute any evaluation quantities that depend on the resampled rows in the callback, such as the evaluation sample's mean outcome used as a baseline.
| Parameters: |
|
|---|
| Raises: |
|
|---|
discrimination_gap
discrimination_gap(oracle_risk: ArrayLike, fitted_risk: ArrayLike, *, metric: Callable[[ArrayLike], float]) -> DiscriminationGap
Compare the AUC of the generating score with the AUC of a fitted model on the same rows.
The same AUC function is applied to both sets of risk scores. Returns both AUCs and the generating score's AUC minus the fitted model's.
| Parameters: |
|
|---|
A finite sample may give a negative gap.