metacountregressor
A JAX-first Python package for hierarchical model fitting and metaheuristic-driven model structure search. Supports count, CMF, duration, and linear models with random parameters, latent classes, zero-inflation, and heterogeneity in means - all with one unified API.
How to use this page
Five steps, in order. Everything after them is reference.
| In order | Section | You end up with |
|---|---|---|
| 1 | Install | the package importable |
| 2 | Tutorials & resources | notebooks on disk |
| 3 | Quick start | a fitted specification and its BIC |
| 4 | Where your run's results appear | one JSON per run |
| 5 | Use your own data | your data fitted |
Reference:
- What the package does
- Data loaders
- ExperimentBuilder API
- ModelConstraints API
- Bayesian Compilation
- Role codes
- Search algorithms
- Model families
- Latent class models
- Help system
- Running on HPC clusters
- Common validation errors
- Getting help
Install
pip install metacountregressor
pip install jax jaxlib jaxopt # JAX backend
Quick import check:
python -c "from metacountregressor import __version__, load_example16_3_raw_data; print(__version__, load_example16_3_raw_data().shape)"
To work on the package itself, install the checkout in editable mode:
python -m pip install -e .
The PyPI install above is the normal user path.
Optional: let the copilot wizard write the specification
From version 1.0.216, the installed package includes an interactive
experiment-setup wizard. No separate metacount-copilot package is needed:
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 RL search:
python -m metacountregressor.copilot
GPU acceleration (optional)
The package runs on CPU out of the box and automatically uses a GPU when JAX can see one - no code changes required. Install the CUDA flavour of JAX instead of the CPU wheel:
pip install -U "jax[cuda]"
Verify what the package picked up:
from metacountregressor import device_summary
print(device_summary())
# e.g. metacountregressor JAX 0.6.2 | backend=cuda | devices=[CpuDevice(id=0), CudaDevice(id=0)] | x64=True | gpu_preallocate=False
Behaviour and controls:
| Concern | Default | Override |
|---|---|---|
| Platform choice | Auto-detect (GPU if visible, else CPU) | METACOUNT_JAX_PLATFORM=cpu|gpu|tpu or configure_jax(platform='cpu') |
| Float precision | float64 enabled (required by the estimators) | - |
| GPU memory | Grows on demand - safe for shared clusters (XLA's default grabs ~75% of VRAM up front) | METACOUNT_GPU_PREALLOCATE=1 for exclusive nodes |
| GPU out-of-memory | Fits transparently retry once after clearing JAX caches, then fall back to the CPU device instead of crashing the search | - |
Transient GPU failures never poison a structure search: candidate structures that fail only because of device memory are retried, not blacklisted.
Tutorials & resources
Everything you need to learn the package in one place.
Bundled notebook tutorials
Six tutorial notebooks ship inside the wheel and use the bundled Example 16-3 crash-frequency dataset, so every cell runs out of the box - no need to source your own data. Copy them into your working directory:
from metacountregressor import get_templates
get_templates() # copies all six .ipynb files to the current folder
| # | Notebook | What you learn | Time |
|---|---|---|---|
| 00 | 00_quickstart.ipynb | Install, load bundled data, first search run end-to-end | ~10 min |
| 01 | 01_crash_frequency_search.ipynb | Mixed Negative Binomial search - constraints, roles, re-fit with more draws | ~20 min |
| 02 | 02_latent_class_fc_validation.ipynb | 2-class latent class model - fit, extract class probabilities, validate against functional class | ~20 min |
| 03 | 03_cmf_aadt_search.ipynb | CMF model - baseline + AADT-interaction structure search | ~20 min |
| 04 | 04_linear_speed_prediction.ipynb | Gaussian linear model search (platform speed prediction) | ~20 min |
| 05 | 05_batch_script_tutorial.ipynb | Batch scripts, parallel seeds, PBS/SLURM HPC job templates, result collection | ~30 min |
Browse them online in the templates folder or open locally:
jupyter lab # after get_templates(), the notebooks are in your working directory
Worked example scripts & extended walkthroughs
| Resource | Format | Link |
|---|---|---|
| Hierarchical CMF tutorial (full worked analysis) | Python script | examples/manual_hierarchical_cmf_tutorial.py |
| Hierarchical CMF narrative guide | Markdown | examples/TUTORIAL_HIERARCHICAL_CMF.md |
| General tutorial (search -> fit -> interpret) | Jupyter notebook | Tutorial.ipynb |
| Batch / HPC workflow deep dive | Jupyter notebook | Tutorial_Batch.ipynb |
| Batch / HPC workflow deep dive | Markdown | Tutorial_Batch.md |
| CMF vs count, for a non-technical audience | Notebook | cmf_vs_count_general_audience.ipynb |
| CMF vs count, slide deck | Markdown | cmf_vs_count_comparison_slides.md |
Export the slide deck to PDF with
npx @marp-team/marp-cli cmf_vs_count_comparison_slides.md --pdf --allow-local-files,
or render it with Quarto:
quarto render cmf_vs_count_comparison_slides.md --to beamer.
Built-in help system (no internet needed)
Every workflow has a printable guide built into the package:
from metacountregressor import get_help
get_help() # list all available topics
| Topic | Contents |
|---|---|
get_help('roles') |
Role-code reference (0-8) and random-parameter distributions |
get_help('constraints') |
Full ModelConstraints API with examples |
get_help('metaheuristics') |
SA / DE / HS comparison and tuning parameters |
get_help('crash_frequency') |
End-to-end count-model workflow |
get_help('latent_class') |
Latent-class workflow incl. class-probability extraction |
get_help('cmf') |
Crash Modification Factor workflows (both routes) |
get_help('linear') |
Gaussian linear model workflow |
get_help('duration') |
Duration / survival model workflow |
get_help('batch') |
Batch scripts, walltime detection, PBS/SLURM templates |
Other resources
- Source code & issue tracker: github.com/zahern/MetaCount
- Report a bug / request a feature: GitHub Issues
- Release history: PyPI release history
- Example datasets: bundled loaders are documented in Data loaders below; every loader returns a plain
pandas.DataFrame.
Quick start
You do not need the reference dataset, a source checkout, an HPC account, or PBS to start.
import numpy as np
from metacountregressor import (
ExperimentBuilder,
ModelConstraints,
SearchOutputConfig,
load_example16_3_model_data,
get_help,
)
# 1. Load the bundled crash-frequency dataset
df = load_example16_3_model_data()
exposure = df['LENGTH'] * df['AADT'] * 365 / 1e8
df['OFFSET'] = np.log(exposure.clip(lower=1e-9))
# 2. Build constraints
c = (
ModelConstraints()
.force_include('OFFSET')
.no_zi('LENGTH', 'CURVES', 'WIDTH', 'SLOPE')
.no_random('URB')
.allow_random('CURVES', distributions=['lognormal'])
.mutual_exclusion(['SPEED', 'CURVES']) # at most one active at a time
)
# 3. Create the experiment
builder = ExperimentBuilder(df, id_col='ID', y_col='FREQ', offset_col='OFFSET')
builder.describe() # print data summary
get_help('crash_frequency') # print end-to-end workflow guide
# 4. Build the structure evaluator
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,
)
# 5. Run the search
result = builder.run(
evaluator,
algo='sa', # 'sa' | 'de' | 'hs'
max_iter=1000,
seed=42,
output_config=SearchOutputConfig(output_dir='results', experiment_name='demo'),
)
print('Best BIC:', result['best_score'])
print('Saved to:', result.get('saved_to'))
# 6. Re-fit with more draws
fit = builder.fit_manual_model(manual_spec=result['model_spec'], model='nb', R=500)
print(fit)
Where your run's results appear
A search keeps its result in memory until you give it somewhere to write. Pass a SearchOutputConfig to run() (or to run_search()) and every run writes one JSON file:
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,
)
result = builder.run(evaluator, algo='sa', max_iter=2000, output_config=output_config)
print(result['saved_to']) # results/example16_3_count_count_sa_20261120_161500.json
The file is written to output_dir as <experiment_name>_<family>_<algorithm>_<timestamp>.json and holds:
config- the output configuration, including the experiment name and descriptionfamilyandalgorithm- which model family and search ranmetadata- hyperparameters used, candidate variables, elapsed timeresult- the normalized result payload, includingbest_score(BIC) and the best specification
result['saved_to'] is the path just written. Without output_config nothing is saved and the run exists only in memory. To rank the runs in a folder afterwards:
import json, 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'], best['config']['experiment_name'])
A long search survives a walltime kill by setting checkpoint_every (for example checkpoint_every=200). The incumbent is written atomically to <experiment_name>_checkpoint.json during the search, and checkpoint["best_decision"] from that file can be passed as init_solutions to warm-start a rerun.
Exporting fitted output to Markdown or Marp slides
print_coefficients(fit) returns the coefficient table as a DataFrame, so
the same numbers can go straight into a notebook, a Markdown table, or a Marp
deck:
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')
(slide_dir / 'fit_coefficients.html').write_text(
coef_df.to_html(index=False), encoding='utf-8')
The 00_quickstart and 05_batch_script_tutorial notebooks use this pattern.
Use your own data
Keep the Quick Start structure and change only the data mapping:
| Quick Start piece | Replace with your data |
|---|---|
load_example16_3_model_data() |
pd.read_csv('my_segments.csv') |
id_col='ID' |
your row-identifier column |
y_col='FREQ' |
your outcome column (counts, durations, speeds...) |
offset_col='OFFSET' |
your log-exposure column, or None |
group_id_col='FC' |
your grouping column, or None |
variables=[...] |
your candidate predictor columns |
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() # check column types before searching
For a first run on your data, keep the search small - default_roles=[0, 1, 2],
R=50, max_iter=20 - then refit the winning specification with a larger
R for final standard errors. Pick the worked notebook matching your outcome
from Tutorials & resources and mirror its constraint
block.
What the package does
metacountregressor solves two related problems:
-
Structure search - automatically discover which variables to include, whether each coefficient should be fixed or random, and whether the model needs latent classes, zero-inflation, or heterogeneity in means. The search is driven by metaheuristic algorithms (SA, DE, HS) that minimise BIC.
-
Model estimation - fit the discovered (or manually specified) model structure using JAX-accelerated simulation-based maximum likelihood with Halton draws.
The same API handles crash-frequency count models, CMF (Crash Modification Factor) models, duration models, and linear (Gaussian) models.
Data loaders
All loaders return a pandas.DataFrame.
from metacountregressor import (
load_example16_3_raw_data, # Example 16-3: original 31 columns
load_example16_3_model_data, # + OFFSET, FC_ENCODED, FC_LABEL
load_example_crash_data, # alias for load_example16_3_model_data
load_example_duration_data, # synthetic duration target from Ex 16-3
load_example_linear_data, # synthetic linear target from Ex 16-3
load_example_platform_speed_data, # speed relative to platform
load_example_platform_gap_duration_data, # time until next speeding event
load_example_panel_data, # panel-structure example
)
Example 16-3 columns
load_example16_3_raw_data() returns the original source columns:
| Group | Columns |
|---|---|
| Identifiers | ID |
| Outcome | FREQ |
| Geometry | LENGTH, WIDTH, INCLANES, DECLANES, MEDWIDTH, MIMEDSH, MXMEDSH |
| Speed / grade | SPEED, MIGRADE, MXGRADE, MXGRDIFF, SLOPE |
| Traffic | AADT, SINGLE, DOUBLE, TRAIN, PEAKHR, ADTLANE |
| Road class | URB, FC, ACCESS, TANGENT, CURVES, MINRAD, GRADEBR |
| Friction / weather | FRICTION, INTECHAG, AVEPRE, AVESNOW |
load_example16_3_model_data() adds OFFSET, FC_ENCODED, FC_LABEL.
ExperimentBuilder API
from metacountregressor import ExperimentBuilder
builder = ExperimentBuilder(
df=df,
id_col='ID', # required - observation identifier
y_col='FREQ', # required - outcome variable
offset_col='OFFSET', # optional - log-exposure offset (count models)
group_id_col='FC', # optional - group/panel identifier
)
Which arguments can be None
In ExperimentBuilder(...), id_col and y_col are required; offset_col and
group_id_col accept None. In build_evaluator(...), variables,
fixed_override, membership_override, exclude and default_roles are all
optional: leave one out and the builder uses every candidate column, no
per-variable override, or the family default. In the CMF helpers, offset_col,
group_id_col and variables accept None.
Key methods
| Method | Purpose |
|---|---|
builder.describe() |
Print data summary: N, outcome stats, variable types |
builder.suggest_config(max_latent_classes=2) |
Print recommended ExperimentBuilder settings |
builder.build_evaluator(...) |
Build a structure evaluator (see below) |
builder.build_count_evaluator(...) |
Shortcut for count models |
builder.run(evaluator, algo, max_iter, seed, ...) |
Run metaheuristic search |
builder.run_search(evaluator, ...) |
Alias for run() |
builder.make_manual_spec(...) |
Build a model spec dict manually |
builder.fit_manual_model(manual_spec, model, R) |
Fit a manually specified structure |
builder.build_bayesian_model(search_result, ...) |
Compile the selected structure into a PyMC model |
builder.compute_latent_class_probabilities(fit, true_class_col) |
Get class membership probabilities |
ExperimentBuilder.get_family_capabilities() |
Static: list supported model families |
ExperimentBuilder.get_search_argument_guide() |
Static: full argument documentation |
build_evaluator arguments
evaluator = builder.build_evaluator(
variables=['AADT', 'LENGTH', 'SPEED', 'CURVES'], # candidate columns
constraints=c, # ModelConstraints object
model_family='count', # 'count' | 'cmf' | 'duration' | 'linear'
default_roles=[0, 1, 2, 3, 5], # roles the search may assign
max_latent_classes=2, # 1 = standard, 2 = allow LC
mode='single', # 'single' = minimise BIC
R=200, # Halton simulation draws
# CMF-only arguments:
aadt_col='AADT',
baseline_vars=['URB', 'ACCESS'],
local_vars=['CURVES', 'WIDTH'],
# Duration-only:
budget_col='AADT',
)
Per-variable role restrictions, without building a ModelConstraints object:
evaluator = builder.build_evaluator(
variables=['AADT', 'SPEED', 'URB'],
fixed_override={'AADT': [1]}, # AADT restricted to role 1
membership_override={'URB': [7, 8]}, # URB restricted to membership roles
)
R trades time for accuracy: a small R (50) is enough to rank structures
during the search, and a large R (500) is for the final standard errors.
ModelConstraints API
ModelConstraints restricts which roles and distributions each variable may take.
All methods return self for chaining.
from metacountregressor import ModelConstraints
c = (
ModelConstraints()
.force_include('OFFSET') # cannot be excluded
.force_fixed('AADT') # only fixed or excluded
.no_zi('LENGTH', 'CURVES', 'SLOPE', 'WIDTH') # cannot be ZI term
.no_random('URB', 'GRADEBR') # no random parameter
.allow_random('CURVES', distributions=['lognormal']) # restrict distribution
.membership_only('FC_ENCODED') # drives class prob only
.allow_membership('SPEED') # may also enter membership
.outcome_only('AADT') # no membership role
.exclude('YEAR', 'ID') # removed from search
.mutual_exclusion(['SPEED', 'SPEED_50']) # never both in the model
.set_roles('WIDTH', [0, 1, 2]) # low-level override
)
print(c) # display all constraints
c.summary() # same as print(c)
Bayesian Compilation
The Bayesian compiler preserves the selected structure from a completed JAX search and rebuilds its likelihood in PyMC. Install it as an optional extra:
python -m pip install "metacountregressor[bayesian]"
Then compile and sample without rerunning the structural search:
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 first compiler covers count/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 (NBL)
likelihood; use model='nbl' for an explicit specification. Legacy CMF
results can be compiled with CMFExperimentBuilder.build_bayesian_model(...);
pass id_col when random effects should vary by panel unit. 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. It samples theta = 2 + theta_excess to ensure finite
variance. Adjust the prior with priors={'nbl_theta_scale': 2.0}.
mutual_exclusion prevents multicollinearity or redundancy by ensuring at most one variable per group is active. Pass multiple groups for multiple exclusivity rules:
c = ModelConstraints().mutual_exclusion(
['SPEED', 'SPEED_50'], # speed definitions
['AADT', 'ADTLANE'], # traffic volume measures
['TANGENT', 'CURVES'], # alignment descriptors
)
Get detailed API documentation:
from metacountregressor import get_help
get_help('constraints')
Role codes
| Code | Name | Description |
|---|---|---|
0 |
Excluded | Variable not in the model |
1 |
Fixed | Same coefficient for every observation |
2 |
Random (ind.) | Individual random effect, independent draws |
3 |
Random (corr.) | Individual random effect, correlated with others |
4 |
Grouped | Group-level random effect (shared within group) |
5 |
Heterogeneity | Explains variation in random-parameter means |
6 |
Zero Inflation | Enters the zero-inflation probability equation |
7 |
Membership only | Drives latent-class probability - not the outcome |
8 |
Membership + Fixed | Drives class membership AND has class-specific outcome effect |
Random-parameter distributions: normal, lognormal, triangular, uniform.
get_help('roles') # full reference with examples
Search algorithms
| Alias | Algorithm | Best for |
|---|---|---|
'sa' |
Simulated Annealing | Robust default - escapes local minima via cooling schedule |
'de' |
Differential Evolution | Thorough population-based search - use when SA converges early |
'hs' |
Harmony Search | Fast initial convergence - good for a quick first pass |
'hc' |
Hill Climbing | Greedy local search |
# Run the same evaluator with different algorithms
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)
get_help('metaheuristics') # full parameter reference
Model families
Count models (Poisson / Negative Binomial)
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 spec:
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 models
from metacountregressor import CMFExperimentBuilder
cmf = CMFExperimentBuilder(
df=df,
y_col='FREQ',
aadt_col='AADT',
baseline_vars=['URB', 'ACCESS', 'GRADEBR', 'CURVES'],
local_vars=['CURVES', 'WIDTH'],
)
# Route A: full JAX flexibility (random params, LC, ZI)
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)
# Route B: classic GA search (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
from metacountregressor import CMFExperimentBuilder
cmf_builder = CMFExperimentBuilder(
df=df,
y_col='FREQ',
aadt_col='AADT',
baseline_vars=['URB', 'ACCESS'],
local_vars=['CURVES', 'SLOPE'],
)
manual_cmf_spec = cmf_builder.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_builder.fit_manual_cmf_model(
id_col='ID',
offset_col='OFFSET',
group_id_col='FC',
manual_spec=manual_cmf_spec,
model='nb',
R=200,
)
Legacy GA route
cmf_driver='ga' selects the classic GA search instead of the default
'jax_count' architecture:
legacy_cmf = builder.build_evaluator(
model_family='cmf',
cmf_driver='ga',
aadt_col='AADT',
baseline_vars=['URB', 'ACCESS'],
local_vars=['CURVES', 'SLOPE'],
)
get_help('cmf') # full workflow guide
Duration models
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)
fit = gap_builder.fit_manual_model(
manual_spec=result['model_spec'], model='lognormal', R=200)
Linear models
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], # no ZI for linear
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)
Speed relative to a platform
load_example_platform_speed_data() also carries RELATIVE_SPEED and
PLATFORM_TYPE, which suit a mixed-effects style model of speed relative to
the platform:
platform_df = load_example_platform_speed_data()
platform_builder = ExperimentBuilder(
df=platform_df, id_col='PLATFORM_ID', y_col='RELATIVE_SPEED',
offset_col=None, group_id_col='PLATFORM_TYPE')
evaluator = platform_builder.build_evaluator(
variables=['DIST_TO_PLATFORM', 'POSTED_SPEED', 'APPROACH_ACCEL',
'PLATFORM_HEIGHT', 'PLATFORM_WIDTH', 'AT_PLATFORM'],
model_family='linear',
default_roles=[0, 1, 2, 3, 4, 5, 7, 8],
max_latent_classes=2, R=200,
)
Latent class models
# 1. Constrain FC_ENCODED to drive class membership only
c = (
ModelConstraints()
.membership_only('FC_ENCODED')
.force_include('OFFSET')
.no_zi('LENGTH', 'CURVES', 'WIDTH', 'SLOPE')
.no_random('URB', 'GRADEBR')
)
# 2. Build LC evaluator (max_latent_classes=2, include roles 7 & 8)
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,
)
# 3. Run search
result = builder.run(evaluator, algo='sa', max_iter=500, seed=1)
# 4. Manually fit a specific structure
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)
# 5. Extract class membership probabilities
class_probs = builder.compute_latent_class_probabilities(
fit, true_class_col='FC_ENCODED')
print(class_probs.head())
# 6. Compare predicted class vs actual FC
class_probs['predicted'] = (
class_probs[['class_1_prob', 'class_2_prob']].to_numpy().argmax(axis=1))
agreement = (class_probs['predicted'] == class_probs['FC_ENCODED']).mean()
print(f'Agreement with FC: {agreement:.1%}')
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)
get_help('latent_class') # full workflow guide
Help system
The package includes a built-in interactive help system:
from metacountregressor import get_help
get_help() # list all topics
get_help('roles') # role code table + distributions
get_help('constraints') # ModelConstraints API
get_help('metaheuristics') # algorithm comparison and parameters
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('duration') # duration model workflow
get_help('batch') # batch script and HPC guide
Running on HPC clusters
Automatic walltime detection
On PBS/Torque or SLURM, the package reads the scheduler walltime automatically and uses it as a max_time limit - the search stops cleanly before the job is killed.
| Scheduler | Environment variable | Format |
|---|---|---|
| PBS/Torque | PBS_WALLTIME |
HH:MM:SS |
| SLURM | SLURM_TIME_LIMIT |
seconds or HH:MM:SS |
Set manually for local testing:
result = builder.run(evaluator, algo='sa', max_iter=99999, max_time=3600)
PBS job script
#!/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
# Walltime auto-detected from PBS_WALLTIME
python run_experiment.py sa 42 200 99999
SLURM job array
#!/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 05_batch_script_tutorial.ipynb for a complete worked example including a reusable run_experiment.py template and result-collection scripts.
get_help('batch') # inline guide
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,variablesor a constraint that does not exist in the data - family-specific arguments passed to the wrong family
- a CMF specification without
aadt_col,baseline_varsorlocal_vars - CMF data with non-positive
AADT - latent-class probabilities requested from a single-class fit
Getting help
- Revisit the Tutorials & resources section - the six bundled notebooks cover the full API surface with runnable examples.
- Ask the package itself:
get_help()lists every built-in guide. - Found a bug or want a feature? Open an issue at github.com/zahern/MetaCount/issues.
If you use metacountregressor in research, please cite the package:
@software{metacountregressor,
author = {Ahern, Zeke and Corry, Paul and Paz, Alexander},
title = {metacountregressor: JAX-first hierarchical search and fitting
for count, CMF, duration, and linear models},
url = {https://github.com/zahern/MetaCount},
}
Metadata
Release files for metacountregressor 1.0.221
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.221.tar.gz | 6.4 MB | Without provenance | Details for metacountregressor-1.0.221.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| metacountregressor-1.0.221-py3-none-any.whl | Python 3 | none | any | Details for metacountregressor-1.0.221-py3-none-any.whl |
Total release size: 13.6 MB
Release files / metacountregressor-1.0.221.tar.gz
| Download URL | metacountregressor-1.0.221.tar.gz |
|---|---|
| Size | 6.4 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e2a48da118925a094702b97e26ae9fdf5dae09f68d84fdde17874f2203d4f249
|
|
BLAKE2b-256 checksum How to use checksums |
95b857f377900bcf87f293cb6a741392385fb599a4732ae637e8df4221e1e2fe
|
| 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.221-py3-none-any.whl
| Download URL | metacountregressor-1.0.221-py3-none-any.whl |
|---|---|
| Size | 7.2 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
97a0519e37908e7ae08140e7d44a4528fef7788392c5afd162df943f930e71ad
|
|
BLAKE2b-256 checksum How to use checksums |
f15f41766cbc87904b32e8d789458bf15dd9a3995d0cf0b4fb5dea7f9f95cf54
|
| 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.221
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.