Metadata-Version: 2.4
Name: tripdist
Version: 0.1.1
Summary: Trip generation and distribution for the four-step model: regression and cross-classification, P/A balancing, growth-factor methods, gravity models with Furness balancing, Hyman calibration and trip length frequency diagnostics.
Author-email: Yusuf Eminoğlu <geospacephilo@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://gitlab.com/geophilo1/tripdist_sdk
Project-URL: Repository, https://gitlab.com/geophilo1/tripdist_sdk
Project-URL: Issues, https://gitlab.com/geophilo1/tripdist_sdk/-/work_items
Project-URL: Changelog, https://gitlab.com/geophilo1/tripdist_sdk/-/blob/main/CHANGELOG.md
Keywords: transport-planning,travel-demand,four-step-model,trip-generation,trip-distribution,gravity-model,furness,fratar,ipf,hyman,origin-destination,od-matrix,urban-planning
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: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
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

# tripdist

[![PyPI](https://img.shields.io/pypi/v/tripdist.svg)](https://pypi.org/project/tripdist/)
[![Python](https://img.shields.io/pypi/pyversions/tripdist.svg)](https://pypi.org/project/tripdist/)
[![pipeline](https://gitlab.com/geophilo1/tripdist_sdk/badges/main/pipeline.svg)](https://gitlab.com/geophilo1/tripdist_sdk/-/pipelines)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://gitlab.com/geophilo1/tripdist_sdk/-/blob/main/LICENSE)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24235564.svg)](https://doi.org/10.5281/zenodo.24235564)

**Trip generation and distribution (stages 1 and 2 of the four-step model) in plain NumPy.**

`tripdist` covers the first two stages of the classic four-step travel demand model as
set out in Ortúzar & Willumsen, *Modelling Transport*:

- **Trip generation**: zonal or household linear regression with standard errors, t
  statistics and R²; cross-classification (category analysis) trip rates; balancing of
  productions and attractions.
- **Growth-factor methods**: uniform, singly constrained, average factor, Detroit, Fratar
  and Furness.
- **Gravity models**: unconstrained, production-constrained, attraction-constrained and
  doubly constrained (Furness / IPF balancing), with exponential, power, combined (Tanner),
  gamma and tabulated deterrence functions, K-factors and intrazonal handling.
- **Calibration**: Hyman's (1969) method for a deterrence parameter against an observed
  mean trip cost, iterative fitting of stepwise friction factors to an observed trip
  length frequency distribution, ratio K-factors at zone or district level.
- **Diagnostics**: Furness convergence history, trip length frequency distributions and
  the coincidence ratio, RMSE / %RMSE / R² / GEH matrix comparison, district aggregation.

It needs only NumPy. A command-line tool reads CSV matrices and zone tables and writes JSON
and CSV.

## Installation

```bash
pip install tripdist
```

Requires Python 3.9 or newer.

## Quickstart

```python
import numpy as np
import tripdist as td

cost = np.array([[3, 11, 18, 22],
                 [12, 3, 13, 19],
                 [15.5, 13, 5, 7],
                 [24, 18, 8, 5]], dtype=float)          # minutes
productions = np.array([98, 106, 122, 174], dtype=float)
attractions = np.array([102, 118, 141, 139], dtype=float)

# doubly constrained gravity model with an exponential deterrence function
res = td.gravity(cost, productions, attractions, td.exponential(0.1))
res.matrix, res.iterations, res.converged, res.mean_cost
res.history                      # largest relative margin error per Furness pass

# calibrate beta so the model reproduces an observed mean trip cost (Hyman 1969)
cal = td.hyman(cost, productions, attractions, target_mean_cost=10.0)
cal.value, cal.modelled_mean_cost, cal.trace

# compare trip length distributions with an observed matrix
edges = td.cost_bins(cost, 5.0)
cmp = td.compare_tlfd(cal.model.matrix, observed_matrix, cost, edges)
cmp.coincidence_ratio
```

Trip generation and growth factors:

```python
m = td.fit_regression(trips, np.column_stack([households, cars]), ["households", "cars"])
m.coefficients, m.t_stats, m.r_squared
rates = td.cross_classification_rates(hh_trips, list(zip(car_ownership, hh_size)))
p = td.apply_category_rates(households_by_category, rates, category_keys)
p, a = td.balance_pa(p, a, method="productions")

td.furness_growth(base, origin_totals=o_future, dest_totals=d_future)
td.fratar(base, origin_factors=tau, dest_factors=tau)
td.growth_factor(base, "detroit", origin_totals=o_future, dest_totals=d_future)
```

Other deterrence functions and options:

```python
td.power(2.0)                         # c^-n
td.combined(-0.5, 0.05)               # Tanner: c^n exp(-beta c)
td.gamma(a=1.0, b=0.5, g=0.05)        # a c^-b exp(-g c); parameters are yours
td.tabular([0, 5, 10, 20], [1.0, 0.6, 0.2])
td.gravity(cost, p, a, {"form": "exponential", "beta": 0.08},
           constraint="production", k_factors=k, intrazonal="exclude")
td.intrazonal_costs(cost, factor=0.5, neighbours=1)   # factor is a modelling choice
```

## Command line

```bash
tripdist balance --zones zones.csv --method productions --csv balanced.csv
tripdist growth base.csv --method furness --targets targets.csv --matrix-out future.csv
tripdist gravity cost.csv --zones zones.csv --form exponential --beta 0.1 \
    --observed observed.csv --bin-width 5 --matrix-out modelled.csv -o report.json
tripdist calibrate cost.csv --zones zones.csv --observed observed.csv
tripdist calibrate cost.csv --zones zones.csv --target-mean 14 --form power --n 1 \
    --parameter n --start 1 --zero-cost-value 1
tripdist tlfd modelled.csv cost.csv --edges 0,5,10,20,40 --observed observed.csv --csv tlfd.csv
```

Matrices are CSV grids, either plain or with a header row and a first column of zone
labels (give the top-left cell a name such as `zone`); empty cells are 0 and `inf` marks
impossible movements. Zone tables are CSV files with a header (`zone,productions,
attractions` by default; growth targets use `origins,destinations`). Deterrence functions
come from `--form` with its parameters or from a JSON file such as
`{"form": "gamma", "a": 1, "b": 0.5, "g": 0.05}`. Every command prints JSON or writes it
with `-o`.

## API overview

| Area | Functions / classes |
| --- | --- |
| Generation | `fit_regression -> RegressionModel`, `cross_classification_rates -> CategoryRates`, `apply_category_rates`, `balance_pa` |
| Balancing | `furness -> BalanceResult`, `margin_error` |
| Growth factors | `uniform_growth`, `singly_constrained_growth`, `average_factor`, `detroit`, `fratar`, `furness_growth`, `growth_factor -> GrowthResult` |
| Deterrence | `exponential`, `power`, `combined` / `tanner`, `gamma`, `tabular`, `deterrence_from_dict -> Deterrence` |
| Gravity | `gravity -> GravityResult`, `mean_cost`, `intrazonal_costs`, `intrazonal_share` |
| Calibration | `hyman -> CalibrationResult`, `observed_mean_cost`, `calibrate_friction_factors -> FrictionCalibration`, `k_factors` |
| TLFD | `tlfd -> TLFD`, `compare_tlfd -> TLFDComparison`, `coincidence_ratio`, `cost_bins` |
| Diagnostics | `summarize`, `compare_matrices -> MatrixFit`, `geh`, `aggregate` |
| I/O | `read_matrix`, `write_matrix`, `read_zone_table`, `read_long`, `read_json`, `write_json` |

All result objects have `to_dict()` returning JSON-safe values (NaN and infinity become
`null`).

## Methods and sources

| Method | Definition | Source |
| --- | --- | --- |
| Regression trip generation | OLS `y = b0 + sum b_k x_k`, with SE, t, R², adjusted R² | Ortúzar & Willumsen (2011), ch. 4 |
| Cross-classification | mean trips per household by category; `P_i = sum_c H_ic t_c` | Wootton & Pick (1967) |
| P/A balancing | scale attractions to productions (or the reverse, or the mean); optional fixed zones | Ortúzar & Willumsen (2011), ch. 4 |
| Uniform, singly constrained | `T = tau t`; `T_ij = tau_i t_ij` | Ortúzar & Willumsen (2011), §5.2 |
| Average factor | `T_ij = t_ij (tau_i + tau_j) / 2`, iterated | Ortúzar & Willumsen (2011), §5.2 |
| Detroit | `T_ij = t_ij tau_i tau_j / tau`, iterated | Detroit Metropolitan Area Traffic Study (1956), via Ortúzar & Willumsen |
| Fratar | `T_ij = t_ij tau_i tau_j (L_i + L_j) / 2`, `L_i = sum_j t_ij / sum_j t_ij tau_j`, iterated | Fratar (1954) |
| Furness / IPF | `T_ij = A_i B_j t_ij`, alternate row and column scaling | Furness (1965); Deming & Stephan (1940); Bacharach (1970) |
| Gravity model | `T_ij = A_i O_i B_j D_j f(c_ij)` and its singly / unconstrained forms | Wilson (1970); Ortúzar & Willumsen (2011), §5.3 |
| Deterrence | `exp(-beta c)`, `c^-n`, `c^n exp(-beta c)` | Ortúzar & Willumsen (2011), ch. 5; Tanner (1961) |
| Gamma deterrence | `a c^-b exp(-g c)`, i.e. NCHRP 716's `a t^b exp(c t)` with `b = -b_716`, `g = -c_716` (form only; no parameter tables included) | NCHRP Report 716 (2012) |
| Hyman calibration | `beta_0 = 1/c*`, `beta_1 = beta_0 c_0 / c*`, then secant updates on the mean cost | Hyman (1969); Ortúzar & Willumsen (2011), §5.5 |
| Friction-factor fitting | `F_k <- F_k p_k(obs) / p_k(mod)` per cost band | FHWA (1965) |
| K-factors | ratio `observed / modelled`, by zone or district pair | FHWA (1965) (simple ratio form) |
| Coincidence ratio | `sum min(p_k, q_k) / sum max(p_k, q_k)` | FHWA Travel Model Validation Manual (2010) |
| GEH | `sqrt(2 (M - O)^2 / (M + O))` | UK DfT TAG unit M3.1 |

Notes:

- The Furness iteration stops when the largest relative margin error falls below `tol`
  (default `1e-6`). Unequal target totals raise an error unless `total_mismatch` says how
  to reconcile them. Seed rows or columns that are all zero but have positive targets
  raise an error; other infeasible zero patterns are reported as `converged=False`.
- Infinite costs give `f = 0`. Power-type deterrence at `c = 0` raises an error unless
  intrazonal costs are set or `zero_cost_value` is given.
- In Hyman's method the start value `1 / c*` applies to the exponential `beta`; for other
  forms give `start`. If a secant step would make a positive parameter non-positive, the
  step is halved towards zero instead.
- `intrazonal_costs` replaces the diagonal by a fraction of the cost to the nearest
  zone(s); the fraction is yours to choose.

## Limitations

- No default parameter values: published parameter sets (for example the NCHRP 716 gamma
  tables) are not bundled; calibrate or supply your own.
- No acceptance thresholds for coincidence ratios, %RMSE or GEH are built in; they differ
  between guidance documents.
- Dense matrices only; large zone systems (tens of thousands of zones) need care with
  memory.
- No mode choice or assignment: this package covers stages 1 and 2 only.

## References

- Bacharach, M. (1970). *Biproportional Matrices and Input-Output Change*. Cambridge
  University Press.
- Cambridge Systematics (2010). *Travel Model Validation and Reasonableness Checking
  Manual*, 2nd ed. Federal Highway Administration, Washington, DC.
- Cambridge Systematics et al. (2012). *NCHRP Report 716: Travel Demand Forecasting:
  Parameters and Techniques*. Transportation Research Board, Washington, DC.
- Deming, W. E. & Stephan, F. F. (1940). On a least squares adjustment of a sampled
  frequency table when the expected marginal totals are known. *Annals of Mathematical
  Statistics* 11(4), 427-444.
- Federal Highway Administration (1965). *Calibrating and Testing a Gravity Model for Any
  Size Urban Area*. US Department of Commerce, Bureau of Public Roads.
- Fratar, T. J. (1954). Vehicular trip distribution by successive approximations.
  *Traffic Quarterly* 8(1), 53-65.
- Furness, K. P. (1965). Time function iteration. *Traffic Engineering and Control* 7(7),
  458-460.
- Hyman, G. M. (1969). The calibration of trip distribution models. *Environment and
  Planning* 1(1), 105-112.
- Ortúzar, J. de D. & Willumsen, L. G. (2011). *Modelling Transport*, 4th ed. Wiley,
  Chichester.
- Tanner, J. C. (1961). *Factors affecting the amount of travel*. Road Research Technical
  Paper 51, HMSO, London.
- Wilson, A. G. (1970). *Entropy in Urban and Regional Modelling*. Pion, London.
- Wootton, H. J. & Pick, G. W. (1967). A model for trips generated by households.
  *Journal of Transport Economics and Policy* 1(2), 137-153.

## Academic citation

```bibtex
@software{eminoglu_tripdist,
  author  = {Eminoğlu, Yusuf},
  title   = {tripdist},
  year    = {2026},
  version = {0.1.1},
  doi     = {10.5281/zenodo.24235564},
  url     = {https://gitlab.com/geophilo1/tripdist_sdk}
}
```

## License

MIT, see [LICENSE](LICENSE).
