### Run Small Trip Maker Example (Minimal Framework) Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/atap/docs/README.md Executes a small agent-based example for testing parallel link networks. Generates a .tsv file with convergence statistics. ```java ExampleRunner.java ``` -------------------------------- ### Run MATSim GUI Source: https://github.com/matsim-org/matsim-libs/blob/main/matsim/README.txt Starts the MATSim GUI by executing the main JAR file. This is useful for interactive use and configuration. ```bash java -jar matsim-x.y.z.jar ``` -------------------------------- ### Install Informed Mode Choice Module Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/informed-mode-choice/README.md Install the configured Informed Mode Choice module into the MATSim controller. This step integrates the custom mode choice logic into the simulation. ```java controler.addOverridingModule(builder.build()); ``` -------------------------------- ### Install MATSim Core Only Source: https://github.com/matsim-org/matsim-libs/blob/main/README.md Installs only the core MATSim module. The `--also-make` flag ensures that dependencies are built, and `--projects matsim` specifies the target module. ```bash mvn install --also-make --projects matsim ``` -------------------------------- ### Run Berlin Example (MATSim) Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/atap/docs/README.md Demonstrates ATAP route assignment using the Berlin scenario files. Based on the scenario used in Flötteröd (2025). ```java RunBerlinExample.java ``` -------------------------------- ### Configure Discrete Mode Choice via XML Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/GettingStarted.md Example XML configuration for the Discrete Mode Choice module. This demonstrates how to set parameters like model type, selector, constraints, and mode availability. ```xml ``` -------------------------------- ### Run Oslo Example (MATSim) Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/atap/docs/README.md Demonstrates ATAP route, departure time, and mode assignment using the Oslo scenario files. Based on the scenario used in Flötteröd (2025). ```java RunOsloExample.java ``` -------------------------------- ### Command Line Overrides for DRT Benchmark Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/benchmark/README.md Examples of command-line arguments used to override DRT benchmark configuration parameters, following the MATSim convention. ```bash --config:drtBenchmark.requestInserterTypes Default,Parallel --config:drtBenchmark.insertionSearchStrategies Selective,Extensive,RepeatedSelective --config:drtBenchmark.agentCounts 50000,100000,200000 --config:drtBenchmark.maxPartitions 16 --config:drtBenchmark.vehiclePartitioners Replicating,RoundRobin --config:drtBenchmark.outputDirectory output/my-benchmark ``` -------------------------------- ### JVM Arguments for Communication Libraries Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/distributed-simulation/README.md When running a distributed setup, certain JVM options are required for communication libraries. Add these arguments to your JVM launch configuration. ```shell --add-opens java.base/jdk.internal.misc=ALL-UNNAMED --add-exports java.base/jdk.internal.ref=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens java.management/sun.management=ALL-UNNAMED --add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED ``` -------------------------------- ### Implement Person-Specific Routing Costs in Java Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/sbb-extensions/README.md Customize routing parameters per person by implementing the RaptorParametersForPerson interface. Bind your custom implementation after installing the SwissRailRaptorModule. ```java // somewhere in your main method, where you set up your controler: controler.addOverridingModule(new SwissRailRaptorModule()); controler.addOverridingModule(new AbstractModule() { @Override public void install() { bind(RaptorParametersForPerson.class).to(MyPersonSpecificRaptorParameters.class); } }); ``` -------------------------------- ### Example DRT Benchmark CSV Results Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/benchmark/README.md This CSV data represents sample results from a DRT benchmark, detailing various performance and quality metrics for different configurations. ```csv name,iterations,min_ms,max_ms,avg_ms,stddev_ms,rides,rejections,rejection_rate,wait_avg_s,wait_p95_s,in_vehicle_time_s,total_travel_time_s Default_Selective_50k,1,95000,95000,95000,0,42100,7900,0.1580,8500,17200,690,9190 Default_Extensive_50k,1,180000,180000,180000,0,43500,6500,0.1300,7800,15900,685,8485 Parallel_Selective_ShiftRR_LoadAware_cp90_50k,1,45000,45000,45000,0,41025,8975,0.1800,9712,19520,708,10420 Parallel_Extensive_ShiftRR_LoadAware_cp90_50k,1,72000,72000,72000,0,42800,7200,0.1440,8900,17800,695,9595 ``` -------------------------------- ### Configure Informed Mode Choice Module Builder Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/informed-mode-choice/README.md Configure default estimators, mode availability, and pruners for the Informed Mode Choice module. Use `AlwaysAvailable` for modes accessible to all agents, `ConsiderIfCarAvailable` for car-specific conditions, and `PtTripEstimator` for public transport trip analysis. Install a `DistanceBasedPruner` for plan pruning. ```java InformedModeChoiceModule.Builder builder = InformedModeChoiceModule.newBuilder() // Car has a non zero daily costs, so fixed costs need to be considered .withFixedCosts(FixedCostsEstimator.DailyConstant.class, "car") // Configure modes that are available for all agents .withLegEstimator(DefaultLegScoreEstimator.class, ModeOptions.AlwaysAvailable.class, "ride", "bike", "walk") // Car can only be used if the "carAvail" attribute allows it .withLegEstimator(DefaultLegScoreEstimator.class, ModeOptions.ConsiderIfCarAvailable.class, "car") // Pt estimator is not leg based but needs to know the whole trip .withTripEstimator(PtTripEstimator.class, ModeOptions.AlwaysAvailable.class, "pt"); // Adds a subtour constraint .withConstraint(RelaxedSubtourConstraint.class) // Install a pruner based on score and distance .withPruner("name", new DistanceBasedPruner(10, 10)) ``` -------------------------------- ### Configure ActivityBased Tour Finder Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/components/TourFinder.md Defines the activity types that mark the start and end of a tour for the ActivityBased tour finder. If a plan does not begin or conclude with these specified activities, additional tours will be generated. ```xml ``` -------------------------------- ### Run Minibus Scenario from Command Line Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/minibus/README.md Execute the Minibus simulation using a downloaded JAR file and a configuration XML. Ensure sufficient memory is allocated with the -Xmx flag. ```bash java -Xmx2000m -jar minibus-0.X.0-SNAPSHOT.jar config.xml ``` -------------------------------- ### XML Configuration for Driver Shifts Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/operations/README.md Configures driver shifts with start and end times, an optional operation facility for shift start/end, and break details. Breaks are defined by earliest start, latest end, and duration. ```xml ``` -------------------------------- ### Run DRT Benchmark with Default and Overridden Parameters Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/drt-extensions/src/main/java/org/matsim/contrib/drt/extension/benchmark/README.md Execute the DRT scalability benchmark. Copy the sample configuration and then run the benchmark, optionally overriding parameters like request inserter types, insertion search strategies, detour path calculator types, agent counts, and max partitions via command line arguments. ```bash # Copy the sample config to your working directory cp src/main/resources/benchmark-config.xml my-benchmark-config.xml # Run with default configuration java -cp matsim.jar org.matsim.contrib.drt.extension.benchmark.RunScalabilityBenchmark \ --config-path my-benchmark-config.xml # Override parameters via command line java -cp matsim.jar org.matsim.contrib.drt.extension.benchmark.RunScalabilityBenchmark \ --config-path my-benchmark-config.xml \ --config:drtBenchmark.requestInserterTypes Default,Parallel \ --config:drtBenchmark.insertionSearchStrategies Selective,Extensive \ --config:drtBenchmark.detourPathCalculatorTypes SpeedyALT,CH \ --config:drtBenchmark.agentCounts 50000,100000,200000 \ --config:drtBenchmark.maxPartitions 16 ``` -------------------------------- ### Run MATSim Simulation from Command Line Source: https://github.com/matsim-org/matsim-libs/blob/main/matsim/README.txt Executes a MATSim simulation using a specified configuration file. Ensure the JAR file and config are accessible. ```bash java -cp matsim-x.y.z.jar org.matsim.run.RunMatsim myconfig.xml ``` -------------------------------- ### Import necessary Python libraries Source: https://github.com/matsim-org/matsim-libs/blob/main/code-examples/src/main/java/org/matsim/codeexamples/scoring/pseudoRandomErrors/Analysis.ipynb Imports common libraries for data manipulation, plotting, and subprocess management. Ensure these libraries are installed before running the code. ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import subprocess as sp from tqdm.notebook import tqdm_notebook import uuid, shutil import dill %matplotlib inline ``` -------------------------------- ### Create output directory Source: https://github.com/matsim-org/matsim-libs/blob/main/code-examples/src/main/java/org/matsim/codeexamples/scoring/pseudoRandomErrors/Analysis.ipynb Ensures an 'output' directory exists to store experiment results. If the directory already exists, it is ignored. ```python try: os.mkdir("output") except FileExistsError: pass ``` -------------------------------- ### Define Load Slots in DRT Config Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/dvrp/src/main/java/org/matsim/contrib/dvrp/load/README.md Configure the available load slots for DRT. This example defines 'passengers' and 'luggage' as distinct load types. ```xml ``` -------------------------------- ### Calculate Skim Matrices with SBB MATSim Extensions Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/sbb-extensions/README.md This is the basic template for calculating skim matrices. It demonstrates how to initialize the calculator and call methods for sampling points, calculating network and PT matrices, and the beeline matrix. Ensure all required parameters and filenames are correctly provided. ```java CalculateSkimMatrices skims = new CalculateSkimMatrices(zonesShapeFilename, zonesIdAttributeName, outputDirectory, numberOfThreads); skims.calculateSamplingPointsPerZoneFromFacilities(facilitiesFilename, numberOfPointsPerZone, r, facility -> 1.0); // alternative if you don't have facilities: // skims.calculateSamplingPointsPerZoneFromNetwork(networkFilename, numberOfPointsPerZone, r); skims.calculateNetworkMatrices(networkFilename, eventsFilename, timesCar, config, null, link -> true); skims.calculatePTMatrices(networkFilename, transitScheduleFilename, earliestTime, latestTime, config, null, (line, route) -> route.getTransportMode().equals("train")); skims.calculateBeelineMatrix(); ``` -------------------------------- ### Configure MATSim Events to Use Protobuf Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/protobuf/README.md Add 'pb' to the `eventsFileFormat` in your MATSim controller configuration to enable Protobuf event logging. This results in files that can be read by the MATSim Python package for better performance. ```xml ``` -------------------------------- ### Import Libraries for Melun DRT Analysis Source: https://github.com/matsim-org/matsim-libs/blob/main/code-examples/src/main/resources/org/matsim/codeexamples/extensions/drt/melun/Melun prebooking analysis.ipynb Imports essential Python libraries for data manipulation, plotting, and geospatial analysis. Ensure these libraries are installed before running. ```python import numpy as np import matplotlib.pyplot as plt import pandas as pd import geopandas as gpd import shapely.geometry as geo from tqdm.notebook import tqdm import glob %matplotlib inline ``` -------------------------------- ### Enable Deterministic PT Simulation (XML) Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/sbb-extensions/README.md Configure the SBBPt module in config.xml to enable deterministic simulation for specified modes and set link event generation interval. ```xml ``` -------------------------------- ### Initialize Plot for Operational Metrics Source: https://github.com/matsim-org/matsim-libs/blob/main/code-examples/src/main/resources/org/matsim/codeexamples/extensions/drt/melun/Melun prebooking analysis.ipynb Initializes a Matplotlib figure and subplot for plotting operational metrics. This is a setup step for generating detailed plots related to prebooking analysis. ```python plt.figure(dpi = 300, figsize = (6, 3)) plt.subplot(1, 2, 1) for horizon_index, horizon in enumerate(horizons): plt.plot([None], [None], color = "C{}".format(horizon_index), label = horizon_labels[horizon_index]) ``` -------------------------------- ### Package MATSim Core Source: https://github.com/matsim-org/matsim-libs/blob/main/README.md Use this command to package the core MATSim library, skipping tests. Ensure you are in the root directory of the project. ```bash mvn package -DskipTests ``` -------------------------------- ### Standard Event Sequence in WEVC Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/ev/README.md This sequence outlines the typical events generated during a charging process within the WEVC module, from starting a process to ending an attempt and the overall process. ```text StartChargingProcessEvent > StartChargingAttemptEvent > ChargingStartEvent > ChargingEndEvent > EndChargingAttemptEvent > EndChargingProcessEvent ``` -------------------------------- ### Registering a Custom Trip Estimator Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/GettingStarted.md Register a custom trip estimator by creating a class that extends AbstractDiscreteModeChoiceExtension and binding the custom estimator in the installExtension method. This example binds 'MyTripEstimator' to the name 'MyEstimatorName'. ```java public class MyDMCExtension extends AbstractDiscreteModeChoiceExtension { @Override public void installExtension() { bindTripEstimator("MyEstimatorName").to(MyTripEstimator.class); } } // ... controller.addOverridingModule(new MyDMCExtenson()); ``` -------------------------------- ### Build Executable JAR with Maven Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/distributed-simulation/README.md Build an executable JAR file for the MATSim distributed simulation contrib using Maven. Ensure the 'skipShaded' option is set to false to include all necessary dependencies. ```shell mvn package -DskipShaded=false ``` -------------------------------- ### Custom Trip Estimator Implementation Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/GettingStarted.md Implement a custom trip estimator by extending AbstractTripRouterEstimator and overriding the estimateTrip method. This example calculates utility based on travel time and distance for different modes. ```java public class MyTripEstimator extends AbstractTripRouterEstimator { @Inject public MyTripEstimator(TripRouter tripRouter, Network network, ActivityFacilities facilities) { super(tripRouter, network, facilities); } @Override protected double estimateTrip(Person person, String mode, DiscreteModeChoiceTrip trip, List previousTrips, List routedTrip) { // I) Calculate total travel time double totalTravelTime = 0.0; double totalTravelDistance = 0.0; for (PlanElement element : routedTrip) { if (element instanceof Leg) { Leg leg = (Leg) element; totalTravelTime += leg.getTravelTime() / 3600.0; totalTravelDistance += leg.getRoute().getDistance() * 1e-3; } } // II) Compute mode-specific utility double utility = 0; switch (mode) { case TransportMode.car: utility = -0.5 - 0.025 * totalTravelDistance; break; case TransportMode.pt: utility = -0.15 - 0.15 * totalTravelTime; break; case TransportMode.walk: utility = -1.0 * totalTravelTime; break; } return utility; } } ``` -------------------------------- ### Configure Maximum Utility Selector (XML) Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/GettingStarted.md Enable the maximum utility selection mechanism by setting the 'selector' parameter in the configuration file. This ensures that the alternative with the highest utility is always chosen. ```xml ``` -------------------------------- ### Add Frozen Error Term to Utility Calculation (Java) Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/GettingStarted.md Extend the utility calculation in your trip estimator to include a frozen error term. This example reads the error from activity attributes, specific to the mode. ```java utility += (Double) trip.getOriginActivity().getAttributes().getAttribute("next_error_" + mode); ``` -------------------------------- ### Configure Activity-Based Tour Finder Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/GettingStarted.md Sets the tour finder to 'ActivityBased', defining tours as trip chains between 'home' activities. This is the recommended configuration. ```xml ``` -------------------------------- ### Define a MATSim Application Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/application/README.md Extend MATSimApplication and define a main function to create a runnable MATSim application. Use annotations to specify preparation and analysis steps. ```java @CommandLine.Command(header = ":: Open City Scenario ::", version = "1.0") @MATSimApplication.Prepare({ CreateNetworkFromSumo.class, CreateTransitScheduleFromGtfs.class, TrajectoryToPlans.class, GenerateShortDistanceTrips.class }) @MATSimApplication.Analysis({ AnalysisSummary.class, TravelTimeAnalysis.class }) public class RunCityScenario extends MATSimApplication { public RunCityScenario() { // The default config to use when no other config is given by the user super("scenarios/input/city-v1.0-25pct.config.xml"); } public static void main(String[] args) { MATSimApplication.run(RunCityScenario.class, args); } } ``` -------------------------------- ### Custom Route Selector Implementation Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/sbb-extensions/README.md Implement a custom route selector by binding your class to the RaptorRouteSelector interface within your MATSim controller setup. This allows for more complex choice behaviors beyond the default algorithm. ```java // somewhere in your main method, where you set up your controler: controler.addOverridingModule(new SwissRailRaptorModule()); controler.addOverridingModule(new AbstractModule() { @Override public void install() { bind(RaptorRouteSelector.class).to(MyCustomRouteSelector.class); } }); ``` -------------------------------- ### DSim Configuration Module Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/distributed-simulation/README.md Configure the distributed simulation (DSim) module with various parameters similar to QSim. This XML snippet shows common settings like end time, link dynamics, and partitioning strategy. ```xml ``` -------------------------------- ### Define Train Vehicle Type with Railsim Attributes Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/railsim/docs/train-specification.md Example of defining a train vehicle type in MATSim's XML configuration, including custom railsim attributes for acceleration and deceleration. Ensure the network mode is set to 'rail'. ```xml 0.4 0.5 ``` -------------------------------- ### Configure ActivityBased Home Finder Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/components/HomeFinder.md Sets up the ActivityBased home finder to use specific activity types as the home location. This is a comma-separated list. ```xml ``` -------------------------------- ### Configure VehicleContinuity Constraint (Tour) Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/components/Constraint.md Defines modes that must fulfill continuity constraints, meaning they can only be used if the respective vehicle has been moved to the new departure location beforehand. The vehicle must also start at and return to a home location, which is inferred by the HomeFinder component. ```xml ``` -------------------------------- ### Run Basic MATSim Scenario Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/GettingStarted.md This script sets up and runs a basic MATSim simulation using the Sioux Falls scenario. It configures the controller to overwrite output directories and loads the scenario. ```java public class RunRandomSelection { static public void main(String[] args) { URL configURL = IOUtils.newUrl(ExamplesUtils.getTestScenarioURL("siouxfalls-2014"), "config_default.xml"); Config config = ConfigUtils.loadConfig(configURL); config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); config.controler().setOutputDirectory("output"); Scenario scenario = ScenarioUtils.loadScenario(config); Controler controller = new Controler(scenario); controller.run(); } } ``` -------------------------------- ### Configuring Trip and Tour Constraints Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/components/Constraint.md Defines how to activate built-in trip and tour constraints in the Discrete Mode Choice module. Multiple constraints can be specified, separated by commas. ```xml ``` -------------------------------- ### Run and Collect Simulation Data (Python) Source: https://github.com/matsim-org/matsim-libs/blob/main/code-examples/src/main/java/org/matsim/codeexamples/scoring/pseudoRandomErrors/Analysis.ipynb Iterates through different strategies and innovation rates, runs simulations, and collects the results into a pandas DataFrame. Requires 'run_unconstrained' function and 'SAMPLE_SIZE', 'ITERATIONS' variables. ```python df_innovation_rates = [] for strategy in ["BestScore", "ChangeExpBeta"]: for innovation_rate in INNOVATION_RATES: for sample in range(SAMPLE_SIZE): df_sample = run_unconstrained( strategy = strategy, innovation_rate = innovation_rate, sample = sample, iterations = ITERATIONS ) df_sample["sample"] = sample df_sample["innovation_rate"] = innovation_rate df_sample["strategy"] = strategy df_innovation_rates.append(df_sample) df_innovation_rates = pd.concat(df_innovation_rates) ``` -------------------------------- ### Create Communicator and Distributed Controller Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/distributed-simulation/README.md Instantiate a Communicator (e.g., HazelcastCommunicator) and create the MATSim controller with a DistributedContext. This is essential for running simulations across multiple JVMs. ```java import org.matsim.core.communication.Communicator; import org.matsim.core.communication.HazelcastCommunicator; Communicator comm = new HazelcastCommunicator(0, 2, null); Controler controler = new Controler(scenario, DistributedContext.create(config)); ``` -------------------------------- ### Define Innovation Rates (Python) Source: https://github.com/matsim-org/matsim-libs/blob/main/code-examples/src/main/java/org/matsim/codeexamples/scoring/pseudoRandomErrors/Analysis.ipynb Sets up a list of innovation rates to be used in the simulation experiments. ```python INNOVATION_RATES = [0.05, 0.1, 0.2] ``` -------------------------------- ### Configure Trip and Tour Constraints Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/discrete_mode_choice/docs/GettingStarted.md Set the trip and tour constraints for the discrete mode choice model. These parameters define filters applied to alternatives. ```xml ``` -------------------------------- ### Add Custom Dashboard via Guice Binding Source: https://github.com/matsim-org/matsim-libs/blob/main/contribs/simwrapper/README.md Bind a custom dashboard implementation using Guice modules. This is the recommended approach when SimWrapper is used within a MATSim scenario that already utilizes Guice. ```java import org.matsim.simwrapper.SimWrapper; public class MyModule extends AbstractModule { @Override protected void configure() { // Use utility method, which just uses multi-binder internally SimWrapper.addDashboardBinding(binder()).toInstance(new CustomDashboard()); } } ```