Skip to content

Repository files navigation

TrafMod — Traffic Dynamics Lab

Checks License: MIT

Simulate interacting cars, preserve reproducible runs, and test differential equations against observations.

TrafMod models a straight, single-lane road with force/power-limited vehicles, stochastic arrivals, safe following, queues and destination stops. It compares empirical and source-informed candidate equations without assuming a power law.

Use the lab

Use Node.js 24 and a modern browser:

git clone https://github.com/ChristopherJohannesKoen/TrafMod.git
cd TrafMod
npm ci
npm run dev

Open http://127.0.0.1:4173. Stop with Ctrl+C. Local runs persist in an ignored SQLite database and observation files under .sites-runtime/local-data/. Local development requires no account or API key.

The deployed Site uses authenticated, owner-scoped D1 metadata and R2 observation bundles. Completed runs save automatically and remain available across devices. Local development storage and deployed storage are separate.

Features

  • Editable road geometry, spawn rate (cars/second), regular or Poisson arrivals, seed, duration, vehicle mass, power, traction, braking, initial speed, resistance, following distance, headway and dwell.
  • A unique ID for every run; immutable saved observations; JSON import/export; reopening and replaying saved configurations.
  • All admitted vehicles recorded at a chosen interval (0.2 seconds by default); spatial counts, mean speed, variance and destination occupancy.
  • Fit acceleration, road count, upstream queue or mean speed derivatives.
  • Custom candidate terms with a safe mathematical expression parser, up to 24 terms, optional ridge regularization, and adjustable observation limits.
  • Polynomial, inverse-speed, state-dependent and parameter-dependent candidates. Source-informed features are labelled assisted identification.
  • Separate training, validation and final holdout sets in the interactive fitter. Repeated interactive model choices remain exploratory.
  • Saved browser campaigns with 1,000–10,000 runs per configuration. Keep the page open; pause/resume within the session. Completed records remain saved even if the page closes.
  • A reproducible offline research campaign with frozen code, data splits, per-run checksums and extensive ODE/PDE analysis.

First experiment

  1. Adjust the setup and choose Apply & reset run.
  2. Run, pause or step the simulation. Playback speed does not change the physical time step.
  3. Choose Finish run & fit ODEs. The completed observations save automatically.
  4. Open ODE discovery → Customize equation generation to add terms such as 1, v, v^2, r/L, lambda, rho, or parameter-dependent expressions.
  5. Use Saved runs to reload, download, replay or select up to 12 runs for comparison.
  6. Use Experiments for large saved campaigns or a small distance preview.

The per-run website upload/import limit is 8 MB of JSON. Choose a larger recording interval for long, busy runs; this changes observation resolution without changing the motion. Larger datasets can be exported and analyzed with the offline tools. Saving errors preserve the current page's observations and offer a retry. Research archives explicitly document their observation subsampling.

What the equations mean

The exact implemented system is a stochastic hybrid difference model: continuous vehicle state is updated on a time grid, while arrivals, admission, stops and departures are events. A piecewise ODE describes its formal continuous-time counterpart; global convergence to it has not been proved.

A scalar equation in car count alone cannot exactly determine future departures: position, velocity, following state and destination dwell memory matter. Continuum conservation equations are available, but a predictive PDE also needs a validated relation between density, flux and other state.

Read Model and methods, Research protocol, and the research report in the lab. The preset is a representative example, not a measured fleet average. This is an experimental simulator, not a calibrated real-traffic forecasting tool.

Rate-driven aggregate study

The current study replaces origin probability with requested rate λ in cars/second, using regular or Poisson arrival clocks. Requests can exceed one per second and wait outside the road when admission is blocked. Old saved Bernoulli runs retain their original meaning.

40,000 reference simulations cover 40 configurations with 1,000 scenarios each. Five frozen models produce 98,000 conditional forecasts across validation and final tests; 30,000 labelled ensemble scenarios test predictions from arrival rates, with 1,000 per condition and paired physical/profile inputs across arrival modes. Scenarios vary geometry, propulsion, braking, headway, dwell, starting speed, arrival profiles and phase. The study preserves failed cases and separates wholly new configurations from new scenarios in existing configurations.

The validation-selected memory-passage passes all applicable output gates in 21/30 final conditions. It does not meet the all-condition requirement. It is a reduced travel/service-memory model. The scalar and vector PDE alternatives, complete gates, numerical sensitivity and rate-only ensemble results remain published.

In the noninteracting limit, the derivation closes as an age-transport PDE or the delay relation N′(t)=λ(t)−λ(t−τ_total); steady density is ρ̄=λτ_total/L. Congestion needs admission, velocity and service memory. Identical density with different speeds or dwell ages has different next outcomes, excluding a universal exact instantaneous density-only law over arbitrary admissible simulator states. A rate alone also does not specify one stochastic arrival realization.

Open Autonomous forecasts for packet or continuous-rate comparisons and editable coefficients. See the rate-study report, derivation, reproduction guide, frozen coefficients, and complete rate-study data.

Earlier autonomous aggregate study

The previous study contains 25,000 reference simulations (25 conditions ×1,000 runs), paired autonomous forecasts, and 18,000 independent demand-ensemble forecasts. The frozen travel/service-memory model passes all six output gates in 17/18 final conditions, versus 12/18 for the density-only baseline. This comprises 12/12 new-seed development conditions and 5/6 wholly unseen parameter configurations for the memory model. It is a closed hybrid model with transport memory, not a universal scalar density PDE. The failed long-road speed/spatial case remains published.

Open Autonomous forecasts in the lab to compare models, edit physics and coefficients, and save complete comparisons across devices. The forecast runs before the reference and receives no measured traffic states. Saved forecast IDs preserve settings, forcing, model versions, coefficients, both histories and scores.

Read the final report, complete derivation, reproduction guide, and complete data release. The earlier 35,000-run identification study below remains separate.

Earlier identification campaign

35,000 runs, 1,000 per condition, have been completed and checked. Source-informed acceleration and following expressions have final derivative RMSEs of 0.00238 and 0.00906 m/s². The selected road-count closure fails all four unseen combined-parameter configurations; the density-only flux closure also fails overall transfer. Numerical trip outputs remain sensitive to the physics step.

Read the full research report, governing formulation, and download all 35,000 compact records. The website's Research tab exposes every run ID, seed and summary. Derivative agreement is not a validation of autonomous coupled traffic forecasts.

Reproduce the earlier identification study

node research/run-campaign.mjs
node research/analyze.mjs train
node research/analyze.mjs select
node research/analyze.mjs test
node research/diagnostics.mjs
node research/reindex.mjs
node research/make-report.mjs
python research/figures.py

The protocol defines 32 physical configurations and three paired numerical-resolution configurations, each with 1,000 runs. Each run lasts 600 simulated seconds. Development configurations allocate 600/200/200 independent seeds to training/validation/final testing; additional whole configurations test parameter transfer.

Source snapshots preserve the controller, observation policy and candidate library used for the published campaign. Detailed compressed records live under ignored research-data/; public reports and frozen source live under research/. The final-test script refuses to overwrite an existing final evaluation. Start a new campaign for new hypotheses rather than tuning against the old final test.

The commands show the pipeline stages. This checkout includes frozen results, so the final-test refusal is expected unless reproducing in a separate output workspace. Python figures require Matplotlib and NumPy. To replay a dense trajectory without changing the published records, run node research/replay.mjs road-500-demand-35 1. Condition names and repetitions (1–1,000) are shown in the catalog. Archives contain .json.gz records; provenance.tar includes the per-record SHA-256 index and source snapshot, and SHA256SUMS.txt checks the release archives.

Full dense all-vehicle trajectories are reproducible from settings and seeds. Research records retain complete one-second aggregates/spatial bins, full first-vehicle trajectories and seeded per-regime observation-window reservoirs. They do not claim to retain every dense trajectory sample.

Architecture

Path Purpose
dist/engine.mjs, dist/arrivals.mjs Versioned motion controller, independent arrival clocks and observations
dist/rate-model.mjs, dist/aggregate-model.mjs Autonomous scalar/vector transport and travel/service-memory candidates
dist/discovery.mjs Safe expression parsing, regression and validation
dist/fitting.mjs Legacy comparison helpers and equation formatting
dist/app-main.mjs, dist/research-ui.mjs Interface, plots, archive and campaign controls
dist/batch-worker.mjs Browser campaign computation
server/ Worker API, owner-scoped storage and local adapters
db/schema.ts, drizzle/ Schema and generated immutable migrations
research/ Frozen protocol, execution, analysis and reports
tests/ Numerical, discovery, storage and source checks

dist/ still contains authored browser source. dist/server/ and dist/.openai/ are ignored build output.

Checks and hosting

npm test
npm run build

Tests cover motion invariants, deterministic replay, known equation recovery, parser rejection, observation coverage, real SQLite migrations, authentication, owner isolation, immutable IDs, idempotent saves and malformed input rejection. CI runs on Windows and Linux with Node.js 24.

The production build emits a Cloudflare Workers-compatible ES module with the website assets and D1 migrations. Declare logical DB and BUCKET bindings in your hosting environment. Authentication uses the Sites gateway's verified user header; do not expose the Worker through an untrusted proxy that forwards arbitrary identity headers. Instance-specific Sites configuration stays out of Git.

Contributions and methodological critiques are welcome. Released under the MIT License, © 2026 ChristopherJohannesKoen.

About

Traffic simulation and autonomous ODE/PDE closure experiments with configurable arrival rates, reproducible runs, derivations, and archived validation data.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages