mnlite
Lightweight discrete choice modelling for travel mode choice, in numpy.
mnlite estimates multinomial logit (MNL) and one-level nested logit (NL) models
by maximum likelihood and gives you what a mode choice study needs afterwards:
standard errors (classical and robust), rho-squared, likelihood ratio tests,
elasticities, the value of travel time with a delta-method standard error, and
market-share scenarios. It depends on numpy only; scipy and pandas are optional.
It is meant for teaching, quick studies and pipelines where a full econometrics package is too heavy. For mixed logit, latent classes, panel data or large production models use a fuller package: Biogeme, PyLogit, xlogit (GPU mixed logit) or Apollo in R.
pip install mnlite # numpy only
pip install "mnlite[pandas]" # + DataFrame export
pip install "mnlite[scipy]" # + scipy optimiser backend
Requires Python 3.9 or newer.
Quickstart
import mnlite
from mnlite import Spec, estimate
# Ben-Akiva & Lerman (1985, p. 88): 21 travellers, car vs transit.
data = mnlite.ben_akiva_lerman()
res = estimate({"car": "b_time*time", "transit": "asc_transit + b_time*time"}, data)
print(res.summary())
# asc_transit 0.2376 (s.e. 0.7505), b_time -0.0531 (s.e. 0.0206),
# LL -6.166, rho2 0.576, adjusted rho2 0.439 -> identical to the published values
# Three modes, availability, generic and alternative-specific coefficients.
modes = mnlite.synthetic_mode_choice(n=3000) # known true parameters
spec = Spec({
"car": "b_time*time + b_cost*cost + b_inc_car*income",
"bus": "asc_bus + b_time*time + b_cost*cost",
"rail": "asc_rail + b_time*time + b_cost*cost",
})
mnl = estimate(spec, modes)
print(mnl.vtt("b_time", "b_cost", scale=60)) # currency per hour, delta-method s.e.
print(mnl.elasticities(modes, "cost", "car")) # direct (car) and cross elasticities
print(mnl.simulate(modes, {"cost_bus": "*1.2", "time_rail": "-5"}).table())
# Nested logit: bus and rail in a public transport nest (FIML).
nl = estimate(Spec(spec.utilities, nests={"pt": ["bus", "rail"]}), modes)
print(mnlite.lr_test(mnl, nl))
print(mnlite.compare([mnl, nl], ["MNL", "NL"]))
See examples/quickstart.py for a complete script.
Data
ChoiceData holds one row per choice observation (wide form). Alternative-specific
attributes are columns named {var}_{alt} (time_car, time_bus); other columns
(income) are individual-specific. The utility term b_time*time for alternative
bus uses column time_bus if it exists, otherwise time.
d = mnlite.read_csv("trips.csv", alternatives=["car", "bus", "rail"],
choice="mode", avail="{alt}_av", weights="w") # wide
d = mnlite.read_csv("trips_long.csv", form="long", id_col="id", alt_col="alt",
choice_col="chosen", avail_col="av") # long
d = mnlite.ChoiceData.from_wide(df, ["car", "bus", "rail"]) # pandas
d.to_long(); d.to_wide(); d.write_csv("out.csv", "long"); d.to_pandas()
In long form, missing rows mean "unavailable"; a variable that is constant across an observation's alternatives is also kept as an individual-specific column.
Specification mini-language
| Written | Meaning |
|---|---|
asc_bus |
alternative-specific constant |
b_time*time |
parameter times variable; the first name is always the parameter |
b_inc_rail*income |
individual-specific variable (needs an alternative-specific parameter) |
b*time*income |
interaction (product of variables) |
b_cost*cost*0.01 |
numeric scaling |
- b*x |
negative sign |
0 or "" |
utility fixed at zero (reference alternative) |
A parameter name used in several utilities is generic; used once it is
alternative-specific. Spec(..., fixed={"asc_rail": 0}) holds a parameter fixed;
nests={"pt": ["bus", "rail"]} adds the nest parameter lambda_pt.
Spec.to_dict() / Spec.from_dict() round-trip through JSON.
API overview
| Object | Purpose |
|---|---|
Spec(utilities, nests=None, fixed=None, column_pattern="{var}_{alt}") |
model specification |
ChoiceData(columns, alternatives, choice, avail=None, weights=None) |
data; .from_wide, .from_long, .to_long, .to_wide, .write_csv, .to_pandas |
read_csv(path, form="wide" or "long", **kw) |
CSV reader (stdlib csv) |
estimate(spec, data, start=None, method="auto") |
MLE; returns EstimationResults |
res.params, .std_errors(robust=), .tstats(), .pvalues(), .conf_int() |
inference |
res.loglik, .loglik_null, .loglik_constants, .rho2, .rho2_bar, .aic, .bic |
fit |
res.lr_test_null(), lr_test(restricted, unrestricted), res.wald_test(name, value) |
tests |
res.ratio(num, den, scale), res.vtt(time, cost, scale=60) |
ratios, VTT with delta-method s.e. |
res.elasticities(data, var, alt, aggregate=True) |
direct / cross point elasticities |
res.predict(data), .market_shares(data), .simulate(data, changes, avail) |
prediction and scenarios |
res.summary(), .to_dict(), .to_json(), compare([...]) |
reporting |
ben_akiva_lerman(), synthetic_mode_choice(n, seed, nested) |
validation data |
Command line
mnlite example # reproduces Ben-Akiva & Lerman (1985)
mnlite synth trips.csv --n 2000 [--nested] [--long]
mnlite estimate trips.csv --avail "{alt}_av" \
-u "car=b_time*time + b_cost*cost + b_inc_car*income" \
-u "bus=asc_bus + b_time*time + b_cost*cost" \
-u "rail=asc_rail + b_time*time + b_cost*cost" \
--nest pt:bus,rail --ratio "b_time/b_cost*60" \
--elasticity cost:car --scenario "cost_bus*1.2" --json results.json
mnlite estimate trips.csv --spec spec.json # {"utilities": {...}, "nests": {...}, "fixed": {...}}
mnlite convert trips_long.csv trips_wide.csv --long --avail avail --to wide
Scenario changes: COL*1.2, COL+5, COL-5, COL/2, COL=0.
Method and sources
- MNL.
P_ni = a_ni exp(V_ni) / sum_j a_nj exp(V_nj)with availabilitya_nj(McFadden 1974; Train 2009, ch. 3). The weighted log-likelihoodsum_n w_n ln P_n,i(n)is globally concave; its scorex_ni - sum_j P_nj x_njand Hessian-sum_n w_n sum_j P_nj (x_nj - x̄_n)(x_nj - x̄_n)'are analytic (Train 2009, sec. 3.7). Newton-Raphson with step halving, stopping on the scaled gradientg' H^-1 g(Train 2009, sec. 8.3-8.4); BFGS (Nocedal & Wright 2006) when the Hessian is not negative definite;method="scipy"usesscipy.optimize.minimize(method="BFGS"). - Nested logit, one level, normalised at the top (the random-utility-consistent form
of Koppelman & Bhat 2006 and Train 2009, sec. 4.2):
P_ni = exp(V_ni/λ_m) / exp(I_m) · exp(λ_m I_m) / sum_l exp(λ_l I_l),I_m = ln sum_{j in m} a_nj exp(V_nj/λ_m). Estimation is FIML (all parameters jointly, started from the MNL estimates), not the sequential two-step method. The gradient is analytic; the Hessian for standard errors is a central difference of the analytic gradient.0 < λ ≤ 1is required for consistency with utility maximisation (McFadden 1978); the summary flags estimates outside that range and reports a t-test against 1. Single-alternative nests have λ fixed at 1. - Inference. Covariance
(-H)^-1; robust sandwichH^-1 (sum w_n² s_n s_n') H^-1(White 1982). With non-unit weights (e.g. WESML for choice-based samples, Manski & Lerman 1977) use the robust standard errors. p-values use the normal approximation. - Fit.
rho2 = 1 - LL(β)/LL(0),rho2_bar = 1 - (LL(β) - K)/LL(0)(Ben-Akiva & Lerman 1985, sec. 7.4);LL(0)gives equal probability to the available alternatives;LL(C)is from a constants-only MNL.AIC = 2K - 2LL(Akaike 1974),BIC = K ln N - 2LL(Schwarz 1978). LR test-2(LL_r - LL_u) ~ χ²(K_u - K_r); the χ² tail uses the regularised incomplete gamma function (Press et al. 2007, sec. 6.2), so scipy is not needed. - Elasticities. Point elasticities of
P_njwith respect to a data column, by central difference of the model probabilities; this equalsβ x_ni (1 - P_ni)(direct) and-β x_ni P_ni(cross) for MNL and the nested-logit expressions with the(1/λ - 1)terms, both checked in the tests. Aggregate elasticities are probability-weighted,Σ w_n P_nj E_nj / Σ w_n P_nj: the elasticity of the predicted share (Ben-Akiva & Lerman 1985, sec. 5.5). - Value of travel time
scale · β_time / β_cost, with the delta-method variance∇g' Σ ∇g,∇g = scale · (1/β_c, -β_t/β_c²)(e.g. Daly, Hess & de Jong 2012, who also discuss the alternatives to the delta method). - Scenarios use sample enumeration: probabilities recomputed for every observation with the changed attributes or availability, then averaged with the weights.
Validation
ben_akiva_lerman()is the 21-person car/transit example of Ben-Akiva & Lerman (1985, p. 88), as reproduced in the EPFL Transport and Mobility Laboratory course slides (binary choice lecture). mnlite reproduces the published constant 0.2376 (s.e. 0.7505), time coefficient -0.0531 (s.e. 0.0206), LL(β) = -6.166, LL(0) = -14.556, ρ² = 0.576 and adjusted ρ² = 0.439 (tests/test_mnl.py).synthetic_mode_choice()simulates car/bus/rail choices (with rail availability) from known parameters, by MNL or nested logit; the tests check that the estimates recover them within their standard errors, that the analytic gradients match finite differences, that NL with λ = 1 equals MNL, and that the scipy backend agrees.
References
- Akaike, H. (1974). A new look at the statistical model identification. IEEE Transactions on Automatic Control, 19(6), 716-723.
- Ben-Akiva, M., & Lerman, S. R. (1985). Discrete Choice Analysis: Theory and Application to Travel Demand. MIT Press.
- Daly, A., Hess, S., & de Jong, G. (2012). Calculating errors for measures derived from choice modelling estimates. Transportation Research Part B, 46(2), 333-341.
- Koppelman, F. S., & Bhat, C. (2006). A Self Instructing Course in Mode Choice Modeling: Multinomial and Nested Logit Models. US DOT, Federal Transit Administration.
- Manski, C. F., & Lerman, S. R. (1977). The estimation of choice probabilities from choice based samples. Econometrica, 45(8), 1977-1988.
- McFadden, D. (1974). Conditional logit analysis of qualitative choice behavior. In P. Zarembka (Ed.), Frontiers in Econometrics. Academic Press.
- McFadden, D. (1978). Modelling the choice of residential location. In A. Karlqvist et al. (Eds.), Spatial Interaction Theory and Planning Models. North-Holland.
- Nocedal, J., & Wright, S. J. (2006). Numerical Optimization (2nd ed.). Springer.
- Press, W. H., Teukolsky, S. A., Vetterling, W. T., & Flannery, B. P. (2007). Numerical Recipes (3rd ed.). Cambridge University Press.
- Schwarz, G. (1978). Estimating the dimension of a model. Annals of Statistics, 6(2), 461-464.
- Train, K. E. (2009). Discrete Choice Methods with Simulation (2nd ed.). Cambridge University Press.
- White, H. (1982). Maximum likelihood estimation of misspecified models. Econometrica, 50(1), 1-25.
Limitations
- Utilities must be linear in parameters (transform variables beforehand, e.g. log cost).
- One nesting level only; no cross-nesting, mixed logit, latent class or panel (repeated choice) correlation. Use Biogeme, PyLogit, xlogit or Apollo for those.
- The nested logit Hessian is numerical (finite differences of the analytic gradient), so its standard errors are accurate to a few significant digits rather than to machine precision.
- Elasticities are with respect to a data column: if the same column enters several
utilities (for example
income), all of them change together. - The ratio/VTT confidence interval is the symmetric delta-method interval; for ratios with an imprecise denominator a simulation or Fieller interval may be more suitable (Daly, Hess & de Jong 2012).
- Designed for datasets that fit in memory as an
(observations × alternatives × parameters)array; tens of thousands of observations are fine.
Academic citation
@software{eminoglu_mnlite,
author = {Eminoğlu, Yusuf},
title = {mnlite},
year = {2026},
version = {0.1.2},
doi = {10.5281/zenodo.24235586},
url = {https://gitlab.com/geophilo1/mnlite_sdk}
}
Related Geophilo SDKs
- tripdist: trip generation and distribution for the four-step model, with gravity models and Furness balancing.
- routematrix: travel-time and distance matrices from OSRM, Valhalla, GraphHopper and openrouteservice.
- transitfreq: transit service frequency, headways and span of service from GTFS feeds.
- odflows: origin-destination flow tables, desire lines and functional regions.
License
MIT License, Copyright (c) 2026 Yusuf Eminoğlu. See LICENSE.
Metadata
Release files for mnlite 0.1.2
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 |
|---|---|---|---|---|
| mnlite-0.1.2.tar.gz | 55.7 kB | Without provenance | Details for mnlite-0.1.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| mnlite-0.1.2-py3-none-any.whl | Python 3 | none | any | Details for mnlite-0.1.2-py3-none-any.whl |
Total release size: 96.2 kB
Release files / mnlite-0.1.2.tar.gz
| Download URL | mnlite-0.1.2.tar.gz |
|---|---|
| Size | 55.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
fd5716c128a962049ce8466ad6533b20a5ee0b39fa30120b6543234aa533cf76
|
|
BLAKE2b-256 checksum How to use checksums |
3cb0698ff68c94ea10593ae57040fb71d690ab821294edc115274ed771a0af31
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
Release files / mnlite-0.1.2-py3-none-any.whl
| Download URL | mnlite-0.1.2-py3-none-any.whl |
|---|---|
| Size | 40.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f79a1b65bf2e6077a7682354577e3e66c4c11ba67a3cfd7ca15ef2abb2ca46cc
|
|
BLAKE2b-256 checksum How to use checksums |
0b781f9b2348210649bd6bed92621b42e5fb14028eda55ca98aa24ed2686dfa7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
Security for mnlite 0.1.2
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.