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_ids gives 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.asdict turns 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:
  • X (NDArray[float64]) –

    Read-only numeric matrix, observations by features.

  • feature_ids (tuple[str, ...]) –

    Unique column IDs, non-empty strings without surrounding whitespace.

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:
  • X (NDArray[float64]) –

    Read-only matrix of sampled rows in draw order.

  • feature_ids (tuple[str, ...]) –

    Feature IDs in column order.

  • source_indices (NDArray[int64]) –

    Read-only zero-based indices into the input matrix. Repeats are allowed.

as_population

as_population() -> Population

Return a Population without the source indices.

PopulationPartition dataclass

Disjoint fitting, tuning and test pools with identical columns.

Attributes:
  • training (Population) –

    Rows for fitting.

  • validation (Population) –

    Rows for tuning.

  • evaluation (Population) –

    Rows for testing.

  • training_source_indices (NDArray[int64]) –

    Original training row indices, zero-based.

  • validation_source_indices (NDArray[int64]) –

    Original validation row indices, zero-based.

  • evaluation_source_indices (NDArray[int64]) –

    Original test row indices, zero-based.

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:
  • training_fraction (float) –

    Positive training fraction.

  • validation_fraction (float) –

    Positive validation fraction. The fractions must sum to less than one.

  • seed (int) –

    Non-negative integer for shuffling rows.

Raises:
  • ValueError –

    The seed or fractions are invalid, or the requested split leaves a pool empty.

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:
  • sample_size (int) –

    Positive number of rows to draw.

  • method (SamplingMethod, default: 'with_replacement' ) –

    "with_replacement" allows repeats. "without_replacement" draws distinct rows.

Raises:
  • ValueError –

    The size is not a positive integer, the method is unsupported, or a draw without replacement exceeds the available row count.

Generation

Simulate outcomes on sampled rows, optionally in separate training, validation and test sets.

Plasmode dataclass

Sampled features paired with simulated outcomes.

Attributes:
  • X (NDArray[float64]) –

    Feature matrix in draw order. Generation functions return it read-only.

  • feature_ids (tuple[str, ...]) –

    Feature IDs in column order.

  • outcome (GeneratedOutcome) –

    Simulated outcomes in row order, with model parameters.

  • truth (MaterializedTruth) –

    The generating score and its recovery targets.

  • source_indices (NDArray[int64]) –

    Zero-based row indices into this sample's input pool.

  • seed (int) –

    Generation seed for generate, or this pool's row-sampling seed for a split dataset.

  • sampling_method (SamplingMethod) –

    Whether source rows were drawn with or without replacement.

PartitionSampleSizes dataclass

Positive row counts for drawing separate datasets.

Attributes:
  • training (int) –

    Row count for fitting.

  • validation (int) –

    Row count for tuning.

  • evaluation (int) –

    Row count for testing.

PartitionedPlasmode dataclass

Simulated datasets for fitting, tuning and testing drawn from separate source pools.

Attributes:
  • training (Plasmode) –

    Dataset for fitting.

  • validation (Plasmode) –

    Dataset for tuning.

  • evaluation (Plasmode) –

    Dataset for testing.

  • training_source_indices (NDArray[int64]) –

    Original training row indices, zero-based.

  • validation_source_indices (NDArray[int64]) –

    Original validation row indices, zero-based.

  • evaluation_source_indices (NDArray[int64]) –

    Original test row indices, zero-based.

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:
  • truth (TruthSpec) –

    Generating score and recovery targets to compute from the sampled rows.

  • outcome (OutcomeSpec) –

    Outcome family and its calibration settings.

  • sample_size (int) –

    Positive number of feature rows to draw.

  • seed (int) –

    Non-negative seed for sampling rows, choosing features and drawing outcomes.

  • sampling_method (SamplingMethod, default: 'with_replacement' ) –

    Whether repeats are allowed when drawing rows.

  • feature_sets (FeatureSets | None, default: None ) –

    Named feature groups required by CorrelatedTruth and ModuleTruth.

Raises:
  • ValueError –

    Invalid generation, sampling or outcome settings, or an infeasible draw or generating score.

  • TypeError –

    The truth or outcome specification type is unsupported.

  • CalibrationError –

    Outcome targets are unattainable.

  • RealizationError –

    The simulated outcomes fail a sampling diagnostic.

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:
  • truth (TruthSpec) –

    Built-in signal structure and recovery targets.

  • outcome (OutcomeSpec) –

    Outcome targets for the combined sample.

  • seed (int) –

    Non-negative seed for rows, features and outcomes.

  • sampling_method (SamplingMethod, default: 'with_replacement' ) –

    Whether to draw the rows in each pool with replacement.

  • feature_sets (FeatureSets | None, default: None ) –

    Named feature groups required by CorrelatedTruth and ModuleTruth.

Raises:
  • ValueError –

    Invalid generation, sampling or outcome settings, a custom signal, or an infeasible draw or generating score.

  • TypeError –

    The truth or outcome specification type is unsupported.

  • CalibrationError –

    Outcome targets are unattainable.

  • RealizationError –

    The combined outcomes fail a sampling diagnostic.

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:
  • name (str) –

    Group identifier.

  • direct_feature (str | None) –

    Designated generating feature, or None if there is none.

  • features (tuple[str, ...]) –

    Unique eligible feature IDs, including the direct feature if designated.

FeatureWeight dataclass

A signed feature weight whose magnitude counts towards weighted recovery.

Attributes:
  • feature (str) –

    Feature ID.

  • weight (float) –

    Finite, non-zero weight. In built-in additive generating scores it multiplies a standardised feature before the score itself is standardised.

MaterializedTruth dataclass

The generating score, one number per row, and the targets for scoring feature selection.

Attributes:
  • kind (TruthKind) –

    Signal structure, such as "sparse" or "custom".

  • signal (NDArray[float64]) –

    Read-only score in input row order.

  • feature_universe (tuple[str, ...]) –

    All input feature IDs in column order.

  • direct_features (tuple[str, ...]) –

    IDs counted as exact selection targets.

  • admissible_groups (tuple[RecoveryGroup, ...]) –

    Groups credited when a selection includes any member.

  • weights (tuple[FeatureWeight, ...]) –

    Signed coefficients for scoring coverage by absolute weight.

  • graph_region (tuple[str, ...]) –

    Target graph node IDs.

  • center (float) –

    Mean before score standardisation.

  • scale (float) –

    Population standard deviation before score standardisation.

  • description (str) –

    Label for the signal structure.

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:
  • count (int | None) –

    Number of features to pick automatically.

  • features (tuple[str, ...]) –

    Unique IDs of explicitly chosen features, also the exact selection targets.

  • weights (tuple[float, ...]) –

    Finite, non-zero coefficients in explicit feature order, defaulting to one.

  • max_absolute_correlation (float) –

    Maximum absolute Pearson correlation between any two automatically chosen features, in [0, 1). Ignored when features is supplied.

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:
  • group_names (tuple[str, ...]) –

    Names of the groups in FeatureSets, in coefficient order.

  • sentinels (tuple[str, ...]) –

    One generating feature per group, in group_names order. In "sentinels" mode an empty tuple picks one member per group using the seed. The generating features are the exact recovery targets in this mode. Leave empty in "group_means" mode.

  • weights (tuple[float, ...]) –

    Finite, non-zero coefficients in group_names order, defaulting to one.

  • signal_form (Literal['sentinels', 'group_means']) –

    "sentinels" uses the standardised value of each chosen feature. "group_means" uses the mean of each group's standardised features.

ModuleTruth dataclass

Define a generating score as a weighted sum over a named set of standardised features.

Attributes:
  • set_name (str) –

    Name of the set in FeatureSets.

  • weights (tuple[float, ...]) –

    Finite, non-zero coefficients in set order, defaulting to one.

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:
  • features (tuple[str, str]) –

    Two distinct feature IDs that form the joint selection target.

  • operation (Literal['product', 'threshold']) –

    "product" multiplies values. "threshold" tests if both exceed the cutoff.

  • threshold (float) –

    Finite cutoff in feature standard deviations. With "threshold", the indicator is one when both standardised values exceed the cutoff and zero otherwise. The indicator is then standardised to form the generating score. A constant indicator raises ValueError during generation.

CustomSignal dataclass

Supply a user-defined generating score and optional targets for feature selection.

Attributes:
  • signal (NDArray[float64]) –

    Finite, non-constant score with one value per input row.

  • direct_features (tuple[str, ...]) –

    Feature IDs counted as exact targets.

  • groups (tuple[RecoveryGroup, ...]) –

    Groups credited when any member is selected.

  • weights (tuple[FeatureWeight, ...]) –

    Signed coefficients used to score coverage by absolute weight.

  • graph_region (tuple[str, ...]) –

    Target feature IDs for graph scoring.

  • description (str) –

    Optional label for the signal structure.

All target feature IDs must occur in the input columns.

CustomTruth dataclass

Define the generating score with a user-supplied function.

Attributes:
  • function (CustomTruthFunction) –

    Callback taking a read-only matrix, column IDs and a seeded NumPy generator.

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:
  • truth (TruthSpec) –

    Built-in signal specification or a CustomTruth wrapping a callback.

  • seed (int) –

    Non-negative integer for automatic choices or the custom callback.

  • feature_sets (FeatureSets | None, default: None ) –

    Named feature groups required by correlated and module specifications.

Raises:
  • ValueError –

    Invalid settings or targets, an infeasible automatic selection, a non-finite or constant non-null generating score, or a custom callback that returns the wrong shape or differs between identical calls.

  • TypeError –

    The specification type is unsupported.

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:
  • days (float) –

    Finite positive length.

  • label (str) –

    Non-empty display label.

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:
  • probability (float) –

    Mean event probability across rows, in (0, 1).

  • odds_ratio (float | None) –

    Positive finite event odds multiplier.

  • risk_ratio (float | None) –

    Positive finite event probability multiplier.

  • risk_difference (float | None) –

    Finite change in event probability.

  • target_auc (float | None) –

    Expected AUC of model-implied risks, in [0.5, 1).

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:
  • mean (float) –

    Finite mean in outcome units.

  • standard_deviation (float) –

    Positive standard deviation in outcome units.

  • effect (float | None) –

    Change in the mean per standard deviation of the generating score. Its magnitude must be smaller than standard_deviation.

  • variance_explained (float | None) –

    Variance fraction in [0, 1), giving a non-negative effect.

CountOutcome dataclass

Specify event counts with an exposure-adjusted rate that depends on the generating score.

Attributes:
  • rate (float) –

    Expected total count divided by total exposure, finite and positive.

  • rate_ratio (float) –

    Positive finite rate multiplier per score standard deviation.

  • exposure (float | tuple[float, ...]) –

    Finite positive amounts, shared or one per row, in the rate denominator units.

  • variance_to_mean (float) –

    Finite conditional variance-to-mean ratio, at least one.

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:
  • categories (tuple[str, ...]) –

    At least two distinct labels, ordered lowest to highest.

  • probabilities (tuple[float, ...]) –

    Positive probabilities in category order, summing to one.

  • common_odds_ratio (float) –

    Positive finite multiplier on the odds of exceeding any category cutoff.

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:
  • horizon (Duration) –

    Elapsed time as a Duration.

  • probability (float) –

    Cumulative probability, in [0, 1) for TimeToEventOutcome.

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:
  • event_risks (tuple[RiskPoint, ...]) –

    Non-empty series of cumulative event probabilities before censoring.

  • hazard_ratio (float | None) –

    Positive finite hazard multiplier per score standard deviation.

  • censoring_risks (tuple[RiskPoint, ...]) –

    Independent censoring risks at the same times, defaulting to zero.

  • target_auc (float | None) –

    Expected AUC in [0.5, 1), used to set a hazard ratio of at least one.

  • auc_horizon (Duration) –

    Time at which AUC is calibrated or reported, strictly before the cutoff.

  • administrative_horizon (Duration) –

    Follow-up cutoff. Defaults to the last event-risk time.

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:
  • name (str) –

    Summary name.

  • target (float) –

    Requested value.

  • expected (float) –

    Model-implied population summary over the calibration rows, before sampling outcomes.

  • realized (float) –

    Summary from the simulated draw.

  • tolerance (float) –

    Maximum absolute difference from target, in the summary's units.

  • within_tolerance (bool) –

    Whether the draw met that bound. After calibration, a draw outside the bound raises RealizationError, so returned checks have this flag set to True.

CalibrationResult dataclass

Parameters and diagnostics for the model used to simulate outcomes.

Attributes:
  • family (str) –

    Outcome model family.

  • parameters (tuple[tuple[str, ParameterValue], ...]) –

    Parameter names and values.

  • checks (tuple[CalibrationCheck, ...]) –

    Comparisons of targets, model expectations and simulated summaries.

  • oracle_auc (float | None) –

    Expected AUC of model-implied risk for binary or survival outcomes.

  • target_auc (float | None) –

    Requested expected AUC, or None if no AUC was requested.

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:
  • values (NDArray[int8]) –

    Read-only vector, zero for non-events and one for events.

  • calibration (CalibrationResult) –

    Model parameters, event-probability check and expected AUC.

ContinuousGeneratedOutcome dataclass

Simulated continuous outcomes for the input rows.

Attributes:
  • values (NDArray[float64]) –

    Read-only vector in the units of the specified outcome mean.

  • calibration (CalibrationResult) –

    Model parameters and checks on mean and standard deviation.

CountGeneratedOutcome dataclass

Simulated event counts and their exposures.

Attributes:
  • values (NDArray[int64]) –

    Read-only vector of non-negative integer counts, one per row.

  • exposure (NDArray[float64]) –

    Read-only exposure amounts in the supplied units, one per row.

  • calibration (CalibrationResult) –

    Model parameters and rate check.

OrdinalGeneratedOutcome dataclass

Simulated ordered categories for the input rows.

Attributes:
  • codes (NDArray[int64]) –

    Read-only vector of zero-based indices into categories.

  • categories (tuple[str, ...]) –

    Labels in lowest-to-highest order.

  • calibration (CalibrationResult) –

    Model parameters and category proportion checks.

SurvivalGeneratedOutcome dataclass

Simulated event times, censoring times and observed follow-up.

Attributes:
  • time (NDArray[float64]) –

    Days to the first of event, independent censoring or administrative cutoff.

  • event (NDArray[bool_]) –

    True when the event occurs by both censoring and the administrative cutoff.

  • latent_event_time (NDArray[float64]) –

    Days to event before applying censoring, or infinity if none occurred.

  • censoring_time (NDArray[float64]) –

    Days to independent censoring, or infinity if none occurred.

  • calibration (CalibrationResult) –

    Model parameters, risk checks and expected AUC.

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:
  • signal (NDArray[float64]) –

    Finite, non-empty generating-score vector in row order. Rescaled to mean zero and unit population standard deviation, or replaced with zeros if constant.

Returns:
  • GeneratedOutcome –

    Read-only outcome arrays and model diagnostics. Survival times are in days.

Raises:
  • OutcomeSpecificationError –

    Exposure vector length differs from the score length, or Gaussian generation has fewer than two rows or a non-zero effect with a constant score.

  • CalibrationError –

    The model cannot use the score or attain the requested targets.

  • RealizationError –

    Simulated summaries exceed their sampling tolerance.

  • TypeError –

    The outcome specification type is unsupported.

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:
  • mapped (tuple[str, ...]) –

    Declared IDs found in the matrix, in column order.

  • unmapped (tuple[str, ...]) –

    Declared IDs missing from the matrix, sorted by ID.

  • excluded (tuple[str, ...]) –

    Matrix IDs absent from the declaration, in column order.

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:
  • sets (tuple[FeatureSet, ...]) –

    Non-empty collection of uniquely named groups.

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:
  • source (str) –

    One endpoint. Direction carries no meaning; an edge and its reverse are the same.

  • target (str) –

    The other endpoint, different from source.

  • weight (float) –

    Finite, non-negative strength of the connection (default 1.0), used by weighted_edge_coverage in evaluate_graph_region.

FeatureGraph dataclass

Undirected graph for scoring feature recovery.

Attributes:
  • nodes (tuple[str, ...]) –

    Non-empty tuple of unique feature IDs.

  • edges (tuple[FeatureEdge, ...]) –

    Distinct undirected edges between those IDs. An empty tuple is allowed.

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:
  • ranking (tuple[str, ...]) –

    Every input feature ID once, most important first.

  • depths (tuple[int, ...]) –

    Non-empty tuple of strictly increasing cutoffs from one to the feature count.

Raises:
  • ValueError –

    The ranking or depths are invalid, or direct_features is empty.

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:
  • ranking (tuple[str, ...]) –

    Every input feature ID once, most important first.

  • depths (tuple[int, ...]) –

    Non-empty tuple of strictly increasing cutoffs from one to the feature count.

Raises:
  • ValueError –

    The ranking or depths are invalid, or the signal defines no target groups.

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:
  • ranking (tuple[str, ...]) –

    Every input feature ID once, most important first.

  • depths (tuple[int, ...]) –

    Non-empty tuple of strictly increasing cutoffs from one to the feature count.

Raises:
  • ValueError –

    The ranking or depths are invalid, or the signal defines no feature weights.

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:
  • ranking (tuple[str, ...]) –

    Every node of graph once, most important first.

  • region (tuple[str, ...]) –

    The nodes to look for, a non-empty subset of the graph's nodes.

  • depths (tuple[int, ...]) –

    Non-empty tuple of strictly increasing cutoffs from one to the node count.

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:
  • X (ArrayLike) –

    Feature matrix with observations in rows.

  • feature_ids (tuple[str, ...]) –

    Unique IDs in column order.

  • selected_features (tuple[str, ...]) –

    Unique IDs of the columns used for prediction.

  • signal (ArrayLike) –

    Finite generating score in row order.

  • development_indices (ArrayLike) –

    Distinct zero-based row indices for fitting.

  • evaluation_indices (ArrayLike) –

    Distinct zero-based test indices, disjoint from the fitting rows.

Raises:
  • ValueError –

    The inputs are invalid, the fitting and test rows overlap, or the held-out generating score has fewer than two distinct values.

evaluate_prediction

evaluate_prediction(target: ArrayLike, prediction: ArrayLike, *, metric: PredictionMetric) -> PredictionEvaluation

Score predictions against observed outcomes with one metric.

Parameters:
  • target (ArrayLike) –

    Finite outcome vector in prediction order. Classification labels are zero or one.

  • prediction (ArrayLike) –

    Finite vector in target order. Supply class-one probabilities for log loss. Higher scores predict class one for AUC and average precision.

  • metric (PredictionMetric) –

    "roc_auc", "average_precision", "log_loss", "r2" or "rmse".

Raises:
  • ValueError –

    AUC lacks either class, average precision lacks positives, log loss receives values outside [0, 1], or R-squared has fewer than two distinct outcomes.

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:
  • reference_prediction (ArrayLike) –

    Reference model predictions in target order.

  • panel_prediction (ArrayLike) –

    Panel predictions in target order.

  • metric (PredictionMetric) –

    Scoring rule, with the same input requirements as evaluate_prediction.

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:
  • rankings (tuple[tuple[str, ...], ...]) –

    At least two rankings of the same two or more features, most important first.

  • depth (int) –

    Number of leading features per ranking, from one to the feature count.

  • persistence (float, default: 0.9 ) –

    Rank-biased overlap parameter in (0, 1). Smaller values weight the top more.

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:
  • values (ArrayLike) –

    One finite estimate per successful simulation, with at least two estimates.

  • failure_count (int, default: 0 ) –

    Non-negative count of omitted failed simulations.

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:
  • left_ids (tuple[str, ...]) –

    Unique IDs of the independent datasets scored by the left procedure.

  • left_values (Sequence[float | None]) –

    Finite estimates in left ID order, with None for failures.

  • right_ids (tuple[str, ...]) –

    Unique IDs of the independent datasets scored by the right procedure.

  • right_values (Sequence[float | None]) –

    Finite estimates in right ID order, with None for failures.

  • allow_unmatched (bool, default: False ) –

    Use shared IDs and report unmatched counts. By default ID sets must match.

Raises:
  • ValueError –

    Invalid or unmatched IDs (unless unmatched IDs are allowed), invalid values, or fewer than two pairs that succeed on both sides.

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:
  • feature_ids (tuple[str, ...]) –

    Unique candidate IDs in membership vector order.

  • membership (NDArray[float64]) –

    Read-only selection probability in [0, 1] for each candidate.

  • requested_depth (int) –

    Number of slots requested, from one to the candidate count.

  • positive_support (tuple[str, ...]) –

    All IDs with positive importance scores, even below the cutoff.

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:
  • feature_ids (tuple[str, ...]) –

    Unique candidate IDs in score order.

  • scores (ArrayLike) –

    Finite, non-negative importance scores.

  • depth (int) –

    Number of slots requested, from one to the feature count.

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:
  • nomination (FractionalNomination) –

    Selection with candidate IDs in the same order as the truth's feature IDs.

  • truth (MaterializedTruth) –

    Recovery targets used to score the selection.

  • estimand (RecoveryEstimand) –

    "exact" averages selection probabilities across exact targets, "group" averages the probability of selecting any member per group, "module" gives the fraction of absolute weight expected to be selected, and "interaction" gives the probability of selecting both exact targets.

  • allow_subset (bool, default: False ) –

    Allow any subset or reordering of the input feature IDs. Features omitted from the candidates have zero selection probability, and all targets remain in scope.

Raises:
  • ValueError –

    Candidate IDs do not match the input feature IDs under allow_subset, or the requested recovery measure is unsupported or has no valid targets.

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:
  • strata (tuple[str, ...]) –

    Non-empty group labels in feature order, independent of outcomes and targets.

  • draws (int) –

    Positive number of independent selections.

  • seed (int) –

    Non-negative integer for random assignments.

Raises:
  • ValueError –

    Invalid strata, draw count or seed.

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:
  • truth (MaterializedTruth) –

    Known targets for scoring the selection.

  • estimand (RecoveryEstimand) –

    Recovery measure as in evaluate_fractional_recovery.

  • strata (tuple[str, ...]) –

    Non-empty group labels in feature order, independent of outcomes and targets.

  • allow_subset (bool, default: False ) –

    Allow any subset or reordering of the input feature IDs. Omitted features have zero selection probability in observed and chance recovery.

Raises:
  • ValueError –

    The strata, candidate IDs or recovery targets are incompatible.

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:
  • own_truth (MaterializedTruth) –

    Generating score and recovery targets for the simulated outcome.

  • foreign_truths (tuple[MaterializedTruth, ...]) –

    Alternative signals with the same kind, ordered feature IDs and target count for estimand, and disjoint target features.

  • estimand (RecoveryEstimand) –

    Recovery measure as in evaluate_fractional_recovery.

  • strata (tuple[str, ...]) –

    Non-empty group labels in feature order, independent of outcomes and targets.

  • allow_subset (bool, default: False ) –

    Allow a candidate subset while scoring against all targets.

Raises:
  • ValueError –

    Inputs are invalid, there are no alternatives, targets overlap across signals, or signals differ in kind, ordered feature IDs or target count for estimand.

Evaluation results

Results returned by prediction, feature-recovery and stability evaluators.

RankingAtDepth dataclass

Exact-target recovery for the leading features of a ranking.

Attributes:
  • depth (int) –

    Cutoff in the ranking, counted from one.

  • selected_count (int) –

    Size of the top list.

  • true_positive_count (int) –

    Number of selected exact targets.

  • target_count (int) –

    Total exact targets.

  • recall (float) –

    Selected targets divided by all targets.

  • precision (float) –

    Selected targets divided by all selected features.

  • false_discovery_fraction (float) –

    Selected non-targets divided by all selected features.

RankingEvaluation dataclass

Results for finding exact target features in a ranking.

Attributes:
  • first_relevant_rank (int | None) –

    One-based position of the first exact target. evaluate_ranking always sets it because it requires targets and a complete ranking.

  • at_depth (tuple[RankingAtDepth, ...]) –

    Counts, precision, recall and false discovery fraction in depth order.

GroupAtDepth dataclass

Group recovery at one depth.

Attributes:
  • depth (int) –

    Number of leading features selected.

  • recovered_group_count (int) –

    Number of groups with at least one member selected.

  • group_count (int) –

    Total target groups.

  • group_recall (float) –

    Groups with a selected member divided by all target groups.

GroupEvaluation dataclass

Group recovery across depths.

Attributes:
  • at_depth (tuple[GroupAtDepth, ...]) –

    Group counts and recall by cutoff.

ModuleAtDepth dataclass

Weight recovered by the leading features of a ranking.

Attributes:
  • depth (int) –

    Number of leading features selected.

  • recovered_member_count (int) –

    Number of selected weighted features.

  • member_count (int) –

    Total weighted features.

  • weighted_coverage (float) –

    Sum of selected absolute weights divided by the total absolute weight.

ModuleEvaluation dataclass

Weighted recovery across depths.

Attributes:
  • at_depth (tuple[ModuleAtDepth, ...]) –

    Counts and absolute-weight coverage by cutoff.

GraphRegionAtDepth dataclass

Recovery of a graph region by the first depth features of a ranking.

Attributes:
  • depth (int) –

    Number of leading features counted as selected.

  • node_coverage (float) –

    Fraction of the region's nodes that are selected.

  • edge_coverage (float | None) –

    Fraction of the region's edges with both ends selected, counting every edge equally, or None when the region has no edges.

  • target_edge_count (int) –

    Number of edges joining two nodes of the region.

  • weighted_edge_coverage (float | None) –

    Summed weight of the region's edges with both ends selected, divided by the summed weight of all the region's edges. None when the region has no edges or their weights sum to zero. Equal to edge_coverage when every edge has the same positive weight.

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:
  • selected_feature_count (int) –

    Number of features supplied to the model.

  • evaluation_count (int) –

    Number of held-out rows.

  • r_squared (float) –

    Held-out R-squared.

  • root_mean_squared_error (float) –

    Root mean squared prediction error in generating-score units.

PredictionEvaluation dataclass

Metric name, metric value and number of observations scored.

PanelEvaluation dataclass

Prediction scores for a panel and a reference model.

Attributes:
  • metric (str) –

    Name of the scoring rule.

  • reference_value (float) –

    Metric value for the reference model.

  • panel_value (float) –

    Metric value for the panel.

  • difference (float) –

    Panel value minus reference value. Negative favours the panel for loss metrics.

  • sample_count (int) –

    Number of shared evaluation rows.

RankStabilityEvaluation dataclass

Agreement averaged over pairs of feature rankings.

Attributes:
  • ranking_count (int) –

    Number of rankings.

  • feature_count (int) –

    Features per ranking.

  • depth (int) –

    Features per top list.

  • mean_leading_jaccard (float) –

    Mean fraction of the two top lists' union shared by both lists.

  • mean_leading_intersection (float) –

    Mean number of features shared by the two top lists.

  • expected_random_intersection (float) –

    Expected shared feature count for independent random rankings (depth**2 / feature_count).

  • excess_leading_intersection (float) –

    Mean shared count minus the random expectation.

  • mean_spearman (float) –

    Mean pairwise Spearman correlation.

  • mean_rank_biased_overlap (float) –

    Mean pairwise rank overlap, weighted towards the top.

ReplicateSummary dataclass

Mean and uncertainty across independent successful simulations.

Attributes:
  • replicate_count (int) –

    Number of successful simulations.

  • failure_count (int) –

    Number of failed simulations.

  • mean (float) –

    Mean of successful estimates.

  • standard_deviation (float) –

    Sample standard deviation of successful estimates.

  • standard_error (float) –

    Sample standard deviation divided by the square root of the success count.

  • confidence_interval_low (float) –

    Lower bound of the 95% t interval for the mean.

  • confidence_interval_high (float) –

    Upper bound of that interval.

PairedReplicateComparison dataclass

Differences between two procedures evaluated on the same simulated datasets.

Attributes:
  • replicate_ids (tuple[str, ...]) –

    Shared dataset IDs for which both procedures succeeded, in left input order.

  • differences (tuple[float, ...]) –

    Right minus left for each ID in replicate_ids.

  • matched_pair_count (int) –

    Shared dataset count, including failures.

  • failed_pair_count (int) –

    Shared datasets with a failure on either side.

  • left_failure_count (int) –

    Shared datasets where the left estimate failed.

  • right_failure_count (int) –

    Shared datasets where the right estimate failed.

  • unmatched_left_count (int) –

    IDs supplied only on the left.

  • unmatched_right_count (int) –

    IDs supplied only on the right.

  • summary (ReplicateSummary) –

    Mean and 95% t interval across jointly successful pairs.

FractionalRecovery dataclass

Recovery averaged over ties at the selection cutoff.

Attributes:
  • estimand (Literal['exact', 'group', 'module', 'interaction']) –

    Recovery measure for exact targets, groups, weights or interactions.

  • value (float) –

    Score in [0, 1], with the denominator or event defined by estimand.

  • truth_support (int) –

    Count of targets for estimand (two for an interaction).

  • positive_score_support_size (int) –

    Number of positive scores, including those below the cutoff.

  • requested_depth (int) –

    Requested slot count.

  • achieved_size (int) –

    Features with positive selection probability.

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:
  • estimand (Literal['exact', 'group', 'module', 'interaction']) –

    Recovery measure for exact targets, groups, weights or interactions.

  • method (Literal['analytic']) –

    "analytic", giving the chance expectation by calculation.

  • requested_depth (int) –

    Requested slot count.

  • achieved_size (int) –

    Features with positive selection probability.

  • observed_recovery (float) –

    Recovery score for the supplied selection.

  • expected_recovery (float) –

    Mean recovery score under matched random selection.

  • chance_adjusted_recovery (float) –

    Recovery above chance (observed minus expected recovery).

  • admissible_panel_count (int) –

    Number of ways to assign positive-score status and selection probabilities within matching groups, counting assignments separately even if they can yield the same final panel.

OutcomeSpecificity dataclass

Recovery above chance for the outcome's targets compared with alternatives.

Attributes:
  • estimand (Literal['exact', 'group', 'module', 'interaction']) –

    Recovery measure for exact targets, groups, weights or interactions.

  • own_adjusted_recovery (float) –

    Recovery above chance for the outcome's targets.

  • mean_foreign_adjusted_recovery (float) –

    Mean recovery above chance across alternatives.

  • specificity (float) –

    Own adjusted recovery minus the alternative mean.

  • foreign_truth_count (int) –

    Number of alternative target sets.

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:
  • value (float | None) –

    One if all refits always select the same features, zero at chance and negative below chance. Identical cutoff ties can reduce the score below one.

  • feature_ids (tuple[str, ...]) –

    Feature order from the first refit.

  • frequencies (tuple[float, ...]) –

    Mean selection probability per feature in ID order.

  • membership_budgets (tuple[float, ...]) –

    Total selection probability per refit in input order.

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:
  • feature_ids (tuple[str, ...]) –

    Input feature order for the ranks, probabilities and medians.

  • ranking (tuple[str, ...]) –

    Sorted feature IDs, alphabetised within ties.

  • ranks (tuple[float, ...]) –

    One-based ranks from the combined ordering, averaged among features tied in both frequency and median rank.

  • inclusion_probabilities (tuple[float, ...]) –

    Mean selection probability across refits.

  • median_selected_ranks (tuple[float, ...]) –

    Median within-refit rank over refits in which the feature had positive selection probability, or infinity if it always had zero probability.

BootstrapDifference dataclass

Paired bootstrap difference and percentile interval.

Attributes:
  • left (float) –

    Left estimate on the original sample.

  • right (float) –

    Right estimate on the original sample.

  • difference (float) –

    Right minus left on the original sample.

  • confidence_level (float) –

    Requested coverage in (0, 1).

  • confidence_interval_low (float) –

    Lower percentile bound across successful draws.

  • confidence_interval_high (float) –

    Upper percentile bound across successful draws.

  • differences (tuple[float | None, ...]) –

    Right minus left for each draw in order, with None for failures.

  • failed_resamples (int) –

    Draw count with either estimate undefined.

DiscriminationGap dataclass

Difference in AUC between the generating model and a fitted model on the same outcomes.

Attributes:
  • oracle_auc (float) –

    AUC of the known generating model's risk scores.

  • fitted_auc (float) –

    AUC of the fitted model's risk scores.

  • gap (float) –

    Generating-model AUC minus fitted-model AUC. Negative values are possible.

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:
  • nominations (Sequence[FractionalNomination]) –

    At least two selections on the same set of at least two features, in any order.

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:
  • left_ranks (ArrayLike) –

    Finite ranks for two or more features. Lower is better. Equal ranks are ties.

  • right_ranks (ArrayLike) –

    Finite ranks for the same features in the same order.

  • persistence (float, default: 0.9 ) –

    Value in (0, 1). Smaller values weight the top more.

  • tie_method (Literal['webber', 'independent'], default: 'webber' ) –

    "webber" includes whole ties. "independent" breaks ties at random.

Returns:
  • float –

    Weighted agreement in [0, 1]. For "webber", each cutoff uses twice the shared count

  • float –

    divided by the combined sizes of the two top lists. For "independent", it averages the

  • float –

    shared fraction over independent uniform resolutions, so identical tied lists can score

  • float –

    below one. At depth d, weight the agreement by (1 - p) * p**(d - 1), where p is

  • float –

    persistence. At the full feature count n, both lists contain all features, so the

  • float –

    final agreement is one and receives the remaining weight p**(n - 1).

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:
  • feature_ids (tuple[str, ...]) –

    Unique column IDs for scores.

  • scores (ArrayLike) –

    Finite, non-negative importance scores, with one row per refit (at least two).

  • depth (int) –

    Number of selection slots per refit, from one to the feature count.

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:
  • training_time (ArrayLike) –

    Positive finite follow-up for at least two training rows.

  • training_event (ArrayLike) –

    Training indicators in row order, zero for censoring or one for event.

  • time (ArrayLike) –

    Positive finite follow-up for at least two test rows.

  • event (ArrayLike) –

    Test indicators in row order, zero for censoring or one for event.

  • risk (ArrayLike) –

    Finite scores increasing with event risk, in test row order.

  • horizon (float) –

    Positive cutoff in the same units as both time vectors.

  • tied_tolerance (float, default: 0.0 ) –

    Finite non-negative gap for chaining adjacent scores into ties.

Returns:
  • float –

    Weighted share of case-control pairs with higher case risk, giving ties half credit.

Raises:
  • ValueError –

    No cases or controls, the horizon reaches maximum training follow-up, or estimated censoring survival is zero at a case time or the horizon.

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:
  • participants (int | Sequence[str] | NDArray[str_]) –

    Row count, or unique participant IDs in row order. Both forms require at least two participants.

  • statistic (Callable[[NDArray[int64]], tuple[float, float] | None]) –

    Takes zero-based row indices and returns finite left and right estimates, or None if either is undefined. Use the same indices for both estimates.

  • resamples (int, default: 1000 ) –

    Number of attempted draws, at least two.

  • confidence_level (float, default: 0.95 ) –

    Percentile interval coverage in (0, 1).

  • seed (int, default: 0 ) –

    Non-negative sampling seed.

Raises:
  • ValueError –

    Inputs are invalid, the callback returns invalid estimates or the original comparison is undefined, or fewer than two draws succeed.

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:
  • oracle_risk (ArrayLike) –

    At least two finite scores from the generating model, in evaluation row order.

  • fitted_risk (ArrayLike) –

    Finite fitted-model scores in the same row order.

  • metric (Callable[[ArrayLike], float]) –

    Function mapping a score vector to AUC in [0, 1], with the outcomes fixed. For survival, also fix the horizon and censoring reference.

A finite sample may give a negative gap.