Metadata-Version: 2.4
Name: mnlite
Version: 0.1.0
Summary: Lightweight discrete choice modelling for travel mode choice in numpy: multinomial and nested logit by maximum likelihood, robust standard errors, rho-squared, LR tests, elasticities, value of travel time and scenario simulation.
Author-email: Yusuf Eminoğlu <geospacephilo@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://gitlab.com/geophilo1/mnlite_sdk
Project-URL: Repository, https://gitlab.com/geophilo1/mnlite_sdk
Project-URL: Issues, https://gitlab.com/geophilo1/mnlite_sdk/-/work_items
Project-URL: Changelog, https://gitlab.com/geophilo1/mnlite_sdk/-/blob/main/CHANGELOG.md
Keywords: discrete-choice,multinomial-logit,nested-logit,mode-choice,travel-demand,transport-planning,maximum-likelihood,elasticity,value-of-time,econometrics
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Environment :: Console
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Education
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
Provides-Extra: pandas
Requires-Dist: pandas>=1.3.0; extra == "pandas"
Provides-Extra: scipy
Requires-Dist: scipy>=1.7; extra == "scipy"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

# mnlite

[![PyPI version](https://img.shields.io/pypi/v/mnlite.svg)](https://pypi.org/project/mnlite/)
[![Python versions](https://img.shields.io/pypi/pyversions/mnlite.svg)](https://pypi.org/project/mnlite/)
[![pipeline](https://gitlab.com/geophilo1/mnlite_sdk/badges/main/pipeline.svg)](https://gitlab.com/geophilo1/mnlite_sdk/-/pipelines)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://gitlab.com/geophilo1/mnlite_sdk/-/blob/main/LICENSE)

**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](https://biogeme.epfl.ch/),
[PyLogit](https://github.com/timothyb0912/pylogit),
[xlogit](https://github.com/arteagac/xlogit) (GPU mixed logit) or
[Apollo](http://www.apollochoicemodelling.com/) in R.

```bash
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

```python
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`.

```python
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

```bash
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 availability `a_nj`
  (McFadden 1974; Train 2009, ch. 3). The weighted log-likelihood
  `sum_n w_n ln P_n,i(n)` is globally concave; its score
  `x_ni - sum_j P_nj x_nj` and 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 gradient `g' H^-1 g` (Train 2009, sec. 8.3-8.4); BFGS (Nocedal & Wright 2006)
  when the Hessian is not negative definite; `method="scipy"` uses
  `scipy.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 < λ ≤ 1` is 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 sandwich `H^-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_nj` with 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

```bibtex
@software{eminoglu_mnlite,
  author  = {Eminoğlu, Yusuf},
  title   = {mnlite},
  year    = {2026},
  version = {0.1.0},
  url     = {https://gitlab.com/geophilo1/mnlite_sdk}
}
```

## License

MIT License, Copyright (c) 2026 Yusuf Eminoğlu. See [LICENSE](LICENSE).
