Skip to content

Modeling API

RapmStintManifest

Bases: BaseModel

Integrity and source evidence for one canonical RAPM stint dataset.

ChronologicalSplitConfig

Bases: BaseModel

Expanding-window validation and final-test configuration.

ChronologicalFold

Bases: BaseModel

Game-level boundaries for one expanding validation fold.

NeuralPossessionManifest

Bases: BaseModel

Integrity and source evidence for the neural possession dataset.

ArtifactRecord

Bases: BaseModel

Integrity metadata for one model-run artifact.

BaselineRunManifest

Bases: BaseModel

Reproducibility contract for one null/team/RAPM experiment.

BayesianRapmRunManifest

Bases: BaseModel

Reproducibility contract for one exact Bayesian RAPM run.

NeuralRapmRunManifest

Bases: BaseModel

Reproducibility contract for one additive neural RAPM run.

CatBoostRunManifest

Bases: BaseModel

Reproducibility contract for one categorical CatBoost lineup run.

RapmBasePredictionManifest

Bases: BaseModel

Integrity contract for stage-specific possession RAPM predictions.

RapmTransformerRunManifest

Bases: BaseModel

Reproducibility contract for one frozen-RAPM Transformer residual run.

ModelEvaluationManifest

Bases: BaseModel

Reproducibility contract for one cross-model evaluation report.

RapmDiagnosticsManifest

Bases: BaseModel

Reproducibility contract for one RAPM stability diagnostic run.

AgingSeasonFold

Bases: BaseModel

One expanding target-season validation fold for the aging model.

AgingModelRunManifest

Bases: BaseModel

Reproducibility contract for one forward-only RAPM aging model.

modeling_code_fingerprint(source_paths=None)

Hash modeling-owned source files for reproducible analytical artifacts.

rapm_stints_frame(lineup_stints, possession_segments)

Build positive-exposure RAPM stints with conserved possession shares.

build_rapm_stint_dataset(season, *, curated_dir=Path('data/curated'), analytical_dir=Path('data/analytical'))

Validate curated regular-season inputs and publish RAPM stints atomically.

read_rapm_stints(season, analytical_dir=Path('data/analytical'))

Read and validate one regular-season RAPM stint dataset.

validate_rapm_stint_partition(partition_dir)

Require exact RAPM part integrity and row-level invariants.

build_rapm_stints_from_processed_games(game_ids, *, processed_dir=Path('data/processed'))

Build RAPM stints directly from selected persisted per-game tables.

build_rapm_stints_from_legacy_processed_games(game_ids, *, catalog_path=Path('data/catalog/games.parquet'), processed_dir=Path('data/processed'))

Adapt cached pre-envelope per-game tables into valid RAPM source rows.

build_rapm_stints_from_curated_games(season, *, curated_dir=Path('data/curated'))

Build historical RAPM stints while excluding invalid game-level inputs.

Historical curated partitions can contain a small number of games produced before a lineup or possession reconstruction repair. RAPM requires exact point conservation, so an invalid game is excluded rather than allowing it to contaminate a season-wide design matrix. The caller persists the returned game IDs as part of its run provenance.

allocation_policy_stints(lineup_stints, possession_segments, policy)

Construct comparable RAPM stints under one possession-allocation policy.

possession_allocation_summary(possession_segments, *, reference_policy='equal_segments')

Quantify how each policy changes possession-to-lineup attribution.

A possession is changed when a policy's exposure vector over distinct ten-player lineups differs from the reference vector. Reassigned exposure is total-variation distance with an additional removed-possession bucket, so excluded exposure counts fully rather than as half a possession.

GameFold dataclass

Concrete train and validation game IDs for one expanding fold.

GameSplitPlan dataclass

All chronological folds plus the untouched final test.

BaselineExperiment dataclass

In-memory outputs ready for atomic model-run persistence.

chronological_game_splits(stints, config)

Create expanding folds without dividing any NBA game date.

fit_baseline_experiment(stints, *, lambda_grid=DEFAULT_LAMBDA_GRID, split_config=None, minimum_ranking_possessions=500.0, player_bios=None)

Tune, test, and refit null, team, and canonical one-number RAPM models.

train_regular_season_baselines(season, *, curated_dir=Path('data/curated'), analytical_dir=Path('data/analytical'), artifacts_dir=Path('artifacts/models'), lambda_grid=DEFAULT_LAMBDA_GRID, split_config=None, minimum_ranking_possessions=500.0)

Build RAPM stints, run all baselines, and atomically persist artifacts.

validate_baseline_run(run_dir)

Require every recorded model artifact to match its manifest.

BayesianRapmExperiment dataclass

In-memory outputs for one exact Bayesian RAPM analysis.

bayesian_code_fingerprint(source_paths=None)

Hash Bayesian RAPM source files for reproducible model runs.

fit_bayesian_rapm_experiment(stints, *, player_columns, ridge_rankings, game_splits, ridge_test_predictions, ridge_intercept, selected_lambda, posterior_draws=DEFAULT_POSTERIOR_DRAWS, posterior_seed=DEFAULT_POSTERIOR_SEED, credible_interval_probability=DEFAULT_CREDIBLE_INTERVAL)

Fit, evaluate, and summarize the conjugate counterpart to one ridge RAPM.

train_bayesian_rapm(season, *, source_run_id=None, analytical_dir=Path('data/analytical'), model_artifacts_dir=Path('artifacts/models'), posterior_draws=DEFAULT_POSTERIOR_DRAWS, posterior_seed=DEFAULT_POSTERIOR_SEED, credible_interval_probability=DEFAULT_CREDIBLE_INTERVAL)

Fit exact Bayesian RAPM from one validated canonical ridge run.

validate_bayesian_rapm_run(run_dir)

Require every recorded Bayesian RAPM artifact to match its manifest.

diagnostics_code_fingerprint(source_paths=None)

Hash diagnostics-owned source files for reproducible reports.

lambda_sensitivity(stints, player_matrix, player_ids, rankings, lambdas, selected_lambda)

Refit full-season RAPM over a lambda path and compare player ranks.

chronological_stability(stints, player_matrix, player_ids, rankings, game_splits, selected_lambda, minimum_possessions)

Compare fixed-lambda coefficients across expanding season windows.

bootstrap_stability(stints, player_matrix, player_ids, rankings, selected_lambda, *, samples, seed)

Refit RAPM on complete-game bootstrap samples.

context_concentration(stints, rankings)

Measure how broadly each player is connected to teammates and lineups.

raw_adjusted_comparison(rankings)

Compare raw on-court net rating with the adjusted RAPM coefficient.

influence_diagnostics(stints, player_matrix, player_ids, rankings, selected_lambda, *, influence_player_count, stints_per_player, delete_games_per_player)

Screen influential stints and verify top games with exact deletions.

allocation_sensitivity(lineup_stints, possession_segments, rankings, player_ids, player_columns, game_splits, selected_lambda, policies)

Refit RAPM under alternative multi-lineup possession policies.

player_diagnostics_summary(rankings, lambda_coefficients, chronological_summary, bootstrap_summary, concentration, raw_adjusted, allocation_coefficients, delete_game)

Combine review-oriented player diagnostics into one wide table.

run_rapm_diagnostics(season, *, source_run_id=None, analytical_dir=Path('data/analytical'), curated_dir=Path('data/curated'), model_artifacts_dir=Path('artifacts/models'), reports_dir=Path('artifacts/reports'), sensitivity_lambdas=DEFAULT_SENSITIVITY_LAMBDAS, bootstrap_samples=200, bootstrap_seed=7, influence_player_count=25, influence_stints_per_player=5, delete_games_per_player=3, allocation_policies=POSSESSION_ALLOCATION_POLICIES)

Run every RAPM stability diagnostic and publish immutable reports.

validate_diagnostics_run(run_dir)

Require every diagnostics artifact to match its manifest.

CaseStudyThresholds dataclass

Transparent editorial thresholds for the top-ranking review bands.

CaseStudySource dataclass

Provenance displayed in a generated RAPM case study.

classify_top_rankings(player_diagnostics, thresholds=None)

Assign transparent review bands to the exposure-eligible top ranking.

build_rapm_case_study(season, *, diagnostics_run_id=None, reports_dir=Path('artifacts/reports'), output_path=None, asset_dir=None, thresholds=None)

Generate a review page and charts from one immutable diagnostics run.

render_case_study_markdown(source, top, lambda_summary, allocation_metrics, thresholds, *, bootstrap_reference, sensitivity_reference)

Render the complete one-season RAPM case study.

BayesianCaseStudySource dataclass

Provenance displayed in a generated Bayesian RAPM case study.

prepare_case_study_players(posterior_rankings, bootstrap_summary, *, top_n=25)

Join posterior and bootstrap uncertainty and return all eligible plus initial top N.

build_bayesian_case_study(season, *, bayesian_run_id=None, diagnostics_run_id=None, model_artifacts_dir=Path('artifacts/models'), reports_dir=Path('artifacts/reports'), output_path=None, asset_dir=None)

Generate a Bayesian-versus-ridge case study from immutable model runs.

render_bayesian_case_study_markdown(source, eligible, top, comparison, calibration, *, interval_reference, rank_reference)

Render the complete Bayesian-versus-ridge case study.

Historical player features

PlayerSeasonPanelSource

Bases: BaseModel

Exact model and curated inputs for one season of the panel.

PlayerSeasonPanelManifest

Bases: BaseModel

Integrity and temporal contract for reusable player-season features.

aggregate_box_score_features(players)

Aggregate played game boxscore rows into stable season-level features.

player_season_frame(season, boxscore_features, rapm_rankings, player_bios, player_catalog, *, rapm_run_id)

Combine same-season outcomes, box features, and static player context.

player_transition_frame(panel)

Create target-season rows containing only lagged performance features.

build_player_season_panel(seasons, *, rapm_run_ids=None, curated_dir=Path('data/curated'), artifacts_dir=Path('artifacts/models'), player_catalog_path=Path('data/catalog/players.parquet'), analytical_dir=Path('data/analytical'))

Build an atomic multi-season panel and leakage-safe lag-one transitions.

validate_player_season_panel(panel_dir)

Validate exact panel artifacts, hashes, rows, and temporal columns.

player_history_code_fingerprint(source_paths=None)

Hash sources that define player-season and transition features.

RAPM aging model

TargetSeasonFold dataclass

Concrete expanding train and validation target seasons.

AgingExperiment dataclass

In-memory outputs for one forward-only aging experiment.

expanding_target_season_folds(transitions, *, holdout_target_season=None)

Create expanding target-season folds and one untouched latest holdout.

run_aging_experiment(transitions, *, holdout_target_season=None, regularization_grid=DEFAULT_AGING_REGULARIZATION_GRID, age_spline_knots=5, age_spline_degree=2)

Select and evaluate an aging model without using holdout outcomes.

train_forward_aging_model(*, panel_dir=Path('data/analytical/player_season_panel'), artifacts_dir=Path('artifacts/models'), holdout_target_season=None, regularization_grid=DEFAULT_AGING_REGULARIZATION_GRID, age_spline_knots=5, age_spline_degree=2)

Train from a validated player-season panel and publish an immutable run.

validate_aging_model_run(run_dir)

Validate hashes, rows, holdout identity, and label-free player priors.

aging_code_fingerprint(source_paths=None)

Hash the implementation sources that define the aging experiment.

FittedMeanModel dataclass

Possession-weighted intercept-only prediction.

RidgeLineupModel

Sparse ridge model with a sample-size-normalized lambda convention.

PriorCenteredRidgeLineupModel

Sparse ridge whose coefficient penalty is centered on a prior vector.

Fitting ridge to y - X @ prior gives the coefficient adjustment around the prior. Adding the prior back to that adjustment is equivalent to penalizing ||coefficient - prior||^2 in the original objective.

entity_vocabulary(frame, positive_column, negative_column, *, multiple)

Return sorted entity IDs appearing on either side of a signed design.

signed_entity_matrix(frame, positive_column, negative_column, entity_to_column, *, multiple)

Encode positive and negative entities in a SciPy CSR matrix.

vocabulary_mapping(identifiers)

Map unique entity IDs to stable contiguous sparse columns.

MarginalPosterior dataclass

Univariate summaries from one marginal Student-t posterior.

PredictivePosterior dataclass

Posterior predictive location and interval for observed outcomes.

ConjugateBayesianRidge dataclass

Exact weighted Gaussian posterior corresponding to a ridge fit.

The likelihood variance for row i is sigma_squared / weight_i. Player coefficients have a zero-centered Gaussian prior conditional on sigma_squared. The intercept is unpenalized, and the residual variance uses the scale-invariant prior p(sigma_squared) proportional to 1 / sigma_squared.

intercept_mean property

Posterior location for the unpenalized intercept.

coefficient_mean property

Posterior locations for all penalized coefficients.

residual_variance_mean property

Posterior mean of the residual variance.

fit(features, target, sample_weight, regularization) classmethod

Fit the exact conjugate posterior with an unpenalized intercept.

marginal_summary(*, interval_probability=0.9)

Return exact marginal summaries for every model parameter.

draw_parameters(draw_count, *, seed)

Draw jointly from the multivariate Student-t posterior.

predict_mean(features)

Predict from the posterior location.

predictive_summary(features, sample_weight, *, interval_probability=0.9, batch_size=2048)

Return marginal posterior predictive intervals for new observations.

Neural possession data

PossessionTensorDataset

Bases: Dataset[dict[str, Tensor]]

Contiguous tensor representation of fixed-lineup possessions.

neural_code_fingerprint(source_paths=None)

Hash neural-owned sources for reproducible datasets and runs.

neural_possessions_frame(possession_segments)

Orient single-lineup possessions by offense and exclude ambiguous rows.

build_neural_possession_dataset(season, *, curated_dir=Path('data/curated'), analytical_dir=Path('data/analytical'))

Validate curated segments and publish single-lineup possessions atomically.

read_neural_possessions(season, analytical_dir=Path('data/analytical'))

Read and validate one regular-season neural possession dataset.

validate_neural_possession_partition(partition_dir)

Require exact neural possession files, hashes, and row invariants.

player_vocabulary(possessions)

Map stable NBA player IDs to embedding rows, reserving zero for unknown.

Neural models

AdditivePlayerModel

Bases: Module

Signed scalar player embeddings with a centered home-offense effect.

centered_player_values()

Return identifiable player values, excluding the reserved unknown row.

AdditiveRapmModule

Bases: LightningModule

Lightning training wrapper for the additive player model.

DeepSetsPlayerModel

Bases: Module

Permutation-invariant nonlinear lineups with an additive skip path.

centered_player_values()

Return additive-path values, excluding the reserved unknown row.

DeepSetsRapmModule

Bases: LightningModule

Lightning wrapper for the additive-plus-Deep-Sets possession model.

RapmTransformerResidualModel

Bases: Module

Position-free lineup attention that corrects a frozen RAPM prediction.

RapmTransformerModule

Bases: LightningModule

Lightning wrapper for frozen-RAPM plus Transformer residual training.

Neural training

NeuralTrainingConfig dataclass

Hyperparameters and runtime controls for the first neural baseline.

AdditiveNeuralExperiment dataclass

In-memory summaries plus checkpoints written in a temporary run directory.

PossessionDataModule

Bases: LightningDataModule

Lightning data module backed by contiguous possession tensors.

train_additive_neural_rapm(season, *, curated_dir=Path('data/curated'), analytical_dir=Path('data/analytical'), artifacts_dir=Path('artifacts/models'), split_config=None, training_config=None, minimum_ranking_possessions=500.0, enable_progress_bar=True)

Build neural possessions, train additive RAPM, and persist an atomic run.

fit_additive_neural_experiment(possessions, *, checkpoint_dir, split_config=None, training_config=None, minimum_ranking_possessions=500.0, player_bios=None, enable_progress_bar=False)

Select epochs, evaluate the final test, and refit the full season.

validate_neural_rapm_run(run_dir)

Require every recorded neural artifact to match its manifest.

Deep Sets training

DeepSetsArchitectureConfig dataclass

Fixed architecture for the first nonlinear lineup-composition model.

DeepSetsExperiment dataclass

In-memory Deep Sets outputs ready for atomic persistence.

train_deep_sets(season, *, curated_dir=Path('data/curated'), analytical_dir=Path('data/analytical'), artifacts_dir=Path('artifacts/models'), split_config=None, training_config=None, architecture_config=None, refit_seeds=None, minimum_ranking_possessions=500.0, enable_progress_bar=True)

Tune, evaluate, and refit the regular-season Deep Sets model.

fit_deep_sets_experiment(possessions, *, checkpoint_dir, split_config=None, training_config=None, architecture_config=None, refit_seeds=None, minimum_ranking_possessions=500.0, player_bios=None, enable_progress_bar=False)

Select optimization settings, evaluate fixed seeds, and refit all games.

validate_deep_sets_run(run_dir)

Validate a Deep Sets run and require its architecture contract.

default_deep_sets_training_config()

Return the CPU-conscious default search budget for Deep Sets.

RAPM base predictions

RapmBasePredictions dataclass

Stage-aware RAPM predictions and the states that produced them.

build_rapm_base_prediction_dataset(season, *, source_rapm_run_id=None, curated_dir=Path('data/curated'), analytical_dir=Path('data/analytical'), artifacts_dir=Path('artifacts/models'))

Build leakage-safe stage predictions from the canonical RAPM baseline.

fit_rapm_base_predictions(possessions, stints, *, split_config=None, regularization)

Fit one frozen RAPM state per chronological model stage.

read_rapm_base_predictions(season, analytical_dir=Path('data/analytical'))

Read and validate the stage-specific RAPM prediction rows.

read_rapm_base_state(season, analytical_dir=Path('data/analytical'))

Read fitted coefficients and stage parameters for base prediction.

validate_rapm_base_prediction_partition(partition_dir)

Require exact files, hashes, roles, and chronological boundaries.

rapm_base_code_fingerprint(source_paths=None)

Hash source files that define the stage-aware base predictions.

RAPM + Transformer training

RapmTransformerArchitectureConfig dataclass

Fixed architecture for the first attention-based lineup residual.

RapmTransformerExperiment dataclass

In-memory outputs ready for an immutable Transformer model run.

RapmResidualTensorDataset

Bases: Dataset[dict[str, Tensor]]

Possession tensors augmented with one frozen RAPM base prediction.

RapmResidualDataModule

Bases: LightningDataModule

Lightning loaders for one stage of the RAPM residual mart.

train_rapm_transformer(season, *, source_rapm_run_id=None, curated_dir=Path('data/curated'), analytical_dir=Path('data/analytical'), artifacts_dir=Path('artifacts/models'), training_config=None, architecture_config=None, refit_seeds=None, enable_progress_bar=True)

Build frozen RAPM predictions, train the residual, and persist a run.

fit_rapm_transformer_experiment(possessions, base_predictions, *, checkpoint_dir, split_plan=None, training_config=None, architecture_config=None, refit_seeds=None, enable_progress_bar=False)

Select optimization settings, evaluate fixed seeds, and refit all games.

validate_rapm_transformer_run(run_dir)

Require every Transformer artifact to match its run manifest.

frozen_rapm_predictions(possessions, coefficients, *, intercept_home_net_rating, mean_offense_margin)

Apply a stored RAPM state in offense orientation.

rapm_transformer_predictions(module, possessions, player_columns, base_predictions, *, batch_size=DEFAULT_TRANSFORMER_BATCH_SIZE, num_workers=0)

Apply a fitted Transformer and return total and residual predictions.

transformer_code_fingerprint(source_paths=None)

Hash Transformer-owned model, training, and evaluation sources.

default_transformer_training_config()

Return the CPU-conscious first Transformer search budget.

CatBoost training

CatBoostTrainingConfig dataclass

Explicit controls for the defaults-first CatBoost exemplar.

CatBoostExperiment dataclass

In-memory CatBoost outputs ready for atomic persistence.

train_catboost_lineup_model(season, *, curated_dir=Path('data/curated'), analytical_dir=Path('data/analytical'), artifacts_dir=Path('artifacts/models'), split_config=None, training_config=None)

Train, evaluate, and persist the categorical player-state model.

fit_catboost_experiment(possessions, *, split_config=None, training_config=None, player_bios=None)

Fit the defaults-first CatBoost protocol on an in-memory dataset.

categorical_player_state_matrix(possessions, player_columns)

Encode each player as absent, offense, or defense plus home offense.

catboost_feature_names(player_columns)

Return feature names in encoded column order.

catboost_predictions(model, possessions, player_columns)

Predict possessions and count player exposures absent from training.

validate_catboost_run(run_dir)

Require every recorded CatBoost artifact to match its manifest.

catboost_code_fingerprint(source_paths=None)

Hash CatBoost-owned sources for reproducible runs.

Leaderboard

evaluation_code_fingerprint(source_paths=None)

Hash evaluation-owned sources for reproducible comparison reports.

build_model_evaluation(season, *, ridge_run_id=None, prior_rapm_run_id=None, bayesian_run_id=None, neural_run_id=None, deep_sets_run_id=None, catboost_run_id=None, rapm_transformer_run_id=None, curated_dir=Path('data/curated'), analytical_dir=Path('data/analytical'), model_artifacts_dir=Path('artifacts/models'), reports_dir=Path('artifacts/reports'), docs_path=Path('docs/models/leaderboard.md'))

Evaluate fitted regular-season models on regular holdout and playoffs.

evaluate_fitted_models(season, sources, regular_segments, regular_lineups, playoff_segments, *, analytical_dir=Path('data/analytical'))

Build common cohorts and score each stored point-prediction model.

score_prediction_cohort(possessions, model_predictions, *, cohort, training_window, mean_prediction)

Score multiple models on one identical possession cohort.

paired_game_cluster_bootstrap(possessions, reference_predictions, candidate_predictions, *, cohort, reference_model='additive_neural', candidate_model='deep_sets', draws=2000, random_seed=20260729)

Bootstrap paired candidate-minus-reference RMSE differences by game.

render_evaluation_page(manifest, metrics, cohorts, output_path, comparisons=None)

Render the canonical equations and current model comparison tables.

validate_model_evaluation_run(run_dir)

Require every recorded evaluation artifact to match its manifest.

validate_forward_lagged_rapm_run(run_dir)

Validate the forward-prior RAPM artifact contract.

mean_squared_error(actual, predicted, sample_weight=None)

Return optional-weighted mean squared error.

rmse(actual, predicted, sample_weight=None)

Return optional-weighted root mean squared error.

mean_absolute_error(actual, predicted, sample_weight=None)

Return optional-weighted mean absolute error.

game_margin_rmse(game_ids, actual_net_rating, predicted_net_rating, possessions)

Aggregate stint net ratings into game margins before computing RMSE.

possession_game_margin_rmse(game_ids, actual_offense_margin, predicted_offense_margin, home_offense_sign)

Aggregate offense-oriented possessions into eligible home game margins.

skill_score(model_mse, baseline_mse)

Return out-of-sample skill relative to a baseline MSE.