Open-source Python library for matrix-based econometric inference: multivariate normal CDF evaluation with analytic gradients, and maximum-likelihood estimation of discrete-choice models (MNP, MORP, MDCEV, MNL).
The numerical core follows the GAUSS BHATLIB library by Chandra Bhat and colleagues (UT Austin / Aptech Systems) and implements Bhat's (2018) analytic MVNCD approximation.
pip install pybhatlib # core (NumPy + SciPy + Numba)
pip install "pybhatlib[torch]" # add PyTorch backend (optional GPU)From source (for development, or to run the bundled examples and tutorials):
git clone https://github.com/UMN-Choi-Lab/pybhatlib.git
cd pybhatlib
pip install -e . # core (NumPy + SciPy + Numba)
pip install -e ".[torch]" # add PyTorch backend (optional GPU)
pip install -e ".[dev]" # add pytest, ruff, mypy
pip install -e ".[all]" # everything (torch + dev)Sample data: examples/data/TRAVELMODE.csv (3 modes — DA / SR / TR, 1125 observations).
from pybhatlib.models.mnp import MNPModel, MNPControl
model = MNPModel(
data="examples/data/TRAVELMODE.csv",
alternatives=["Alt1_ch", "Alt2_ch", "Alt3_ch"],
availability="none",
spec={
"CON_SR": {"Alt1_ch": "sero", "Alt2_ch": "uno", "Alt3_ch": "sero"},
"CON_TR": {"Alt1_ch": "sero", "Alt2_ch": "sero", "Alt3_ch": "uno"},
"IVTT": {"Alt1_ch": "IVTT_DA", "Alt2_ch": "IVTT_SR", "Alt3_ch": "IVTT_TR"},
"OVTT": {"Alt1_ch": "OVTT_DA", "Alt2_ch": "OVTT_SR", "Alt3_ch": "OVTT_TR"},
"COST": {"Alt1_ch": "COST_DA", "Alt2_ch": "COST_SR", "Alt3_ch": "COST_TR"},
},
control=MNPControl(iid=True),
)
results = model.fit()
results.summary()from pybhatlib.models.morp import MORPModel, MORPControl
model = MORPModel(
data=df, # DataFrame or CSV path
dep_vars=["satisfaction", "recommendation"], # ordinal outcome columns
spec={
"income": {"satisfaction": "income", "recommendation": "income"},
"age": {"satisfaction": "age", "recommendation": "age"},
"education": {"satisfaction": "education", "recommendation": "education"},
},
n_categories=[3, 3],
control=MORPControl(iid=True, seed=42),
)
results = model.fit()
results.summary()A runnable end-to-end example (with morp_ate, morp_predict,
morp_predict_category) is at
examples/tutorials/t05b_morp_ate_predict.ipynb.
Models
- Multinomial Probit (MNP) — IID, flexible covariance, heteroscedastic-only, random coefficients, mixture-of-normals
- Multivariate Ordered Response Probit (MORP) — multiple ordinal outcomes
with shared covariance; per-outcome
specmapping - Multiple Discrete-Continuous Extreme Value (MDCEV) — traditional
(Bhat 2008) and linear outside-good utility specifications, selected via
MDCEVControl.utility - Multinomial Logit (MNL)
- Linear regression (LR) — single continuous outcome, closed-form OLS with classical / White-robust / BHHH standard errors
- Mixed / simulation-based models —
MixMNLModel,MNPKerCPModel,MORPFlexModel,MDCEVMixedModelon a shared maximum-simulated-likelihood engine (Halton draws, panel data, normal / log-normal / Yeo-Johnson coefficient transforms). New and under active refinement.
Numerical core
vecup— vecdup, matdupfull, LDLT decomposition, truncated MVN momentsmatgradient— gradcovcor, gomegxomegax, spherical / Cholesky parameterizationsgradmvn— Bhat (2018) MVNCD analytic approximation with analytic gradients
Estimation
- Multiple SE estimators (
se_method="bhhh" | "hessian" | "sandwich"); BHHH is the default to match GAUSS BHATLIB's_max_CovPar=2. All three are computed at fit time and exposed asse_bhhh/se_hessian/se_sandwich;results.summary()prints a side-by-side diagnostic block (a large Hessian/BHHH divergence is a misspecification signal). MNPControl.active_maskto freeze a subset of parameters at their starting values without recoding the model.verboselevels:0silent,1summary,2per-iteration NLL,3per-iteration parameter / gradient / relative-gradient table.loglik_constants(LL(C)): MNL/MNP use analytic empirical shares when all alternatives are available. Otherwise they fit shared alternative constants with each observation's availability, using basic MNL or IID MNP likelihoods. Mixed choice models use the same unmixed baselines. MORP/MORP-flex retain analytic independent threshold-only baselines, not correlated MORP null fits.- MDCEV/MDCEV-mixed LL(C) fits the basic MDCEV model with alternative constants
in both baseline utility and inside-good gamma, plus free sigma, preserving
traditional/linear utility, prices and weights. This adds an auxiliary fit;
mixed models do not simulate the baseline. Panel baselines assume independent
occasions and use the fitted model's individual weights and normalization.
Failed auxiliary fits return
NaN(shown asN/A) with a warning. External estimates without training data also haveN/Abaselines. MDCEV has no uniform LL(0); density-based likelihood comparisons require consistent units and numerical conventions. - Adjusted rho-squared uses total likelihoods:
1 - (LL - K) / LL(0)and1 - (LL - (K - Kc)) / LL(C). With stored mean likelihoods, parameter penalties are divided by the same case/individual count.Kretains the model's existing optimizer parameter count;Kccounts the baseline's constants (J - 1for choice models), thresholds (sum of category counts minus one per ordinal outcome), or utility/gamma constants plus sigma (2 * (J - 1) + 1for MDCEV). MDCEV summaries show only constants-based rho-squared measures. Unavailable baseline counts or zero baseline likelihoods produceN/Afor the affected adjusted statistic.
Backend
- NumPy by default; optional PyTorch backend with GPU support (install with
[torch]). All numerical functions take an optionalxpkwarg.
Post-estimation
- Average Treatment Effects (ATE) with scenario-matrix support, forecasting, per-category MORP probability prediction.
- MORP ATEs from supplied coefficients without re-fitting:
MORPResults.from_estimates(beta, thresholds, correlation)rebuilds a results object from natural-space estimates, andmorp_ate_from_params/morp_joint_probs(mean joint category-combination probabilities, the GAUSSate1.csvequivalent) compute effects directly from them.
MNP parameter-vector migration in #71:
results.params/startbuse optimizer coordinates. Each full random- coefficient covariance block is now[radial correlation coordinates | log SDs], replacing lower-Cholesky entries. Diagonal blocks still use log SDs. The vector length alone does not establish compatibility. Convert every segment's block; settingscaling="first"does not restore the old layout.- To migrate an old full covariance block, reconstruct
Omega = L_old @ L_old.T, obtainsd = sqrt(diag(Omega))andR = Omega / outer(sd, sd), and encode its correlation factor withrevnewcholparmscaled(np.linalg.cholesky(R).T, control.scal)frompybhatlib.matgradient._radial. Appendlog(sd). This assumes positive SDs and the same utility normalization; account separately for a change tosumsq. Zero-variance blocks need a positive starting value before encoding. b_originalreports correlations and SDs (corr[...],scal[...]) rather than the oldCovCOv*variances/covariances.omega_hatandsegment_covsretain covariance semantics. Convert old variances to SDs and off-diagonal covariances to correlations using the full covariance matrix. Reported uncertainty must be transformed too; an old variance SE is not an SD SE.- Optimizer segment coordinates remain logits relative to segment 1. Reporting
now uses probabilities:
segunparis the second-segment probability, andsegunpar_sNidentifies segments 2..N. Convert old reported logits withsoftmax([0, logits...]); convert probabilities back to optimizer logits withlog(p_segment / p_reference).segment_probscontains all weights. - Automatic starts now use SD
0.1and zero correlations in every segment, with equal mixture weights. In diagonal models this changes the SD start from1to0.1. Supplied starts are not silently converted. Changes in starting points may change the optimization path and local optimum.
For external IID MNP estimates, MNPResults.from_estimates and
mnp_ate_from_params interpret beta in control.scaling units. The default
remains "sumsq"; the coefficient vector alone cannot identify its original
normalization. For J alternatives, these two inputs give equivalent ATEs:
# GAUSS IID coefficients, kept in first-scale-equals-one units:
gauss_ate = mnp_ate_from_params(
beta_gauss, X=X, n_alts=J,
control=MNPControl(iid=True, scaling="first"),
)
# Equivalent coefficients in the library's default sumsq units:
default_ate = mnp_ate_from_params(beta_gauss / np.sqrt(J - 1), X=X, n_alts=J)For coefficients from a fitted pybhatlib model, reuse its scaling control.
For non-IID external inputs, provide the matching beta and kernel_cov pair;
the constructor normalizes them together without changing predictions.
pybhatlib reproduces Table 1 of the BHATLIB GAUSS reference implementation using the TRAVELMODE dataset (3 modes — DA, SR, TR; 1125 observations):
| Model | Specification | Target LL | Achieved LL | Status |
|---|---|---|---|---|
| (a)(i) | IID errors | -670.956 | -670.956 | exact match |
| (a)(ii) | Flexible covariance | -661.111 | -661.111 | exact match |
| (b) | + AGE45 demographics | -659.285 | -659.284 | exact match |
| (c) | + Random coeff. OVTT | -635.871 | -635.871 | exact match |
| (d) | 2-segment mixture | -634.975 | -632.912 | close (multi-modal) |
Models (a)–(c) reproduce the GAUSS estimates and BHHH standard errors to ≤0.001
on every parameter (verified end-to-end against GAUSS 26.1.1 + MaxLik 5.0.9).
Direct GAUSS coefficient/SE comparisons use MNPControl(scaling="first").
The default is now scaling="sumsq" (squared differenced kernel scales sum to
one), matching MNPKerCP's existing default. This changes reported units;
equivalent, consistently rescaled parameters give the same probabilities.
Use scaling="first" for externally supplied IID GAUSS coefficients.
startb always uses the selected optimizer coordinates; choosing first
does not undo other parameter-layout changes in this release.
Model (d) is multi-modal — the Python optimum is a slightly better local mode
than the GAUSS one.
For MORP, iid=False now uses GAUSS BHATLIB's unit-variance identification by
default (MORPControl.fix_scales=True): the latent-utility variances are fixed
at 1 and only correlations are estimated. The full-covariance MORP_DINING /
MORP_WALK models reproduce the GAUSS mean log-likelihoods (−4.6598 / −3.7591)
and correlation matrices. summary() reports the actual threshold cut-points
(with delta-method standard errors) and a gradient column, matching GAUSS's
output. See docs/plans/MORP_BHATLIB_PARITY.md.
The driving notebooks are
t04h_bhatlib_table1.ipynb and
t04i_bhat2018_table2.ipynb.
A complete tutorial series lives under
examples/tutorials/ as Jupyter notebooks (each with a
matching .py script under python_scripts/):
| Track | Notebooks |
|---|---|
| Foundations | t00_quickstart, t01a_vectorization, t01b_ldlt, t01c_truncated_mvn |
| Matrix gradients | t02a_gradcovcor, t02b_spherical, t02c_chain_rules |
| MVNCD | t03a_mvncd_methods, t03b_mvncd_gradients, t03c_mvncd_rect, t03d_univariate_cdfs, t03e_bhat2018_table1 |
| MNP | t04a_mnp_iid … t04g_mnp_forecasting, t04h_bhatlib_table1, t04i_bhat2018_table2 |
| MORP | t05b_morp_ate_predict |
| MDCEV | t07a_mdcev_trad, t07b_mdcev_lin |
| MNL | t08a_mnl |
| LR | t09a_lr |
| Backends & verification | t06a_backend_switching, t06b_custom_specs, t06c_gradient_verification |
See CONTRIBUTING.md for development setup, the PR-test
workflow, and CODEOWNERS conventions. Key tests:
pytest tests/ # full suite
pytest tests/ -m "not slow" # skip integration tests
pytest tests/ -m torch # PyTorch backend tests only- Bhat, C. R. (2018). New Matrix-Based Methods for the Analytic Evaluation of the Multivariate Cumulative Normal Distribution Function. Transportation Research Part B, 109: 238–256.
- Bhat, C. R. (2008). The Multiple Discrete-Continuous Extreme Value (MDCEV) Model: Role of Utility Function Parameters, Identification Considerations, and Model Extensions. Transportation Research Part B, 42(3): 274–303.
MIT