This version of the MATSim tutorial was taught until April 2011. It is deprecated and a newer version exists
here. Sources for this tutorial can be found under: "src/main/java/tutorial".
Author: K. Meister
MATSim provides a toolbox to implement large-scale agent-based transport simulations. The toolbox consists of several modules that can be combined or used stand-alone. Modules can be replaced by own implementations to test single aspects of your own work. Currently, MATSim offers a toolbox for demand modeling, mobility-simulation, re-planning, a controller to iteratively run simulations as well as methods to analyze the output generated by the modules.

A modern desktop or laptop computer with at least 1 GB RAM and 500 MB free disk space is required to follow the steps in this guide (find more information on MATSim system requirements here). Please make sure that the following software is installed on your computer:
Furthermore, an active internet connection is required to successfully run the examples in the subsequent sections.
This version of the tutorial matches the code in the MATSim Spring 2011 release. The version number is 0.3.x, with 'x' being the number of latest official bugfix release. Make sure always to use the latest bugfix release. For reasons of simplicity, we use the string "matsim-0.3.x" when the version number is referred to.
In order to access code and data, the Eclipse IDE is used instead of the command line. Take the following steps in order install MATSim in Eclipse.
File -> New -> Java ProjectJRE.Next.matsim-0.3.x-sources.jar and click Remove.matsim-0.3.x.jar and expand it.Source attachment: (None), then click Edit....Workspace....matsim-0.3.x/matsim-0.3.x-sources.jar, then click OK.JRE System Library and expand it.Native library location: (None), and click Edit....Workspace....matsim-0.3.x/libs/jogl-1.1.1/jogl-1.1.1-OS-MACHINE/lib.OK.Finish.Congratulations! You have successfully installed MATSim for usage with Eclipse. The project can be found in the Package Explorer on the left side of the screen. You can now investigate the MATSim software project, e.g.
README.txt, CHANGELOG.txt)Referenced Libraries - matsim-0.3.x.jar). For this, make sure that the package presentation is hierarchical: Click the small triangle at the top right of the Package Explorer, then choose Package presentation - Hierarchical.Next, we take a look at an example scenario.
Each scenario contains of at least a plans and a network file. As well as the later described configuration file these two are xml-files, which you may view and edit with a text editor of your choice.

The example scenario used in this tutorial is based on the so-called "equil scenario" originally documented in Raney and Nagel (2006).
Network files describe the networks of links and nodes of a city. Links may be streets or even other transportation links. Inspect the file
examples/equil/network.xml
to get a first idea of a basic network file. You will also notice that each node has a specific location given in coordinates.
The pure xml file is of course not very comfortable to read. But you may also visualize it using OTFVis. To do so with the use of Eclipse,
Referenced Libraries - matsim-0.3.x.jar.Run As - Java Application.Matching items list below.OTFVis is selected in this list.OK.MATSim net or config file (*.xml).network.xml file mentioned above in your matsim-0.3.x folder.After a moment, you will see the network visualized. If the network is not visible or any other problem occurs, information about the problem can be found in the console output which is displayed at the bottom right of the Eclipse workspace. In this case, you may re-run the visualization by choosing Run - Run History - OTFVis.
Now you can also configure the visualizer further, e.g. by changing the colors of the links or by displaying their names. Read more about the usage options of OTFVis here and about technical issues here.
Plans are the essential counterparts of a network: They represent the population of a scenario. Have a look at the plans file for 100 agents of the equil scenario:
examples/equil/plans100.xml
Usually, you will however not create plans by writing into the actual plans files but will generate your demand by either using the API or your own code. More on demand generation and creating your own scenario is found in a separate tutorial.
A scenario may include additional input files that are referenced by other data. A configuration file collects all settings including file paths to the data files (network, population, …). The settings are separated into modules, which group related settings together.

The configuration file is read by the Controler, which will then run the simulation according to the settings outlined in the file. All configuration files referred to in this section are situated in the folder:
examples/tutorial/config/
Open the configuration file
examples/tutorial/config/example1-config.xml
in your favourite text editor. As you can see, the first modules (i.e. networks and plans) reference to the respective files describing them. The controler module describes where the output of the simulation will be written to and how many iterations will be run. In this case, only one iteration is run, as both first and last is set to 0. Finally, the config module planCalcScore lists the activity types that exist and how long they typically last.
Now, it's time to run your first simulation. For comfort, we have added a controler automatically reading this configuration. Run the controler in Eclipse:
Referenced Libraries - matsim-0.3.x.jar.Run As - Java Application.Matching items list below.MyControler1 - tutorial.config.example1mobsim is selected.OK.If everything is set up correctly, you should see the message “regular shutdown completed.” shortly after the execution of the command. If it reads “unexpected shutdown completed”, an error or exception has happened. In this case, you will find more information in earlier lines of the log.
Now, check your matsim folder for a new directory named output: In the Package Explorer, navigate to the project root symbol labeled with the project name. Right-click on it and choose Refresh. The new output folder appears, with a single folder called example1 in it. There, you will find
scorestats.txt,logfile.log, andIn our case, the ITERS folder contains our only iteration it.0. This folder contains results of the specific iteration. The most important file is 0.events.xml.gz, which lists all events the agents pass. It also contains the plans file which shows the agents' plans in the current iteration. Furthermore, iteration-specific statistics may be located in this folder.
As for now, no visual output has been produced. For generating this, check out
examples/tutorial/config/example2-config.xml.
You will notice the roughly same config as above, but there is also a module called simulation. The comments in the file will explain you the usage of them. Another prepared controler exists for this config file. Proceed as above, but this time use
MyControler2 - tutorial.config.example2vis
Note: It may be that you encounter an out of memory error (check the console output). In ths case, you will need to increase the memory Java is allowed to use. Use at least 512MB here:
Run - Run Configurations... Java Application - MyControler2.Arguments tab.VM arguments, type "-Xmx512M".Run.You will see the OTF-Visualizer that we have previously used to display a network. Press the play button and you will see the agents moving from home to work.
The results are stored in the folder output/example2. Additionally to the standard results files, there is a file called 0.googleearth.kmz in the ITERS/it.0 folder. This file can be opened with Google Earth. You may see the agents on their way somewhere in the Atlantic ocean.
If you want to run more than one iteration check out the
example-config5.xml
which runs 10 iterations. You will also notice the more advanced scoring as well as a new strategy-module. This contains some rerouting strategies with their corresponding probability. Run the corresponding controler
MyControler5 - tutorial.config.example5iterations
as described for the other controlers before. After the iterations have finished ("regular shutdown completed."), refresh the output folder again. The last example has generated ten iterations, which you may view by starting the OTFVis and selecting the appropriate mvi-File in each directory. The last iteration results in a state that is closer to a steady state than the first iteration.
Run - Run History - OTFVisOTFVis movie file (*.mvi) is selected.output/example5/ITERS/it.10/10.otfvis.mvi in your matsim-0.3.x folder and click Open. The OTFVis starts.File - Preferences menu.Usually, in each iteration a certain percentage of the agents receives a new plan, which is set by the replanning module (see next section). This is repeated several times until the last iteration (“day to day” replanning). The agents that change their plans are randomly varied each time. As each agent simulates an individual, their knowledge is private and they do not know, what the “other agents are planning”. The agents are able to fall back to earlier routes travelled and is hence able to “learn”, so the best solution is eventually found.
The setup of the replanning modules in the previous example can already be used to simulate larger scenarios. Open the config file of the previous example, examples/tutorial/config/example5-config.xml, and move to the "strategy" config module.
TimeAllocationMutator varies, as the name suggests, the time of day when the agents leave, depending on their plans.ReRoute_Dijkstra generates new shortest paths based on a time-dependent Dijkstra algorithm. For both the TimeAllocationMutator and the ReRoute_Dijkstra, refer to the initial paper by Raney and Nagel (2006).ChangeExpBeta is a selection strategy which selects an existing activity plan for the next iteration, and approximates the simulation to a logit model. The reason for this selector is elaborated in Nagel and Flötteröd (2009).Modify the following settings in the "strategy" config module:
Run the simulation again and look at some consecutive iterations in the visualizer. What effect can you observe?
Finally, have a look at
examples/tutorial/config/example5trip-config.xml.
This file has a somewhat different Scoring part which will result in iterations which are solely based on the previous trips. Run this configuration with the prepared controler named MyControler5Trips.
In the previous steps, the path to the configuration file used by each MyControler* was hard-coded. However, running your own configuration is very simple: Just pass the path to your config file as the single argument to the Controler.
example5-config.xml in the same folder. Name the copy example5-config-2000agents.xmlplans module, change the value of the parameter inputPlansFile to:
"./examples/equil/plans2000.xml.gz"controler module, change the value of the parameter outputDirectory to:"./output/example5-2000agents"controler, increase the value of the parameter lastIteration from 10 to 50. The learning procedure will have progressed substantially after 50 iterations.simulation module, set the snapshotFormat to "" (remove otfvis). The memory-consuming production of OTFVis mvi files will now not be performed during the iterative simulation.Run - Run Configurations... (or Run - Open Run Dialog...).Java Application.New launch configuration).Main class dialog, click Search....Controler - org.matsim.run from the Matching items list, and click OK.Name: field, type a descriptive name for this run, e.g. "Controler - 2000 agents".Arguments tab.Program arguments text field, paste the following text:examples/tutorial/config/example5-config-2000agents.xmlRun. Wait for the 50 iterations to finish successfully.Run - Run Configurations... (or Run - Open Run Dialog...).Java Application - OTFVis. If this item is not available, generate a new launch configuration as described above, choosing OTFVis as the main class.Arguments tab.Program arguments text field, paste the following text:-convert output/example5-2000agents/ITERS/it.50/50.events.xml.gz examples/equil/network.xml output/example5-2000agents/ITERS/it.50/50.otfvis.mvi 60-Xmx512MRun.output/example5-2000agents/ITERS/it.50/50.otfvis.mvi in order to visuallize the result of iteration 50.This step describes the basic output data MATSim produces by default for further traffic data analysis.

If you look into the root folder of your output directory, you will find a chart displaying the scores of each iteration. The scores can easily be modified in the config-File (see above), so you will be able to see the improvements of each iteration without too much effort. The data displayed is also shown in a corresponding text file. There is also a similar chart showing the travel distances travelled.
Events are very simple information information units which are generated by the mobility simulation. Open the events-file
output/*/ITERS/it.0/0.events.xml
(you may need to unzip it first) in Eclipse and look at the possible events. You may want to filter out the events of one single agent to get a better understanding of the events. You can use the events-file for further, custom analysis of the simulation.
Further there are also some charts covering the number of legs depending on the time of day.
Congratulations! You have just run your first MATSim scenarios. Depending on your interest, you might continue with one of the following options:
If you wish access to different/more recent versions of the MATSim software then just the official release, consider the two following options:
The following publications have been cited in this tutorial and are preferred entry points to reading about MATSim.
Nagel, K. and G. Flötteröd (2009) Agent-based traffic assignment: Going from trips to behavioral travelers, paper presented at the 12th International Conference on Travel Behaviour Research (IATBR), Jaipur, December 2009.
Raney, B. and K. Nagel (2006) An improved framework for large-scale multi-agent simulations of travel behavior, in P. Rietveld, B. Jourquin and K. Westin (eds.) Towards better performing European Transportation Systems, 305–347, Routledge, London.
See also a fairly comprehensive list of publications related to MATSim here.
Instructor: R. Waraich
You will learn:
The configuration file serves the users as the primary interface to configure a MATSim run. The configuration file contains different modules, some of which are mandatory, such as network, plans and controler. There exist lots of additional modules and you can browse at matsim.org to find their documentation.
In the next chapter we will learn, how to perform simple calibration in MATSim.
After learning, how to start a simple MATSim run one needs to get into the habit, to run MATSim again and again. For example the different shares of transportation modes (car, bike, public transport, etc.) need to be calibrated.
To exemply how typically parameters in MATSim are calibrated, we look at an example where we have a hypothethical 10% population sample given and we do not have the resouces to create and run a 100% scenario (e.g. the machine has not enough RAM). To do so, the network needs to be calibrated to the popluation sample size. In the network file, each link has a length and a capacity (among other characteristics). The length defines the storage capacity of the road (how many cars have space on the road during a congestion). For all links a capperiod (capacity period) is defined, which is a time duration. The flow capacity of a road (named capacity in the network file), defines how many cars can pass the road during the capacity period. E.g. if the capperiod is set to "01:00:00" and the capacity of a certain road is set to 3600, this means that 3600 cars can pass the road in one hour at maximum.
"examples/equil/network.xml"In order to match a 10% population to a network, the network needs to be scaled down, so that it maches the population. There are two parameters available in MATSim, which can be used to perform this scaling: storageCapacityFactor and flowCapacityFactor (referred to as scaling factors from hereon). In theory, when using a 10% population both these scaling factors need to be set to 0.1. But in practice, this looks different and often the storageCapacityFactor needs to be set much higher than prescribed in theory. Furthermore, it also depends on the micro-simulation being used. By default the "QueueSim" simulation is being used, and the default values for both scaling factors are set to 1.
"examples/tutorial/config/example1-config.xml". If you think, that the configuration file has been changed sense its download, you can download its original version from here."inputPlansFile" to "examples/equil/plans2000.xml.gz".
<module name="strategy"> <param name="maxAgentPlanMemorySize" value="5" /> <!-- 0 means unlimited --> <param name="ModuleProbability_1" value="0.9" /> <param name="Module_1" value="ChangeExpBeta" /> <param name="ModuleProbability_2" value="0.1" /> <param name="Module_2" value="ReRoute_Dijkstra" /> <param name="ModuleProbability_3" value="0.1" /> <param name="Module_3" value="TimeAllocationMutator" /> </module>
"lastIteration" to 10 in the configuration fileMyControler1outputDirectory" to "./output/example1_2"
<module name="simulation"> <param name="flowCapacityFactor" value="0.1" /> <param name="storageCapacityFactor" value="0.1" /> </module>
MyControler1 again. In order to observe the difference in output of the two runs after changing the scaling factors, compare the following two leg histogram files "output/example1/ITERS/it.10/10.legHistogram_all.png" and"output/example1_2/ITERS/it.10/10.legHistogram_all.png".In order to calibrate, many runs with dozens of iterations will need to be performed. In order to improve performance and as such save time, we can perform the following steps:
"output/example1/ITERS/it.xx/xx.events.xml") . To do so, add the following line in the "controler" module (within the config file):<param name="writeEventsInterval" value="0" />
"simulation" to "JDEQSim". A documentation of this micro-simulation called JDEQSim is found here.outputDirectory" to "./output/example1""lastIteration" to 50 in the configuration fileMyControler1"output/example1/scorestats.png"Now you are ready to start with the calibration excercise (see next chapter).
Before starting this excercise, the configruation file in "examples/tutorial/config/example1-config.xml" should be prepared as described in the previous chapter. The configuration file should look as in this example file.
The goal of this excercise is to find calibrated values for the "storageCapacitiyFactor" and "flowCapacityFactor" such that, after calibration the leg histogram in the 50th iteration (located at "output/example1/ITERS/it.50/50.legHistogram_all.png") looks similar to the following figure.

Hints:
"storageCapacitiyFactor" is between 0.5 and 1.0 and the "flowCapacityFactor" between 0 and 0.5."output/example1/scorestats.png"
In this excercise, you will find out the effects of changing the probabilities of the different strategies in the "strategy" module (within the configuration file located at "examples/tutorial/config/example1-config.xml"). The duration of completing the steps described in this excercise, depends mostly only on the speed of your computer (although the questions at the end need some thought).
MyControler1 (for 50 iterations)outputDirectory" to "./output/example1_4""ModuleProbability_3" to "0.001"MyControler1 (for 50 iterations)outputDirectory" to "./output/example1_5""ModuleProbability_3" to "0.1""ModuleProbability_2" to "0.001""lastIteration" to 200 in the configuration fileMyControler1 (for 200 iterations)"output/example1/scorestats.png", "output/example1_4/scorestats.png" and "output/example1_5/scorestats.png").
What do you observe? What can we learn from this?
(If you cannot use the osm data (for example because you have network data in a different format), see here.)
http://download.geofabrik.de/osm/europe/ and download the switzerland.osm.bz2 file. Unpack it using a bunzip2 utility for your platform.http://wiki.openstreetmap.org/wiki/Osmosis and download the latest stable build. Try running the command line program osmosis and have a look at the available options.osmosis --rx file=switzerland.osm --bounding-box top=47.701 left=8.346 bottom=47.146 right=9.019 completeWays=true --used-node --wx zurich.osm
osmosis --rx file=switzerland.osm --tf accept-ways highway=motorway,motorway_link,trunk,trunk_link,primary,primary_link --used-node --wx switzerland-bigroads.osm
osmosis --rx file=switzerland-bigroads.osm --rx zurich.osm --merge --wx merged-network.osm
import org.matsim.api.core.v01.Scenario;
import org.matsim.api.core.v01.network.Network;
import org.matsim.core.api.experimental.network.NetworkWriter;
import org.matsim.core.config.Config;
import org.matsim.core.network.algorithms.NetworkCleaner;
import org.matsim.core.scenario.ScenarioUtils;
import org.matsim.core.utils.geometry.CoordinateTransformation;
import org.matsim.core.utils.geometry.transformations.TransformationFactory;
import org.matsim.core.utils.io.OsmNetworkReader;
import org.matsim.core.utils.misc.ConfigUtils;
public class CreateNetwork {
public static void main(String[] args) {
String osm = "merged-network.osm";
Config config = ConfigUtils.createConfig();
Scenario sc = ScenarioUtils.createScenario(config);
Network net = sc.getNetwork();
CoordinateTransformation ct =
TransformationFactory.getCoordinateTransformation(
TransformationFactory.WGS84, TransformationFactory.WGS84_UTM33N);
OsmNetworkReader onr = new OsmNetworkReader(net,ct);
onr.parse(osm);
new NetworkCleaner().run(net);
new NetworkWriter(net).write("network.xml");
}
}
If you cannot use the osm data (for example because you have network data in a different format), see here.
This Java program gives you an example how to use the MATSim API to create a population of one sample person. Try and run the program, and inspect the generated population file.
Now you will want to change this program so that the start and end location of the plan are actually in your region of interest. In this tutorial, we are using OpenStreetMap data, so open the Geofabrik map application, choose a home location and a work location, copy the coordinates (you will probably have to use pen and paper) and enter the coordinates into the program. You should choose locations which are some larger distance apart so it has to travel a lot. It will be easier to find that way all alone in the network.
Create a config.xml file (you may use example2-config.xml from section 2 of this tutorial as a starting point), change the filenames of the network and the population file to match the files you just created, and run the Controler with this config.xml as a parameter.
You will see the simulation run. When it is done, open the 0.otfvis.mvi file from the ITERS/it.0 directory with OTFVis. You should see your agent drive!
The next step is to generate a population of agents based on available data. This always involves programming, because traffic demand data comes in many forms and there is no generic way of mapping it to a MATSim population. In this tutorial, we will try to assist you in generating MATSim plans from whatever data source you may have available.
Start simple: Write a program which creates home-work-home commuter plans. Use the OpenStreetMap application to pick the center coordinates (roughly) of some administrative units around your city of interest. Write them down in your program. Now write a function which creates a number of commuter plans, which you specify, from every suburban administrative unit into your city. Look at the result.
We also have an example program doing something like this, with two example locations. You can use it as a starting point. Edit it to enter coordinates of locations of your choice, and also enter some volumes. You will find hints in the comments.
You may want to randomly blur the home and work location as well as the start times of your agents (or they will all live and work at the exact same spot and leave the house at the same time, leading to funny traffic patterns). Try simply adding a random number to the x and y coordinates of your locations and the start times of your activities.
This example program reads a custom input file which contains census data with activity-travel diaries for the Zurich region. (You will have to download the attached file and place the data sample in the input directory). Look there if you want to create plans from census data and need to read your own input file. Of course, you will have to make heavy adaptations so it suits your particular input data, but it may be helpful for a start. Create a network for the Zurich region if you want to test and run it!
You can download the source files without line numbers from sourceforge (click on the file, then "download").
Starting from the scenario you set up in the last section, this section will show you how to compare the traffic volume produced by the simulation to traffic volumes obtained externally.
First, change your config.xml so that your simulation runs for 10 iterations. Open the mvi-file for the 10th iteration. Turn on the displaying of link ids by opening the preferences window and checking the option. Now watch the movie and pick a few links that have vehicles going through them. Make note of the link ids.
Next, use some Java code like this to produce a counts file which contains expected traffic volumes. You can simply put it below your demand generation code:
Counts counts = new Counts();
counts.setYear(2011);
counts.setName("Test");
counts.setDescription("Test");
Count count = counts.createCount(sc.createId("6526"), "mycount");
count.createVolume(7, 1000);
count.createVolume(8, 1000);
count.createVolume(9, 1000);
CountsWriter countsWriter = new CountsWriter(counts);
countsWriter.write("../examples/counts.xml");This example produces a file which contains expected traffic volumes for the link 6562, for three hours of the day, namely 6-7, 7-8 and 8-9 a.m, expecting 1000 vehicles each hour.
Note that
Now edit your config.xml again and make the following settings:
<module name="counts" > <param name="countsScaleFactor" value="1.0" /> <param name="inputCountsFile" value="../examples/counts.xml" /> <param name="outputformat" value="kml" /> </module>
Now run the simulation again! The counts module runs every 10 iterations (this cannot be changed), so look in the directory of the 10th iteration (remember, it is called ITERS/it.10). You should find a file called 10.countscompare.kmz. KMZ is the file format used by Google Earth. Open this file with Google Earth, to see the results. If your results seem to be on a different location on the earth than where you expected them, you probably didn't set the coordinate transformation correctly (see above).
Events Structure
When you look at an event file, you will notice that there are different types of events. Each event type is characterized by the agents' action:

Reading Events
In order to read events, you will need to implement certain interfaces from this package:
org.matsim.core.api.experimental.events.handler
An EventHandler is a Java class which implements one or more of these interfaces. The following example shows an EventHandler which handles LinkEnterEvents and LinkLeaveEvents. That means it can follow all vehicle movements over links:
public class MyEventHandler1 implements LinkEnterEventHandler, LinkLeaveEventHandler {
@Override
public void reset(int iteration) {
}
@Override
public void handleEvent(LinkEnterEvent event) {
}
@Override
public void handleEvent(LinkLeaveEvent event) {
}
}
The code in the handleEvent-Methods is executed every time a vehicle enters (or leaves) a link. Fill in anything you feel like doing. For a start, just have it write something to the console.
You will need a simple main routine
public static void main(String[] args) {
// The filename of the input file. Point this to the location where your
// event file is.
String inputFile = "../examples/output/ITERS/it.10/10.events.xml.gz";
// Create an EventsManager instance. This is MATSim infrastructure.
EventsManager events = new EventsUtils.createEventsManager();
// Create an instance of the custom EventHandler which you just wrote.
// Add it to the EventsManager.
MyEventHandler1 handler = new MyEventHandler1();
events.addHandler(handler);
// Connect a file reader to the EventsManager and read in the event file.
MatsimEventsReader reader = new MatsimEventsReader(events);
reader.readFile(inputFile);
System.out.println("Events file read!");
}
Now, try to create handlers which:
write the attributes of the LinkEnter- and LinkLeaveEvents to the console
calculates total time agents spend on the road and the average travel time per agent under the assumption that the size of the population will be given as a parameter.
You will find the solutions in the classes MyEventHandler1 and MyEventHandler2 which are part of the MATSim source distribution. Just open them in Eclipse. But try it yourself first!
Finally, try and write yet another EventHandler which sums up the traveled kilometers per agent. This requires a little more programming (you will have to create a Map in which you keep the current sum and the last link enter time per agent).