metacountregressor
Describe the outcome. Set the rules. Let the search find the model.
metacountregressor is a JAX-first Python package for hierarchical model fitting
and metaheuristic-driven structure search. It searches over variables, fixed and
random effects, zero inflation, latent classes, and heterogeneity, then fits the
winning specification with simulation-based maximum likelihood.
One API covers count, CMF, duration, linear, Tobit, survival, multivariate, and latent-class models. The same search can also produce a Bayesian specification, run on HPC, or be driven interactively by the built-in copilot.
Install: pip install metacountregressor
Jump to a search: Count | CMF | Duration | Linear | Tobit | Survival | Multivariate | Latent class | Bayesian | HPC
Choose your search
Pick the row that matches your outcome. Each row links to the detailed section and, where available, to a runnable notebook.
| Your outcome or requirement | Search family | What the search chooses | Start here |
|---|---|---|---|
| Crash, injury, or other counts | count |
Variables, fixed/random effects, ZI, latent classes, heterogeneity | Count search / 01 notebook |
| Crash modification factors | cmf |
Baseline effects plus AADT interactions | CMF search / 03 notebook |
| Positive duration or time-to-event | duration |
Variables, random parameters, latent classes | Duration search / Tutorial.ipynb |
| Continuous outcome such as speed or cost | linear |
Variables, random parameters, latent classes | Linear search / 04 notebook |
| Continuous outcome censored at a lower bound | tobit |
Variables, random parameters, latent classes | Tobit search |
| Survival time with right-censoring | survival |
Variables, random parameters, heterogeneity | Survival search |
| Several correlated counts per person | multivariate |
Variables for each activity plus copula dependence | Multivariate search |
| Unobserved segments or classes | count + LC |
Membership variables and class-specific effects | Latent-class search / 02 notebook |
| Bayesian uncertainty for a chosen structure | bayesian |
Posterior of the selected specification | Bayesian compilation |
| Many candidates or a long HPC run | any | Parallel seeds, checkpoints, warm starts | HPC search / 05 notebook |
Not sure which family fits? Run builder.suggest_config() or open the copilot
and let it propose a starting specification.
Install
pip install metacountregressor
Optional extras:
pip install "metacountregressor[bayesian]" # PyMC compiler
pip install "metacountregressor[gis]" # GIS / spatial helpers
pip install "metacountregressor[full]" # all optional dependencies
pip install -U "jax[cuda]" # GPU-enabled JAX
Quick import check:
python -c "from metacountregressor import __version__; print(__version__)"
To work on the package itself:
git clone https://github.com/zahern/MetaCount.git
cd MetaCount
python -m pip install -e .
Optional: let the copilot write the specification
From version 1.0.216, the installed package includes an interactive experiment-setup wizard:
metacount-copilot
or:
from metacountregressor import run_cli
run_cli()
The wizard reads your data file, asks for the response and model family,
proposes a pruned variable catalogue and a tiered constraint hierarchy, then
supports /run, /diagnose, /apply, and /rerun from the same prompt. It
can also drive the Delphos reinforcement-learning search:
python -m metacountregressor.copilot
The four-step workflow
Every search follows the same path:
1. Load data -> 2. Set constraints -> 3. Search -> 4. Fit and interpret
| Step | What you write | What happens |
|---|---|---|
| 1. Load | ExperimentBuilder(df, id_col, y_col, offset_col) |
Validates columns and builds the model data |
| 2. Constrain | ModelConstraints() |
Restricts which roles and distributions the search may use |
| 3. Search | builder.run(evaluator, algo='sa') |
Metaheuristic search minimises BIC over candidate structures |
| 4. Fit | builder.fit_manual_model(result['model_spec']) |
Final JAX maximum likelihood fit with standard errors |
The search decides which variables enter, whether each coefficient is fixed or random, and whether the model needs zero inflation, latent classes, or heterogeneity in means. You decide which of those choices are allowed.
Quick start: one count search
import numpy as np
from metacountregressor import (
ExperimentBuilder,
ModelConstraints,
load_example16_3_model_data,
)
# 1. Load the bundled crash-frequency data
df = load_example16_3_model_data()
exposure = df['LENGTH'] * df['AADT'] * 365 / 1e8
df['OFFSET'] = np.log(exposure.clip(lower=1e-9))
# 2. Set the rules
c = (
ModelConstraints()
.force_include('OFFSET') # exposure always in
.no_zi('LENGTH', 'CURVES', 'WIDTH', 'SLOPE') # no zero inflation
.no_random('URB') # dummy: fixed only
.allow_random('CURVES', distributions=['lognormal']) # positive effect
)
# 3. Build the evaluator and search
builder = ExperimentBuilder(df, id_col='ID', y_col='FREQ', offset_col='OFFSET')
evaluator = builder.build_evaluator(
variables=['AADT', 'LENGTH', 'SPEED', 'CURVES', 'URB', 'AVEPRE'],
constraints=c,
default_roles=[0, 1, 2, 3, 5],
max_latent_classes=1,
R=200,
)
result = builder.run(evaluator, algo='sa', max_iter=1000, seed=42)
# 4. Fit and interpret the winning specification
fit = builder.fit_manual_model(
manual_spec=result['model_spec'], model='nb', R=500)
print('Best BIC:', result['best_score'])
print(fit)
R=200 is enough to rank structures. Refit the winner with R=500 or more
when you need final standard errors.
Three ways to work
You do not have to use the search every time. Pick the level of control you need:
| You want to... | Use this | What it gives you |
|---|---|---|
| Explore | default_roles=[0, 1, 2, 3, 5] |
The search chooses variables and roles with little steering |
| Constrain | ModelConstraints() |
You allow or forbid roles, distributions, and combinations |
| Pin | builder.make_manual_spec(...) |
You specify the exact model and skip the search |
The rest of this page shows the middle option, because constraints are how you turn a general search into a model that respects your problem.
Constraint cookbook
ModelConstraints is a fluent builder. Every method returns the same object, so
rules read from top to bottom:
from metacountregressor import ModelConstraints
c = (
ModelConstraints()
.force_include('OFFSET') # never drop exposure
.exclude('ID', 'YEAR') # never enter
.force_fixed('AADT') # fixed only, no random
.no_random('URB', 'GRADEBR') # dummies stay fixed
.allow_random('CURVES', distributions=['lognormal']) # random but positive
.no_zi('LENGTH', 'CURVES', 'WIDTH', 'SLOPE') # no zero inflation
.membership_only('FC_ENCODED') # latent-class membership only
.outcome_only('AADT') # never a membership term
.mutual_exclusion(['SPEED', 'SPEED_50']) # at most one speed variable
)
print(c) # show every rule
c.summary() # same as print(c)
Common recipes
| If you want to... | Write this |
|---|---|
| Keep a variable in every model | .force_include('OFFSET') |
| Remove a variable completely | .exclude('ID', 'YEAR') |
| Allow fixed effects only | .force_fixed('AADT') |
| Prevent random parameters | .no_random('URB', 'GRADEBR') |
| Allow random parameters only where they make sense | .allow_random('CURVES', distributions=['lognormal']) |
| Stop zero inflation on a variable | .no_zi('LENGTH', 'CURVES', 'WIDTH') |
| Make a variable drive latent-class membership only | .membership_only('FC_ENCODED') |
| Let a variable enter both the outcome and membership | .allow_membership('SPEED') |
| Keep a variable out of the membership equation | .outcome_only('AADT') |
| Never allow two variables together | .mutual_exclusion(['SPEED', 'SPEED_50']) |
| Set exact role codes | .set_roles('WIDTH', [0, 1, 2]) |
| Set exact random-parameter distributions | .set_distributions('CURVES', ['normal', 'lognormal']) |
Three constraint patterns
Only fixed effects - useful for a baseline or a small sample:
c = ModelConstraints().force_include('OFFSET')
evaluator = builder.build_evaluator(
variables=['AADT', 'LENGTH', 'SPEED', 'CURVES'],
constraints=c,
default_roles=[0, 1],
)
Random parameters, but not for every variable - the usual production setup:
c = (
ModelConstraints()
.force_include('OFFSET')
.no_random('URB', 'ACCESS', 'GRADEBR') # dummies: fixed only
.allow_random('CURVES', 'LENGTH') # allow taste variation
.no_zi('LENGTH', 'CURVES', 'WIDTH', 'SLOPE') # protect geometry
)
Latent classes with a known membership driver - FC_ENCODED explains class
membership, while other variables can still enter the outcome:
c = (
ModelConstraints()
.force_include('OFFSET')
.membership_only('FC_ENCODED') # role 7 only
.no_zi('LENGTH', 'CURVES', 'WIDTH', 'SLOPE')
.no_random('URB')
)
evaluator = builder.build_evaluator(
variables=['AADT', 'LENGTH', 'SPEED', 'CURVES', 'URB', 'FC_ENCODED'],
constraints=c,
default_roles=[0, 1, 2, 3, 5, 7, 8],
max_latent_classes=2,
)
For the full constraint API, run get_help('constraints').
Search recipes by aspect
Use this table when you know which structural feature you need, rather than which model family you need.
| Capability | How to turn it on | Learn more |
|---|---|---|
| Independent random parameters | Role 2 in default_roles, or .allow_random(...) |
Count search |
| Correlated random parameters | Role 3 in default_roles |
Count search |
| Grouped random effects | group_id_col plus role 4 |
Count search |
| Heterogeneity in means | Role 5 in default_roles |
Count search |
| Zero inflation | Role 6; protect variables with .no_zi(...) |
Count search |
| Latent classes | max_latent_classes=2, roles 7 and 8 |
Latent-class search |
| Class-specific outcome effects | Role 8 |
Latent-class search |
| Mutual exclusion | .mutual_exclusion([...]) |
Constraint cookbook |
| Distribution restrictions | .allow_random(..., distributions=[...]) |
Constraint cookbook |
| Multi-objective search (BIC plus test error) | mode='multi' with algo='de' or algo='hs' |
Search algorithms |
| Sparse variable selection | algo='agds' |
Search algorithms |
| Checkpoint and resume | SearchOutputConfig(checkpoint_every=...) |
Output and results |
| HPC batch or parallel seeds | max_time, PBS/SLURM templates |
HPC search |
| Bayesian uncertainty | builder.build_bayesian_model(result) |
Bayesian compilation |
| Let a wizard write the spec | metacount-copilot |
Copilot |
Advanced estimators
The search API is the main entry point, but the package also ships standalone estimators for specialised data structures:
| Estimator | What it models | Import |
|---|---|---|
BivariateCopulaNB |
Two correlated counts, such as crashes and near-misses, with Frank, Normal, or Kimeldorf-Sampson dependence | from metacountregressor import BivariateCopulaNB |
MultivariateCountRegressor |
Several correlated activity counts per person with NB or Poisson marginals and a Gaussian or vine copula | from metacountregressor import MultivariateCountRegressor |
PavementCLROptimizer |
Clusterwise log-log pavement deterioration with OLS, AR(1), AR(2), random-walk, or near-unit-root errors | from metacountregressor import PavementCLROptimizer |
TemporalRandomParameterRegressor |
Random-parameter models with AR(1), AR(2), random-walk, or random-walk-with-drift dependence | from metacountregressor import TemporalRandomParameterRegressor |
RPStructuralSpec |
Random-parameter structural equations for means and variances | from metacountregressor import RPStructuralSpec |
BayesianModel |
Rebuild a selected count, CMF, linear, Tobit, or duration structure in PyMC | from metacountregressor import BayesianModel |
These estimators are documented in their module docstrings and in the worked examples. The core search remains the recommended path when you want the package to discover the specification.
Worked examples and tutorials
Six notebooks ship inside the wheel and use the bundled Example 16-3 dataset, so every cell runs without extra data:
from metacountregressor import get_templates
get_templates() # copies all six notebooks to the current folder
| Notebook | What it shows | Time |
|---|---|---|
| 00_quickstart.ipynb | Install, load data, first search end-to-end | ~10 min |
| 01_crash_frequency_search.ipynb | Count search with constraints, roles, and refit | ~20 min |
| 02_latent_class_fc_validation.ipynb | Latent classes, class probabilities, and validation | ~20 min |
| 03_cmf_aadt_search.ipynb | CMF search with baseline and AADT-interaction terms | ~20 min |
| 04_linear_speed_prediction.ipynb | Gaussian linear model search | ~20 min |
| 05_batch_script_tutorial.ipynb | Batch scripts, parallel seeds, PBS/SLURM, result collection | ~30 min |
Extended walkthroughs:
| Resource | Format | Link |
|---|---|---|
| General tutorial (search -> fit -> interpret) | Jupyter notebook | Tutorial.ipynb |
| Batch and HPC deep dive | Jupyter notebook | Tutorial_Batch.ipynb |
| Batch and HPC deep dive | Markdown | Tutorial_Batch.md |
| Hierarchical CMF tutorial | Python script | manual_hierarchical_cmf_tutorial.py |
| Hierarchical CMF narrative guide | Markdown | TUTORIAL_HIERARCHICAL_CMF.md |
| CMF versus count for a non-technical audience | Notebook | cmf_vs_count_general_audience.ipynb |
| CMF versus count slide deck | Markdown | cmf_vs_count_comparison_slides.md |
Built-in help
The package includes printable guides for every core workflow:
from metacountregressor import get_help
get_help() # list all topics
get_help('data') # loading data and offsets
get_help('variables') # role codes and distributions
get_help('constraints') # ModelConstraints API
get_help('metaheuristics') # algorithm comparison and tuning
get_help('crash_frequency') # count model workflow
get_help('latent_class') # latent-class workflow
get_help('cmf') # CMF workflow
get_help('linear') # linear model workflow
get_help('roles') is an alias for get_help('variables').
Reference
Data loaders
All loaders return a pandas.DataFrame:
from metacountregressor import (
load_example16_3_raw_data, # original 31 columns
load_example16_3_model_data, # adds OFFSET, FC_ENCODED, FC_LABEL
load_example_crash_data, # alias for the model data
load_example_duration_data, # synthetic duration target
load_example_linear_data, # synthetic linear target
load_example_platform_speed_data, # speed relative to a platform
load_example_platform_gap_duration_data, # time until the next speeding event
load_example_panel_data, # panel-structure example
)
load_example16_3_raw_data() returns:
| Group | Columns |
|---|---|
| Identifiers | ID |
| Outcome | FREQ |
| Geometry | LENGTH, WIDTH, INCLANES, DECLANES, MEDWIDTH, MIMEDSH, MXMEDSH |
| Speed and grade | SPEED, MIGRADE, MXGRADE, MXGRDIFF, SLOPE |
| Traffic | AADT, SINGLE, DOUBLE, TRAIN, PEAKHR, ADTLANE |
| Road class | URB, FC, ACCESS, TANGENT, CURVES, MINRAD, GRADEBR |
| Friction and weather | FRICTION, INTECHAG, AVEPRE, AVESNOW |
load_example16_3_model_data() adds OFFSET, FC_ENCODED, and FC_LABEL.
Use your own data
import pandas as pd
from metacountregressor import ExperimentBuilder
df = pd.read_csv('my_segments.csv')
builder = ExperimentBuilder(
df=df,
id_col='site_id',
y_col='crashes',
offset_col='log_exposure', # or None
group_id_col='road_class', # or None
)
builder.describe()
For a first run, keep the search small: default_roles=[0, 1, 2], R=50,
max_iter=20. Refit the winner with a larger R for final standard errors.
ExperimentBuilder API
builder = ExperimentBuilder(
df=df,
id_col='ID', # required
y_col='FREQ', # required
offset_col='OFFSET', # optional log exposure
group_id_col='FC', # optional group or panel id
)
Key methods:
| Method | Purpose |
|---|---|
builder.describe() |
Print data summary |
builder.suggest_config(max_latent_classes=2) |
Print recommended settings |
builder.build_evaluator(...) |
Build a structure evaluator |
builder.build_search(...) |
Build a search problem for any family |
builder.build_count_evaluator(...) |
Shortcut for count models |
builder.run(evaluator, algo, max_iter, seed, ...) |
Run the search |
builder.make_manual_spec(...) |
Build a specification by hand |
builder.fit_manual_model(manual_spec, model, R) |
Fit a manual specification |
builder.build_bayesian_model(result, ...) |
Compile the selected structure into PyMC |
builder.compute_latent_class_probabilities(fit, true_class_col) |
Class membership probabilities |
ExperimentBuilder.get_family_capabilities() |
List supported families and features |
ExperimentBuilder.get_search_argument_guide() |
Full argument reference |
build_evaluator arguments:
evaluator = builder.build_evaluator(
variables=['AADT', 'LENGTH', 'SPEED', 'CURVES'],
constraints=c,
model_family='count', # count, cmf, duration, linear, tobit, survival, multivariate
default_roles=[0, 1, 2, 3, 5], # roles the search may assign
max_latent_classes=2, # 1 disables latent classes
mode='single', # single = BIC; multi = BIC plus test error
R=200, # Halton draws
aadt_col='AADT', # CMF only
baseline_vars=['URB'], # CMF only
local_vars=['CURVES'], # CMF only
budget_col='AADT', # duration only
family='weibull_ph', # survival only
)
Per-variable role restrictions without a ModelConstraints object:
evaluator = builder.build_evaluator(
variables=['AADT', 'SPEED', 'URB'],
fixed_override={'AADT': [1]},
membership_override={'URB': [7, 8]},
)
R trades time for accuracy: a small R ranks structures, a large R gives
final standard errors.
Role codes
| Code | Name | Meaning |
|---|---|---|
0 |
Excluded | Not in the model |
1 |
Fixed | Same coefficient for every observation |
2 |
Random (independent) | Individual random effect |
3 |
Random (correlated) | Random effect correlated with others |
4 |
Grouped | Group-level random effect |
5 |
Heterogeneity | Explains variation in random-parameter means |
6 |
Zero inflation | Enters the zero-inflation equation |
7 |
Membership only | Drives latent-class probability only |
8 |
Membership plus fixed | Drives membership and has a class-specific outcome effect |
Random-parameter distributions: normal, lognormal, negative_lognormal,
triangular, uniform.
get_help('variables') # full role and distribution reference
Search algorithms
| Alias | Algorithm | Best for |
|---|---|---|
sa |
Simulated Annealing | Robust default; escapes local minima |
de |
Differential Evolution | Thorough population search; multi-objective |
hs |
Harmony Search | Fast initial convergence |
hc |
Hill Climbing | Greedy local search |
agds |
SparseEA-AGDS | Many candidate variables; most should be excluded |
delphos_rl |
Delphos reinforcement learning | RL-driven search through the copilot driver |
result_sa = builder.run(evaluator, algo='sa', max_iter=2000, seed=42)
result_de = builder.run(evaluator, algo='de', max_iter=2000, seed=42)
result_hs = builder.run(evaluator, algo='hs', max_iter=2000, seed=42)
For a Pareto search over BIC and test error:
evaluator = builder.build_evaluator(
variables=['AADT', 'LENGTH', 'SPEED', 'CURVES'],
constraints=c,
mode='multi',
R=200,
)
result = builder.run(evaluator, algo='de', max_iter=2000, seed=42)
Count search
evaluator = builder.build_count_evaluator(
variables=['AADT', 'LENGTH', 'SPEED', 'CURVES', 'URB', 'AVEPRE'],
constraints=c,
default_roles=[0, 1, 2, 3, 5],
max_latent_classes=1,
R=200,
)
result = builder.run(evaluator, algo='sa', max_iter=2000, seed=42)
fit = builder.fit_manual_model(
manual_spec=result['model_spec'], model='nb', R=500)
Manual specification:
spec = builder.make_manual_spec(
fixed_terms=['AADT', 'LENGTH', 'SPEED'],
rdm_terms=['CURVES:normal'],
rdm_cor_terms=['TANGENT:normal', 'SLOPE:lognormal'],
hetro_in_means=['AVEPRE'],
zi_terms=['ACCESS'],
membership_terms=['URB'],
dispersion=1,
latent_classes=2,
)
fit = builder.fit_manual_model(manual_spec=spec, model='nb', R=200)
CMF search
from metacountregressor import CMFExperimentBuilder
cmf = CMFExperimentBuilder(
df=df,
y_col='FREQ',
aadt_col='AADT',
baseline_vars=['URB', 'ACCESS', 'GRADEBR', 'CURVES'],
local_vars=['CURVES', 'WIDTH'],
)
# Full JAX route: random parameters, latent classes, zero inflation
builder_jax, evaluator_jax, meta = cmf.build_jax_count_evaluator(
id_col='ID',
offset_col='OFFSET',
constraints=c,
max_latent_classes=1,
R=200,
)
result = builder_jax.run(evaluator_jax, algo='sa', max_iter=500, seed=42)
# Classic GA route: fast two-component structure
search = cmf.run_search(R=200)
fit = cmf.fit_best_model(search, final_R=500)
cmf.print_report(search, fit)
Manual CMF specification:
manual_cmf_spec = cmf.make_manual_cmf_spec(
baseline_fixed=['URB'],
baseline_correlated=['ACCESS'],
local_random=['CURVES'],
local_correlated=['SLOPE'],
hetro_in_means=['AVEPRE'],
zi_terms=['INTECHAG'],
membership_terms=['FC_ENCODED'],
dispersion=1,
latent_classes=2,
)
cmf_fit = cmf.fit_manual_cmf_model(
id_col='ID',
offset_col='OFFSET',
group_id_col='FC',
manual_spec=manual_cmf_spec,
model='nb',
R=200,
)
For the legacy GA driver:
legacy_cmf = builder.build_evaluator(
model_family='cmf',
cmf_driver='ga',
aadt_col='AADT',
baseline_vars=['URB', 'ACCESS'],
local_vars=['CURVES', 'SLOPE'],
)
Duration search
from metacountregressor import load_example_duration_data
duration_df = load_example_duration_data()
duration_builder = ExperimentBuilder(
df=duration_df, id_col='ID', y_col='DURATION', group_id_col='FC')
evaluator = duration_builder.build_evaluator(
variables=['WIDTH', 'CURVES', 'SLOPE', 'URB', 'FC_ENCODED'],
model_family='duration',
default_roles=[0, 1, 2, 3],
max_latent_classes=1,
R=200,
)
result = duration_builder.run(evaluator, algo='sa', max_iter=500, seed=42)
fit = duration_builder.fit_manual_model(
manual_spec=result['model_spec'], model='lognormal', R=500)
Time until the next speeding vehicle:
from metacountregressor import load_example_platform_gap_duration_data
gap_df = load_example_platform_gap_duration_data()
gap_builder = ExperimentBuilder(
df=gap_df,
id_col='PLATFORM_ID',
y_col='DURATION_UNTIL_NEXT_SPEEDING',
)
evaluator = gap_builder.build_evaluator(
variables=['PRECEDING_VEHICLE_SPEED', 'FOLLOWING_VEHICLE_SPEED',
'POSTED_SPEED', 'PLATFORM_HEIGHT', 'PLATFORM_WIDTH',
'APPROACH_VOLUME'],
model_family='duration',
budget_col='POSTED_SPEED',
default_roles=[0, 1, 2, 3, 4, 5, 7, 8],
max_latent_classes=2,
R=200,
)
result = gap_builder.run(evaluator, algo='sa', max_iter=1500, seed=22)
Linear search
from metacountregressor import load_example_platform_speed_data
speed_df = load_example_platform_speed_data()
speed_builder = ExperimentBuilder(
df=speed_df, id_col='PLATFORM_ID', y_col='SPEED', offset_col=None)
evaluator = speed_builder.build_evaluator(
variables=['DIST_TO_PLATFORM', 'POSTED_SPEED', 'APPROACH_ACCEL',
'PLATFORM_HEIGHT', 'PLATFORM_WIDTH'],
model_family='linear',
default_roles=[0, 1, 2, 3],
max_latent_classes=1,
R=200,
)
result = speed_builder.run(evaluator, algo='sa', max_iter=500, seed=42)
fit = speed_builder.fit_manual_model(
manual_spec=result['model_spec'], model='gaussian', R=500)
Tobit search
Use model_family='tobit' when a continuous outcome piles up at a lower bound,
such as zero:
tobit_builder = ExperimentBuilder(df, id_col='ID', y_col='OUTCOME')
evaluator = tobit_builder.build_evaluator(
variables=['X1', 'X2', 'X3', 'GROUP'],
model_family='tobit',
default_roles=[0, 1, 2, 3, 5],
max_latent_classes=2,
R=200,
)
result = tobit_builder.run(evaluator, algo='sa', max_iter=500, seed=42)
Survival search
Survival search needs an event_col with a 0/1 right-censoring flag:
surv_builder = ExperimentBuilder(
df=surv_df,
id_col='ID',
y_col='DURATION',
event_col='EVENT',
group_id_col='GROUP',
)
evaluator = surv_builder.build_evaluator(
variables=['X1', 'X2', 'X3'],
model_family='survival',
family='weibull_ph', # weibull, lognormal, loglogistic also available
default_roles=[0, 1, 2, 3, 5],
R=200,
)
result = surv_builder.run(evaluator, algo='sa', max_iter=500, seed=42)
family='weibull_ph' reports hazard ratios. The AFT families report time
ratios.
Multivariate search
Use activity_cols for several correlated count outcomes per person:
mv_builder = ExperimentBuilder(df, id_col='PERSON_ID', y_col='N_WORK')
mv_problem = mv_builder.build_search(
model_family='multivariate',
activity_cols=['N_WORK', 'N_SHOP', 'N_REC', 'N_EAT'],
variables=['AGE', 'INCOME', 'CARS', 'HHSIZE'],
offset_col=None,
)
mv_result = mv_problem.run(algo='sa', max_iter=500, seed=42)
The search selects variables for each activity while the copula captures dependence between activities.
Latent-class search
c = (
ModelConstraints()
.membership_only('FC_ENCODED')
.force_include('OFFSET')
.no_zi('LENGTH', 'CURVES', 'WIDTH', 'SLOPE')
.no_random('URB', 'GRADEBR')
)
evaluator = builder.build_evaluator(
variables=['URB', 'ACCESS', 'GRADEBR', 'CURVES', 'LENGTH',
'SPEED', 'WIDTH', 'SLOPE', 'AVEPRE', 'FC_ENCODED'],
constraints=c,
default_roles=[0, 1, 2, 3, 5, 7, 8],
max_latent_classes=2,
R=150,
)
result = builder.run(evaluator, algo='sa', max_iter=500, seed=1)
spec = builder.make_manual_spec(
fixed_terms=['AADT', 'SPEED', 'LENGTH'],
rdm_cor_terms=['CURVES:normal', 'SLOPE:normal'],
hetro_in_means=['AVEPRE'],
membership_terms=['URB', 'ACCESS', 'GRADEBR'],
dispersion=1,
latent_classes=2,
)
fit = builder.fit_manual_model(manual_spec=spec, model='nb', R=200)
class_probs = builder.compute_latent_class_probabilities(
fit, true_class_col='FC_ENCODED')
print(class_probs.head())
Pre-specified reference model:
from metacountregressor import (
load_book_latent_class_spec,
describe_book_latent_class_spec,
)
describe_book_latent_class_spec()
spec = load_book_latent_class_spec()
fit = builder.fit_manual_model(manual_spec=spec, model='nb', R=200)
Bayesian compilation
The Bayesian compiler preserves the selected structure and rebuilds its likelihood in PyMC:
python -m pip install "metacountregressor[bayesian]"
result = builder.run_search(evaluator, algo='sa', max_iter=3000, seed=7)
bayesian = builder.build_bayesian_model(result)
idata = bayesian.sample(draws=1000, tune=1000, chains=4, target_accept=0.9)
The compiler covers count and CMF, Gaussian linear, Tobit, and duration models,
including independent, grouped, and correlated random parameters,
heterogeneity, zero inflation, and latent classes. Count searches
marked as negative binomial compile to the mean-linked negative-binomial
Lindley likelihood; use model='nbl' for an explicit specification.
Pavement's combined regression/Markov/hazard search and multivariate copula results are rejected explicitly until their full joint likelihoods have dedicated compilers.
For NBL, the conditional model is negative binomial with success probability
exp(-U) and U ~ Lindley(theta). The compiler uses the closed-form marginal
likelihood and sets r = mu / h(theta), so mu = exp(X beta + offset) remains
the marginal mean. Adjust the prior with priors={'nbl_theta_scale': 2.0}.
Output and results
Pass a SearchOutputConfig to write one JSON file per run:
from metacountregressor import SearchOutputConfig
output_config = SearchOutputConfig(
output_dir='results',
experiment_name='example16_3_count',
search_description='NB count search on Example 16-3',
save_json=True,
checkpoint_every=200, # optional: write a resumable checkpoint
)
result = builder.run(
evaluator, algo='sa', max_iter=2000, output_config=output_config)
print(result['saved_to'])
The file is named
<experiment_name>_<family>_<algorithm>_<timestamp>.json and contains the
configuration, family, algorithm, metadata, best score, and best
specification.
Rank several runs:
import json
import pathlib
runs = [json.loads(p.read_text()) for p in pathlib.Path('results').glob('*.json')]
best = min(runs, key=lambda run: run['result']['best_score'])
print(best['result']['best_score'], best['algorithm'])
A checkpoint is written to <experiment_name>_checkpoint.json. Pass
checkpoint["best_decision"] as init_solutions to warm-start a rerun.
print_coefficients(fit) returns a DataFrame, so fitted tables can be
exported directly:
from pathlib import Path
coef_df = builder.print_coefficients(fit)
slide_dir = Path('results/slide_assets')
slide_dir.mkdir(parents=True, exist_ok=True)
(slide_dir / 'fit_coefficients.md').write_text(
coef_df.to_markdown(index=False), encoding='utf-8')
HPC search
On PBS/Torque or SLURM, the package reads the scheduler walltime and uses it as
a max_time limit:
| Scheduler | Environment variable | Format |
|---|---|---|
| PBS/Torque | PBS_WALLTIME |
HH:MM:SS |
| SLURM | SLURM_TIME_LIMIT |
seconds or HH:MM:SS |
Set it manually for local testing:
result = builder.run(
evaluator, algo='sa', max_iter=99999, max_time=3600)
PBS example:
#!/bin/bash
#PBS -N metacount_sa
#PBS -l nodes=1:ppn=4
#PBS -l walltime=04:00:00
#PBS -l mem=16gb
#PBS -j oe
#PBS -o logs/sa_seed42.log
module load python/3.11
cd $PBS_O_WORKDIR
source venv/bin/activate
python run_experiment.py sa 42 200 99999
SLURM array example:
#!/bin/bash
#SBATCH --job-name=metacount
#SBATCH --nodes=1
#SBATCH --ntasks=4
#SBATCH --time=04:00:00
#SBATCH --mem=16G
#SBATCH --output=logs/%j.log
#SBATCH --array=1-10
module load python/3.11
source venv/bin/activate
python run_experiment.py sa $SLURM_ARRAY_TASK_ID 200 99999
See the
05_batch_script_tutorial.ipynb
for a reusable run_experiment.py template and result-collection scripts.
GPU acceleration
The package runs on CPU out of the box and uses a GPU automatically when JAX can see one:
pip install -U "jax[cuda]"
from metacountregressor import device_summary
print(device_summary())
| Concern | Default | Override |
|---|---|---|
| Platform | Auto-detect GPU, else CPU | METACOUNT_JAX_PLATFORM=cpu, gpu, or tpu |
| Float precision | float64 enabled | - |
| GPU memory | Grows on demand | METACOUNT_GPU_PREALLOCATE=1 for exclusive nodes |
| Out-of-memory | Retry after clearing caches, then fall back to CPU | - |
Common validation errors
The package raises clear errors rather than fitting something wrong:
- a column named in
id_col,y_col,offset_col,group_id_col,variables, or a constraint that does not exist in the data - family-specific arguments passed to the wrong family
- a CMF specification without
aadt_col,baseline_vars, orlocal_vars - CMF data with non-positive
AADT - survival search without
event_col - latent-class probabilities requested from a single-class fit
Citation
@software{metacountregressor,
author = {Ahern, Zeke and Corry, Paul and Paz, Alexander},
title = {metacountregressor: JAX-first hierarchical search and fitting
for count, CMF, duration, linear, survival, and multivariate models},
url = {https://github.com/zahern/MetaCount},
}
Getting help
- Start with the worked examples.
- Ask the package itself:
get_help()lists every built-in guide. - Report a bug or request a feature at github.com/zahern/MetaCount/issues.
Metadata
Release files for metacountregressor 1.0.224
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| metacountregressor-1.0.224.tar.gz | 6.4 MB | Without provenance | Details for metacountregressor-1.0.224.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| metacountregressor-1.0.224-py3-none-any.whl | Python 3 | none | any | Details for metacountregressor-1.0.224-py3-none-any.whl |
Total release size: 13.7 MB
Release files / metacountregressor-1.0.224.tar.gz
| Download URL | metacountregressor-1.0.224.tar.gz |
|---|---|
| Size | 6.4 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c34548295ca81dafb0bdbe7977653f3f8ba264696cab15ebae7649dfaeedb4a9
|
|
BLAKE2b-256 checksum How to use checksums |
927616802d6186121fc5ff5c02d36535101eaa45db35c898af8e1b0473e96f30
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / metacountregressor-1.0.224-py3-none-any.whl
| Download URL | metacountregressor-1.0.224-py3-none-any.whl |
|---|---|
| Size | 7.3 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
07e687bc726a166eeef698858666dd15f1210c3061d3e4d678779c3531729340
|
|
BLAKE2b-256 checksum How to use checksums |
fe631473a464833602fc9191e59f8c6643abab85909a6eddc82f1a80b3141e86
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for metacountregressor 1.0.224
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.