Written and maintained by CASRAI Editorial Board
Published
On this page
MATSim (Multi-Agent Transport Simulation) is an open-source, activity-based simulation framework developed by researchers at TU Berlin and ETH Zurich that models transport networks at the individual agent level. Unlike traditional aggregate four-step traffic models that compute static link volumes, MATSim simulates the daily activity-travel schedules of millions of autonomous synthetic travelers over a co-evolutionary iterative loop. In each iteration, synthetic agents execute daily plans across a dynamic queue-based network simulation, evaluate their experienced utility using the microeconomic Charypar-Nagel scoring function, and adaptively modify their departure times, routes, and modes through stochastic replanning until the overall transport system converges to a dynamic user equilibrium.
Definition, Origins, and the Co-Evolutionary Simulation Loop
Formalized by Horni, Nagel, and Axhausen (2016), MATSim resolves the trade-off between macroscopic assignment and microscopic traffic simulators. Microscopic models simulate granular vehicle kinematics such as lane-changing, preventing regional scaling across millions of individuals. Static four-step models scale effectively but aggregate trips into origin-destination matrices, losing schedule constraints and time-dependent congestion feedback. MATSim bridges this gap by pairing a mesoscopic queue-based mobility simulation with an evolutionary agent optimization cycle.
The computational engine of MATSim iterates through four continuous stages until system equilibrium is achieved:
- Initial Demand Ingestion: Synthetic agents are instantiated with demographic attributes and daily activity plans specifying chains of home, work, and leisure activities linked by travel legs. Transport studies frequently couple this demand synthesis with land-use modeling platforms such as UrbanSim to project long-range spatial demographic shifts onto daily network trips.
- Mobility Simulation (MobSim / QSim): Agents execute schedules concurrently on a shared road graph. The QSim engine models road links as spatial storage queues with defined flow capacities and storage limits. Vehicles traverse links at free-flow speeds until queues form, capturing dynamic spillbacks and intersection delays without microscopic physics.
- Plan Scoring: Following the simulated 24-hour day, a scoring module evaluates each executed plan using the Charypar-Nagel utility function. Positive utility accrues from activity duration, while travel duration, tolls, transit fares, and late arrival penalties yield disutility.
- Replanning and Selection: Prior to the next iteration, a fraction of agents modify plans through genetic mutation heuristics (such as Dijkstra rerouting, departure time shifts, or mode changes). Remaining agents select an existing plan from memory using a multinomial logit choice model based on historical scores.
Through repeated iterations, poorly performing routes and schedules are abandoned while high-utility plans are retained. This evolutionary pressure drives the simulated transport system toward a microscopic Nash equilibrium where no agent can unilaterally improve their daily score by altering their departure time, route, or transport mode.
Mathematical Formulation of the Charypar-Nagel Scoring Function
Rooted in William Vickrey’s bottleneck congestion model, the total utility of an executed daily plan S_plan is the algebraic sum of utilities earned across all completed activities and disutilities incurred during all travel legs:
S_plan = Σ S_act,q + Σ S_trav,q
Where q indexes each consecutive activity and leg across the simulated day. Each parameter reflects a behavioral coefficient calibrated to empirical travel surveys:
Activity Performance Utility (S_act,q)
The utility derived from performing an activity q over an executed duration t_dur,q is expressed through a logarithmic formulation reflecting diminishing marginal returns:
S_act,q = S_dur,q + S_late.ar,q + S_early.dp,q + S_short.dur,q + S_wait,q
The duration utility component S_dur,q is defined as:
S_dur,q(t_dur,q) = β_dur × t_typ,q × ln(t_dur,q / t_0,q)
Where β_dur is performing marginal utility (+6.00 utils/h), t_dur,q is executed duration, t_typ,q is typical target duration, and t_0,q is the zero-utility threshold. Arriving after the scheduled start deadline t_start,max adds a late penalty:
S_late.ar,q = β_late.ar × max(0, t_start,q – t_start,max,q)
Where β_late.ar is the marginal penalty rate for arriving late (-18.00 utils/hour). Early departures incur a penalty scaled by β_early.dp.
Travel Leg Disutility (S_trav,q)
Travel between activity locations produces generalized travel disutility formulated across time, distance, and monetary expenses:
S_trav,q = β_trav,m × t_trav,q + β_m × Δm_q + β_dist,m × d_trav,q + c_m
Where β_trav,m is travel time marginal utility (-6.00 utils/h for car; -4.00 utils/h for transit; -12.00 utils/h for walking), t_trav,q is travel time in hours, β_m is the marginal utility of money (+1.00 utils/dollar), Δm_q represents tolls or transit fares, β_dist,m is operating cost (-0.10 utils/km), d_trav,q is distance in km, and c_m is a mode constant.
The table below provides standard calibrated parameters established by TU Berlin transport modelers:
| Behavioral Parameter | Symbol | Standard Default Value | Unit | Economic Interpretation |
|---|---|---|---|---|
| Performing Marginal Utility | β_dur | +6.00 | utils / hour | Opportunity value of engaging in out-of-home activities |
| Late Arrival Penalty | β_late.ar | -18.00 | utils / hour | Disutility of arriving after scheduled work start |
| Early Departure Penalty | β_early.dp | -0.00 to -12.00 | utils / hour | Disutility of truncating planned activity duration |
| Car Travel Time Utility | β_trav,car | -6.00 | utils / hour | Direct time cost of private passenger car travel |
| Transit Travel Time Utility | β_trav,pt | -4.00 | utils / hour | In-vehicle transit travel time disutility |
| Walk Travel Time Utility | β_trav,walk | -12.00 | utils / hour | Physical effort penalty for walking and transit access |
| Marginal Utility of Money | β_m | +1.00 | utils / monetary unit | Conversion rate between subjective utility and currency |
| Car Distance Cost | β_dist,car | -0.10 | utils / km | Vehicle depreciation and fuel operating cost per kilometer |
Worked Example: Step-by-Step Daily Plan Score Calculation
To verify scoring arithmetic, consider the daily schedule of synthetic commuter Agent_4102. The agent departs home, drives to work crossing a tolled bridge, arrives slightly late due to congestion, works a full shift, drives to a fitness center, and returns home. We apply standard parameters: β_dur = +6.00 utils/h, β_trav,car = -6.00 utils/h, β_late.ar = -18.00 utils/h, β_m = +1.00 utils/dollar, and β_dist,car = -0.10 utils/km.
- Activity 1 (Home – Cumulative Daily Duration): The agent spends 8.0 hours at home in the morning and 4.5 hours at night (total t_dur = 12.5 h; t_typ = 12.0 h; t_0 = 1.5 h).
S_home = 6.00 × 12.0 × ln(12.5 / 1.5) = 72.0 × ln(8.3333) = 72.0 × 2.12026 = +152.6590 utils. - Trip 1 (Home to Work – Car with Toll): Travel duration = 0.50 h, distance = 15.0 km, bridge toll = $3.00.
Time disutility: -6.00 × 0.50 = -3.00 utils; distance cost: -0.10 × 15.0 = -1.50 utils; toll: -1.00 × 3.00 = -3.00 utils.
S_trip1 = -3.00 + (-1.50) + (-3.00) = -7.5000 utils. - Activity 2 (Work with Late Arrival Penalty): Actual start at 08:45 vs. 08:30 deadline (late = 0.25 h); duration t_dur = 8.5 h (t_typ = 8.0 h; t_0 = 1.0 h).
Duration utility: 6.00 × 8.0 × ln(8.5 / 1.0) = 48.0 × 2.14007 = +102.7232 utils.
Late arrival penalty: -18.00 × 0.25 = -4.50 utils.
S_work = 102.7232 – 4.50 = +98.2232 utils. - Trip 2 (Work to Recreation – Car): Travel duration = 0.40 h, distance = 10.0 km, parking charge = $2.00.
Time disutility: -6.00 × 0.40 = -2.40 utils; distance cost: -0.10 × 10.0 = -1.00 utils; parking: -1.00 × 2.00 = -2.00 utils.
S_trip2 = -2.40 + (-1.00) + (-2.00) = -5.4000 utils. - Activity 3 (Recreation / Leisure): Duration t_dur = 1.5 h (t_typ = 2.0 h; t_0 = 0.25 h).
S_leisure = 6.00 × 2.0 × ln(1.5 / 0.25) = 12.0 × ln(6.0) = 12.0 × 1.79176 = +21.5011 utils. - Trip 3 (Recreation to Home – Car): Travel duration = 0.60 h, distance = 12.0 km, zero tolls.
Time disutility: -6.00 × 0.60 = -3.60 utils; distance cost: -0.10 × 12.0 = -1.20 utils.
S_trip3 = -3.60 + (-1.20) = -4.8000 utils. - Total Plan Score Summation: Combining all activities and trips yields:
S_plan = 152.6590 + (-7.5000) + 98.2232 + (-5.4000) + 21.5011 + (-4.8000) = +254.6833 utils.
This net score of +254.6833 utils is recorded in Agent_4102’s memory. In subsequent iterations, if a replanning module adjusts departure time 15 minutes earlier, eliminating the -4.50 utils late penalty, the plan score will rise to +259.1833 utils and become preferentially selected under the agent’s choice model.
Interpreting Simulation Results and Equilibrium Convergence
Evaluating MATSim outputs requires analyzing system relaxation rather than static capacity ratios. Because agents mutate plans stochastically via Monte Carlo simulation heuristics, early iterations exhibit score variance. Across 60 to 120 iterations, scores stabilize as agents settle into equilibrium. Plan choice follows random utility theory, comparable to frameworks like PyBLP, where the probability P(i) of selecting plan i from memory size K is:
P(i) = exp(β_scale × S_i) / Σ exp(β_scale × S_j)
The diagnostic table below guides the interpretation of simulation stability and convergence:
| Diagnostic Metric | Target Convergence Pattern | Diagnostic Interpretation | Recommended Correction Strategy |
|---|---|---|---|
| Average Executed Score | Monotonically increases and plateaus within 1% variation over 20 iterations | System has reached dynamic user equilibrium; agents can no longer find superior routes | If scores oscillate, reduce replanning mutation rates or increase agent plan memory size K |
| Modal Share Stability | Car, transit, and active mode shares fluctuate by less than 0.5% per iteration | Mode choice equilibrium established; generalized costs between alternatives are balanced | If one mode dominates unrealistically, recalibrate mode-specific constants (c_m) and transit fares |
| Traffic Volume vs. Counts | R² > 0.85 and GEH statistic < 5.0 on at least 85% of physical counting stations | Mesoscopic queue mobility simulation reliably reproduces empirical roadway flows | Calibrate flowCapacityFactor and storageCapacityFactor to adjust bottleneck discharge rates |
| Trip Travel Time Ratio | Peak-to-off-peak travel time ratios match regional sensor observations within 10% | Congestion delays, bottleneck queues, and intersection spillbacks are realistically simulated | Refine network link capacities, free speeds, and traffic signal timings |
| Plan Memory Fill Rate | Agents maintain full memories with distinct routes and departure profiles | Agents preserve viable fallback plans to respond to unexpected network disturbances | If stored plans are identical, increase mutation ranges in TimeAllocationMutator |
Key Assumptions and Common Implementation Mistakes
Understanding MATSim’s foundational assumptions is essential for rigorous transport modeling:
- Day-to-Day Learning vs. Within-Day Adaptation: Standard MATSim assumes that agents adapt between days rather than within a single trip. Agents choose routes and departure times based on expectations formed over previous iterations. Representing spontaneous within-trip diversions requires specialized dynamic replanning modules.
- Queue Model Simplifications: The mesoscopic QSim engine treats vehicles as discrete point entities traveling along links and waiting in spatial queues. It does not model microscopic vehicle physics such as lane-changing or weaving turbulence.
- Synthetic Population Fidelity: Simulation accuracy depends directly on the quality of the input population and activity schedules. If synthetic populations lack accurate spatial distributions or omit commercial truck trips, link traffic counts will diverge from reality.
Frequent implementation mistakes include:
- Sample Scale Factor Mismatches: When simulating a sample population (such as a 10% or 25% sample), researchers must scale road network flow and storage capacity factors (flowCapacityFactor and storageCapacityFactor) proportionally. Running a 10% sample on an unscaled 100% capacity network eliminates congestion, distorting mode choice and travel times.
- Distorted Behavioral Parameter Ratios: The ratio between travel time disutility and monetary marginal utility (β_trav / β_m) establishes the implied Value of Travel Time Savings (VTTS). Violating regional empirical VTTS benchmarks produces irrational detours or unrealistic toll avoidance.
- Inconsistent Network Coordinate Projections: MATSim requires planar Cartesian coordinate projections (such as UTM) to calculate link lengths and spatial buffers. Ingesting raw latitude/longitude coordinates (WGS84) corrupts queue physics. GIS network layers must conform to standard spatial data infrastructure specifications before simulation ingest.
- Premature Simulation Termination: Ending simulations before plan scores have plateaued (e.g., after only 25 iterations) captures nonequilibrium transient fluctuations rather than relaxed policy outcomes.
How to Report MATSim Methodology in Research (APA Format)
Academic transportation and regional science journals require transparent documentation of agent-based simulation setups. Under APA 7th edition reporting guidelines, researchers should state the model version, sample fraction, network attributes, scoring coefficients, replanning parameters, and empirical validation metrics.
Methodological Reporting Example (APA 7th):
“Travel demand and dynamic network equilibrium were modeled using the open-source Multi-Agent Transport Simulation (MATSim, Version 15.0; Horni et al., 2016). The scenario comprised a synthetic population of 1.42 million agents representing a 10% sample of the metropolitan area, synthesized from the regional travel survey. Road network flow and storage capacities across 42,180 links were scaled to 0.10. Agent behavior was evaluated using the Charypar-Nagel scoring function with calibrated marginal utilities of activity performing (β_perf = +6.00 utils/hr), car travel time (β_car = -6.00 utils/hr), public transit travel time (β_pt = -4.20 utils/hr), and late work arrival (β_late = -18.00 utils/hr). The marginal utility of money was set to β_m = +0.85 utils/USD, producing an implied value of travel time savings of $7.06/hr for car commuters. Replanning strategies included time mutation (10%, range = 3,600 s), Dijkstra rerouting (10%), and subtour mode choice (5%), with plan selection governed by the SelectExpBeta algorithm (memory size K = 5). The simulation reached convergence after 150 iterations, achieving an executed score variance < 0.5% over the final 25 iterations and validating against 140 arterial count stations with an R² of 0.88 and a GEH statistic < 5.0 on 86.4% of observation locations."
How to Configure, Run, and Analyze MATSim in Python and R
While MATSim executes in Java, scenario scripting, parameter tuning, and post-simulation data analysis are routinely automated in Python and R. The snippets below demonstrate how to compute plan scores, verify parameters, and track iteration convergence.
Python Script for Plan Scoring
import math
def calculate_matsim_score(activities, legs, beta_perf=6.0, beta_late=-18.0,
beta_travel=-6.0, beta_dist=-0.10, beta_money=1.0):
total_score = 0.0
for act in activities:
dur = act['t_dur']
typ = act['t_typ']
t0 = act['t0']
s_dur = beta_perf * typ * math.log(dur / t0)
late_h = max(0.0, act.get('late_hours', 0.0))
s_late = beta_late * late_h
total_score += (s_dur + s_late)
for leg in legs:
s_time = beta_travel * leg['travel_time_h']
s_dist = beta_dist * leg['dist_km']
s_cost = -1.0 * beta_money * leg.get('cost', 0.0)
total_score += (s_time + s_dist + s_cost)
return total_score
activities = [
{'type': 'home', 't_dur': 12.5, 't_typ': 12.0, 't0': 1.5, 'late_hours': 0.0},
{'type': 'work', 't_dur': 8.5, 't_typ': 8.0, 't0': 1.0, 'late_hours': 0.25},
{'type': 'leisure', 't_dur': 1.5, 't_typ': 2.0, 't0': 0.25, 'late_hours': 0.0}
]
legs = [
{'mode': 'car', 'travel_time_h': 0.50, 'dist_km': 15.0, 'cost': 3.00},
{'mode': 'car', 'travel_time_h': 0.40, 'dist_km': 10.0, 'cost': 2.00},
{'mode': 'car', 'travel_time_h': 0.60, 'dist_km': 12.0, 'cost': 0.00}
]
score = calculate_matsim_score(activities, legs)
print(f'Computed Plan Score: {score:.4f} utils')
// Returns: 254.6833 utils
R Script for Tracking Score Convergence
score_stats <- read.csv("output/scorestats.csv", sep = "t", header = TRUE)
plot(score_stats$ITERATION, score_stats$avg.EXEC,
type = "l", col = "blue", lwd = 2,
xlab = "Simulation Iteration",
ylab = "Average Executed Score (utils)",
main = "MATSim Equilibrium Convergence")
lines(score_stats$ITERATION, score_stats$avg.BEST, col = "darkgreen", lty = 2)
legend("bottomright", legend = c("Executed Plan Avg", "Best Plan Avg"),
col = c("blue", "darkgreen"), lty = 1:2, lwd = 2)
Spreadsheet Calculation Implementation
Modelers validating utility values in spreadsheets can apply native formulas:
- Activity Duration Utility:
=B$1 * B3 * LN(C3 / D3)where B$1 is β_dur, B3 is typical duration, C3 is executed duration, and D3 is zero-utility threshold. - Late Arrival Penalty:
=B$2 * MAX(0, E3 - F3)where B$2 is β_late.ar, E3 is arrival time, and F3 is scheduled start deadline. - Travel Leg Disutility:
=(B$3 * G3) + (B$4 * H3) - (B$5 * I3)where B$3 is β_trav, G3 is travel time, B$4 is β_dist, H3 is distance, B$5 is β_m, and I3 is monetary expenditure. - Total Plan Score:
=SUM(Activity_Scores) + SUM(Leg_Scores).
To examine the functional roles and mathematical parameters across simulation stages, the data table below summarizes core MATSim engine components.
Frequently asked questions
What does MATSim stand for?
MATSim stands for Multi-Agent Transport Simulation. It is an open-source, modular framework implemented in Java that models dynamic, activity-based travel behavior and transport network flows at the level of individual synthetic travelers.
How does the MATSim iterative loop work?
The MATSim loop functions through a co-evolutionary cycle consisting of daily plan execution in the queue mobility simulation, microeconomic evaluation via the Charypar-Nagel utility function, stochastic replanning across routes and departure times, and discrete choice plan selection. This cycle repeats until the transport network reaches a dynamic user equilibrium.
What programming language is MATSim implemented in?
MATSim’s core engine, libraries, and simulation modules are written in Java and compiled via Maven or Gradle. However, synthetic population synthesis, scenario configuration, and post-simulation data analytics are widely conducted using Python and R.
Where can researchers download MATSim and access scenario data?
Researchers can download official releases, source code, and extensions from the official MATSim website (matsim.org) and its GitHub repository (github.com/matsim-org/matsim-libs). The project documentation and ‘The MATSim Book’ provide open-access tutorials and benchmark scenarios such as Sioux Falls, Berlin, and Zurich.
How does MATSim differ from traditional macroscopic traffic models?
Traditional four-step macroscopic models aggregate trips into static origin-destination matrices and assign vehicle volumes to links using static formulas. In contrast, MATSim simulates discrete synthetic agents with complete daily activity schedules, capturing dynamic bottleneck spillbacks, individual mode choice trade-offs, and equity distributions across traveler sub-populations.
Can MATSim simulate public transit and autonomous vehicle fleets?
Yes, MATSim includes native extensions for scheduled public transit (buses, trams, commuter rail) as well as specialized modules for dynamic demand-responsive transit (DRT), ride-pooling fleets, and autonomous vehicles (AVs). It models vehicle dispatching, passenger wait times, fleet rebalancing, and electric vehicle charging constraints.
Sources
- MATSim: The Multi-Agent Transport Simulation Official Book Repository, checked 2026-11-20
- MATSim: Official Documentation and Technical Manual, checked 2026-11-20
- GitHub: matsim-org/matsim-libs (Multi-Agent Transport Simulation Core Framework), checked 2026-11-20
- ETH Library: The Multi-Agent Transport Simulation MATSim (Horni, Nagel, and Axhausen, Eds., Ubiquity Press), checked 2026-11-20
- TU Berlin: Transport Systems Planning and Telematics (Verkehrssystemplanung und Verkehrstelematik), checked 2026-11-20
Data: Core MATSim Simulation Engine Modules, Behavioral Roles, and Mathematical Configurations
Comprehensive comparative catalog of core functional modules within the Multi-Agent Transport Simulation (MATSim) platform, outlining simulation phase execution, primary algorithmic duties, input file definitions, default mathematical parameters, and equilibrium convergence impacts compiled from the MATSim reference manual (Horni, Nagel, & Axhausen, 2016) and project technical specifications.
Period covered: 2016/2026. Coverage: Global.
| Module / Engine Component | Simulation Phase | Primary Algorithmic Function | Input XML File | Default Parameter or Formula Reference | Typical Convergence Impact |
|---|---|---|---|---|---|
| QSim (Queue Mobility Simulation) | Mobility Simulation (MobSim) | Simulates dynamic queue spillback and link storage capacity on road networks | network.xml | storageCapacityFactor = 0.05 to 1.0, flowCapacityFactor = 0.05 to 1.0 | Determines realistic travel times and congestion delays per iteration |
| Charypar-Nagel Scoring | Scoring Evaluation | Calculates microeconomic utility of completed daily activity-travel schedules | config.xml (scoring module) | beta_perf = +6.00/h, beta_trav_car = -6.00/h, beta_late = -18.00/h | Evaluates plan fitness and penalizes congestion delays and schedule violations |
| Re-routing (Dijkstra / A-Star) | Replanning (Mutation) | Recalculates time-dependent shortest paths using travel times observed in previous iteration | config.xml (strategy module) | Strategy: ReRoute, weight = 0.10 to 0.15 | Enables spatial diversion away from bottleneck corridors towards user equilibrium |
| Time Allocation Mutator | Replanning (Mutation) | Shifts departure times and activity durations using Gaussian perturbations | config.xml (strategy module) | Strategy: TimeAllocationMutator, mutationRange = 7200 s | Spreads peak-hour departures to reduce peak congestion penalties |
| Sub-tour Mode Choice | Replanning (Mutation) | Permutes transport modes (car, pt, bike, walk) across nested activity subtours | config.xml (strategy module) | Strategy: SubtourModeChoice, modes = car,pt,bike,walk | Redistributes modal share across alternative transport networks based on utility |
| SelectExpBeta (Choice Model) | Plan Selection | Selects executed plan from agent memory using multinomial logit selection probability | config.xml (strategy module) | Strategy: SelectExpBeta, maxAgentPlanMemorySize = 4 to 6 | Controls exploration versus exploitation balance in agent plan selection |
| Public Transit (PT) Engine | Mobility Simulation (MobSim) | Simulates scheduled transit vehicles, passenger boardings, and transfer coordination | transitSchedule.xml | beta_trav_pt = -4.00/h, marginalUtilityOfMoney = +1.00 | Models transit overcrowding, timetable adherence, and multi-modal transfers |
| Dynamic Demand-Responsive Transit (DRT) | Mobility Simulation (MobSim) | Dispatches automated fleet vehicles to service on-demand passenger trip requests | drt.xml | maxWaitTime = 600 s, maxTravelTimeAlpha = 1.5 | Enables policy testing for ride-pooling, robo-taxis, and micro-transit integration |
Sources
- The Multi-Agent Transport Simulation MATSim (Horni, Nagel, & Axhausen, Eds., Ubiquity Press) (accessed 2026-11-20)
- MATSim Official Documentation (accessed 2026-11-20)
- MATSim Core Libraries Repository (accessed 2026-11-20)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







