We have prepared some tutorials which should help you getting started with MATSim.
MATSim Meeting 2009 in Berlin
MATSim Meeting 2010 in Zürich
Instructor: K. Meister
Co-instructors: R. Waraich, C. Dobler
The tutorial participants will ...
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 2010 release. The version number is 0.1.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.1.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.1.x-sources.jar and click Remove.matsim-0.1.x.jar and expand it.Source attachment: (None), then click Edit....Workspace....matsim-0.1.x/matsim-0.1.x-sources.jar, then click OK.JRE System Library and expand it.Native library location: (None), and click Edit....Workspace....matsim-0.1.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.1.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.1.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.1.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.1.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... (Eclipse 3.5) or Run - Open Run Dialog... (Eclipse 3.3)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.1.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: M Balmer
Co-instructors: F. Ciari, M. Zilske
Lecture type: Presentation
You will learn: A short theoretical overview of what's coming in the next two days
Instructor: Michael Zilske
Co-instructors: Francesco Ciari, Christoph Dobler
Lecture type: Presentation with exercises
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
String osm = "merged-network.osm";
Scenario sc = new ScenarioImpl();
Network net = sc.getNetwork();
CoordinateTransformation ct =
TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84, TransformationFactory.WGS84_UTM35S);
OsmNetworkReader onr = new OsmNetworkReader(net,ct);
onr.parse(osm);
new NetworkWriter(net).write("network.xml");
The process of creating an initial demand (the "population" of the scenario) can be quiet challanging, as a lot of different data sources may be used, depending on what's available. The good thing about MATSim is, that you can start with a fairly simple initial demand and improve it later.
A simple description of agents is as follows:
<person id="1">
<plan>
<act type="home" x="20" y="-5" end_time="06:00:00" />
<leg mode="car" />
<act type="work" x="80" y="5" end_time="16:00:00" />
<leg mode="car" />
<act type="home" x="20" y="-5" />
</plan>
</person> Each person needs a unique identifier id and at least one plan. The plan contains acts and legs. The activities need at least the type, a coordinate-pair (x, y), and an end time (end_time). Legs between activities need a mode, usually set to "car", but do not need any route information at this stage.
NOTE: There is also an activity duration attribute. At this point (may'10), this is essentially deprecated (because the functional differentiation between "dur" and "end_time" did not work that well).
If you are coming from time-dependent OD matrices, do something like the following
<person id="1">
<plan>
<act type="dummy" x="20" y="-5" end_time="06:00:00" />
<leg mode="car" />
<act type="dummy" x="80" y="5" />
</plan>
</person> Note that there is now no return trip.
end_time does not have to be an exact value; with certain set-ups, the simulation can modify these attributes to find better values on its own.
On the other hand, if you are coming from time-dependent OD matrices, you should "smear out" the activity end times (= trip departure times) over the time period of the validity of the matrix, and then not use the "TimeAllocationMutator" later.
The simulation expects all activities to take place on links. To assign each activity a link based on its coordinates, use the tool org.matsim.run.XY2Links. As an argument, pass it a configuration file which contains the information about the network, input-plans and output-plans, e.g.:
java -cp <class-to-matsim-jar>/matsim.jar org.matsim.run.XY2Links config.xml
The tool will then read all plans from the input-file and search for each activity the nearest link from the network. The plans with this additional information are then written to the output-file. That output-file could then be used to start the simulation with org.matsim.run.Controler (see the Getting-Started Tutorial).
Attached are a very small sample network, a very simplistic plans file and a configuration file that can be used with XY2Links.
In more complicated situations, it often makes sense to program the initial demand generation in Java. See matsim.org/node/340.
Instructor: Francesco Ciari, Christoph Dobler
Co-instructor: Michael Zilske
Lecture type: Presentation with exercises
You will learn:
You should already have seen the following for a relatively "minimalistic" introduction: matsim.org/node/110 . Contains information about how to map coordinate-based activity locations to links ("XY2Links").
matsim.org/uploads/320/data_conversion_demand_modelling_gis_49fdc6ca54.pdf
Instructor: R. Waraich
Co-instructors: C. Dobler, M. Zilske
Lecture type: Tutorial
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."parallelEventHandling" into the configuration file (see below), if your machine has more than one CPUs/core available. The documentation of this module is available here. The meaning and importance of event handling will be explained later in the tutorial.<module name="parallelEventHandling"> <param name="numberOfThreads" value="1" /> </module>
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?
Instructor: A. Horni
Co-instructors: F. Ciari, D. Grether
Lecture type: Presentation with exercises
Learning Objectives:
Content:
Find this tutorial @: http://www.matsim.org/node/412

MATSim provides automated comparisons of the simulation results with traffic counts. To date average hourly volumes can be used. For the Swiss scenarios predominantly the following source is used: ASTRA traffic count data.
The comparison is automatically generated every 10th iteration. Generated output is located in the output-directory of the iteration (usually something like output/ITERS/it.10/).
(Adopted from User guide traffic counts)
Future Tasks:

Example CH:

The counts-module offers the following config-parameters:
<module name="counts"> mandatory: <param name="inputCountsFile" value="/path/to/counts.xml" /> <param name="outputformat" value="txt,html,kml" /> optional: <param name="countsScaleFactor" value="Double > 0 " <param name="distanceFilter" value="Double >= 0" /> <param name="distanceFilterCenterNode" value="String" /> <param name="outputCountsFile" value="String" /> </module>
inputCountsFile: [String]
Path to the file containing the real-world traffic counts.
outputformat: [String]
The output format specifies in which format the comparison results are written to disk. It can be any combination of txt, html and kml. Multiple formats can be specified separated by commas. txt writes simple text-tables containing the values to a file. It is most useful to create custom graphs, e.g. in Excel. html creates a directory containing several html files, allowing to browse the results interactively. kml creates a file to be displayed in Google Earth. This last option only works if the correct coordinate system is set.
countsScaleFactor: [Double > 0]; default: 1.0
If you only simulate a sample of your population, the simulated traffic volumes are likely lower than the real-world traffic counts. In order to allow useful comparison, one can specify a factor by which the simulated traffic volumes are multiplied. For example, if you simulate a 25% sample of your full population, specify a countsScaleFactor of 4.
distanceFilter: [Double] and distanceFilterCenterNode: [String]
If the traffic counts cover a larger area than the area being simulated, the traffic counts outside your area will result in a bad comparison. Instead of removing the traffic counts from the counts.xml, you can specify a filter to only include some traffic counts from the file in the comparison. To activate the filter, specify the id of a node that acts as the center of a circle. The circle has the radius specified in "distanceFilter", the unit being the same unit as the length of links (i.e. usually meters).
outputCountsFile: [String]
Take ...
playground.anhorni.kti.CountsAnalyser orplayground.dgrether.analysis.CountsAnalyser
... as an example (will be implemented in the core soon)
Produces kml, txt or html output from the linkstats file (+network file)
Trip length and duration distribution
compare with Swiss Micro Census (PUS) german
Modal split (Example.: Westumfahrung ZH, 2009)
compare with Swiss Micro Census (PUS) german
Route Switchers
Example.: Westumfahrung ZH, 2009

Spideranalysis
Example.: Westumfahrung ZH, 2009

Volumes
Example.: Westumfahrung ZH, 2009

=> A lot of interesting future work!


Building the bypass (WU) has made worse a promiment bottleneck in the region of Zurich. Try to locate it by using the OTFVis. It is best visible between ~ 7:15 and 9:00. It is not visible very clearily in our results, but ... local car drivers say it is there ;)
Hints:

a) Using Google Earth with 100.countscompare.kmz look at the count stations in the south of Switzerland (Tessin, e.g., Lugano, Mendrisio).
b) Look at the count stations in the center of Zurich (e.g., Rosengartenstrasse, Nordring etc.)
c) What is the difference? What is the problem in (a)

3. Counts Configuration & OTFVis
Configure a ZH simulation based on zurich-switzerland.xml such that counts are plotted only within a restricted area: center = Bellevue and radius = 10 km.
I.e.; inspect network by OTFVis and define distanceFilterCenterNode in the count section of the configuration file (see Section Parameters)

Instructor: M. Balmer
Co-instructors: F. Ciari, D. Grether
Lecture type: Presentation
You will learn: Putting it all together. The "Westumfahrung" of Zurich City is used as a real world case study to show, how the steps learned in the tutorial can be used for your own application.
Instructor: D. Grether
Co-instructors: M. Rieser, A. Horni
Lecture type: Presentation with exercises
Learning Objectives:
MyEventsHandling.java within the release (press Ctrl + Shift + T in eclipse and enter the class name MyEventsHandling to get to the class). Using a checkout you can find the classes in the folder src/main/java/tutorial/programming/example6EventsHandling.
As pointed out in the „Getting Started“ - Tutorial, Events are a key concept of MATSim. This tutorial will introduce you into the possibilities of data analysing using events.

In order to use this tutorial, we strongly recommend using the latest SVN checkout. Using Eclipse will ease your work. Furthermore you will need to have run a simulation in order to use the examples given here. If you don't have your own, simply run MyMainClass.java in src/tutorial/example7ControlerListener (this will run a simulation from the forthcoming Controler tutorial ). After running, you should have an output-Folder in your MATSim-directory with a total of 12 iterations. Each iteration contains an events.txt.gz file listing the events.
Before getting into the deep analyis, a look at the controler generated output is worthwile. You will find:
score statistics
leg histograms (each iteration)
Snapshots and plans (every 10th iteration)
These statistics are useful for a basic analysis.
Event Structure
If you have looked at an event file, you will have noticed a column called Event Flag which lists 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 EventHandlers from either of the following packages
org.matsim.core.api.experimental.events
org.matsim.core.api.experimental.events
or
org.matsim.core.events
org.matsim.core.events.handler
Creating an Event Handler
For the next steps, you should create (at least) two classes. One called MyEventHandling and another one implementing the actual Handlers, e.g. MyEventHandler1.
The class MyEventHandling contains the main-method and is thus executable:
public static void main(String[] args){
...
//path to events file
String inputFile = "output/ITERS/it.10/10.events.xml.gz";
//create an EventsManager object
EventsManager events = new EventsManagerImpl();
//create the reader and read the file
MatsimEventsReader reader =
new MatsimEventsReader(events);
reader.readFile(inputFile);
System.out.println("Events file read!");
...
}
For now, this is not very useful, as MyEventHandler1 (of which we created an instance “handler” and registered it for the event) is not yet written, hence we will need to that.
The handler needs to implement the interfaces and should thus look like this:
public class MyEventHandler1 implements LinkEnterEventHandler,LinkLeaveEventHandler {
//or which Handler what ever is to be implemented
public void handleEvent(LinkEnterEvent event) {
//handle something
}
public void handleEvent(LinkLeaveEvent event) {
//handle even more
}
public void reset(int iteration) {
//reset something
}
}
Now, try to create handlers which:
write the attributes of the LinkEnter- and LinkLeaveEvents to the console
Write an event handler that calculates total time agents spent on the road and the average travel time per agent under the assumption that the size of the population will be given as
NB: You will find the solutions in
src/tutorial/programming/example6EventsHandling/MyEventHandler1.java
and MyEventHandler2.java
MATSim
uses the JfreeChart library to gernerate charts (see
for additional information). The library is somewhat complex to
understand, but we have included the most useful tools in:
MATSim uses the JFreeChart library to gernerate charts (see http://www.jfree.org/jfreechart/ for additional information). The library is somewhat complex to understand, but we have included the most useful tools in:
org.matsim.core.utils.chartsA simple chart may be created like this:
public class MyChartCreator {
public static void main(String[] args) {
XYLineChart chart = new XYLineChart("Title","x-axis","y-axis");
chart.addSeries("SeriesTitle", new double[]{1.0,2.0,2.4}, new double[]{1.0,2.0,4.0});
//adds a Series to the chart
charta.saveAsPng("a-chart.png", 800, 600); //File Export
}
}
Now, try to use a chart in your EventHandler:
Try to collect the number of vehicles on link 6 per hour and write them to a chart.
You will find the solution in MyEventHandler3.
Instructor: M. Rieser
Co-instructors: D. Grether, A. Horni
Lecture type: Presentation with exercises
Learning Objectives:
Slides: see below
Beside handling events with EventHandlers in the Events Tutorial, using Controlers is yet another powerful way of analysing data in MATSim.
Controler – Basics
There are two types of Controlers in MATSim. The first one, implemented in org.matsim.run.Controler is public and rather simple, as it delegates most of the work toorg.matsim.core.controler.Controler Hence, this tutorial will focus on the latter one.
Creating a Controler
A Controler can be instanced just like any other object://Create an instance of the controler
Controler controler = new Controler("configurationFile.xml")
You may want to change some settings:
controler.setOverwriteFiles(true);
//Sets, whether Outputfiles are overwritten
controler.setCreateGraphs(false);
//Sets, whether output Graphs are created – set false, if you don't need them
controler.setWriteEventsInterval(5);
//Sets, how often events are written. Set 0 to disable it completely
Now, you can run the controler
controler.run();
With these settings, create and run a Controler using "./examples/tutorial/multipleIterations.xml".
You will find the solution in /src/tutorial/example7ControlerListener/MyMainClass.java.
For now, we can already run a simulation – now it is time to customize them. Simulation may be extended at any of the following points:

At any of those extension points, ControlerEvents and ControlerListeners are available, all of them are available in
org.matsim.core.controler.events.* or
org.matsim.core.controler.listener.*
Examples are IterationStartsEvent or IterationStartsListener.
A sample Listener class might look like this:
public class MyIterationListener1 implements IterationEndsListener {
public void notifyIterationEnds(IterationEndsEvent event) {
System.out.println("iteration " + event.getIteration() + " / " + event.getControler().getLastIteration());
//basic example - lists the Iteration that just ended.
}
}
To include the Listener into your controler, you will need to add it:
controler.addControlerListener(new MyIterationListener1());
Of course, you can also combine EventsHandler with your ControlerListener:
private MyEventHandler2 eventHandler;
//will include a eventHandler from the last tutorial
public void notifyStartup(StartupEvent event) {
this.eventHandler = new MyEventHandler2(event.getControler().getPopulation().getPersons().size());
//gets the size of the population
event.getControler().getEvents().addHandler(this.eventHandler);
//adds the Handler
}
Now, you could try to write a ControlerListener that calculates the average travel time for each iteration and writes it to a chart after the simulation has finished. You will need to implement StartupListener, IterationEndsListener, ShutdownListener for to do so could use MyEventHandler2 for calculating the average travel time. You will find the solution in MyControlerListener.java.
This section contains those tutorials that are not used at the annual tutorial. The main reasons for this are: (i) too specialized; (ii) out of focus for intended user meeting audience.
The Deterministic Event-driven Queue-based Traffic Flow Micro-Simulation (DEQSim) is a fast traffic
simulation written in C++. It can read the usual MATSim XML files for input, which allows it to be
integrated in MATSim.
This tutorial will show you how you can use DEQSim together with MATSim.
The tutorial is also included in the download of the MATSim Extension "DEQSim".
We provide nightly builds of MATSim for download. These builds are are not official releases of MATSim, but are automatically created each night after the code has passed some tests to ensure a certain minimal quality standard. The nightly builds of MATSim require additional libraries to run, which are also provided for download in a separate package, as they do not change that often.
Using a nightly build of MATSim is as simple as following these 3 steps:
MATSim_r####.jar).MATSim_libs_r####.zip).libs with several jar-files inside.Now you can run MATSim by specifying the jar-file as classpath, e.g.:
java -cp MATSim_r####.jar org.matsim.run.Controler
If the directory libs is in the same directory as the MATSim jar-file, the libraries are found automatically and must not be added to the classpath manually.
If you are already using a nightly build of MATSim, it is in most cases sufficient to just replace the nightly MATSim jar-file with a newer version, as the libraries do no change that often.
The above provides an easy way to run MATSim as a shell script. For example:
(1) Write a shell script named, say, "myControler":
#!/bin/bash -xev java -Xmx2000m -cp <path-to-matsim-jar>/MATSim_rXXXX.jar org.matsim.run.Controler $*
(2) Start this shell script from whereever you are as
<path-to-script>/myControler <configfile>
Clearly, if you know how to set your PATH variable, you can use that mechanism.
(3) The filename root (for input/output files) is where you are, that is, networks/plans/etc. can be referenced, say, as
<param name="inputNetworkFile" value="./network.xml" />
or
<param name="inputPlansFile" value="./plans2000.xml" />
This makes working with MATSim considerably easier in many situations.
A similar approach for using OTFVis is described there.
(People on win systems should be able to do something similar using *.bat files.) The Windows way of doing it can found at the OTFVis userguide.
This tutorial describes the EvacuationQueueSimulation. Because the evacuation package is not part of the current release you have to checkout MATSim from SVN.
Contains old material, left here for reference.
This tutorial will make you familiar with MATSim. You will learn
Finally, the tutorial will give an introduction at the code so you will be able to extend the previously mentioned examples to create further sophisticated simulations.
This tutorial is also included in the MATSim download.
This version of the tutorial (supposedly) matches the code in the latest release.
If you plan to use later versions, you will need to keep the following Path-changes in mind:
-cp in commands) is not MATSim.jar, but consists of the directory that contains the compiled classes (usually classes or bin) as well as of all depending jar-files Also see here for more modern ways to obtain and install MATSim. The tutorials have not yet been adapted.
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 controler to iteratively run simulations as well as methods to analyze the output generated by the modules.
MATSim is written in Java 1.6. You will need at least the Java Runtime Environment (JRE) 6 or newer to run the examples and the Java Development Kit (JDK) 6 or newer to compile your own code that uses MATSim functionality.
A scenario consists of at least a network and a population with plans. The network is a representation of a physical road network, on which traffic happens. The population is a collection of agents, in which each agent has a plan that describes activities and routes through the network.
Additionally, a scenario can include additional input files (e.g. a world or a description of facilities) 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 following examples all use the very simple equil scenario, consisting of the two files network.xml and plans100.xml. It is located in examples/equil. Looking at the network in the included visualizer may be the easiest way to get an impression of the network. Additionally, you can look at the textual description of the network in the XML file. Use the following command to start the visualizer:
(This and the following has been tested with MATSim_r4776.jar, but should work with any (successful) nightly build.)
java -cp MATSim_rXXXXX.jar org.matsim.utils.vis.netvis.NetVis
After the visualizer started, you will be prompted to choose a file. Set the File Format to “All Files” and select the file network.xml. You can zoom in the visualizer either by pressing the “+” button in the toolbar or by spawning a rectangle when dragging the mouse pointer across the screen with the mouse button pressed. To zoom out, use the “–“ button in the toolbar. You can scroll the image either by using the scroll bars (on the left and on the bottom side of the window) or by holding the middle mouse button and moving the mouse. Also check out the other settings available in the toolbar.
In this example, 100 agents will start on link 1 and first travel to link 20 by crossing the nodes 2, 7 and 12. A bit later, the agents will depart at link 20 and travel back to link 1 by crossing the nodes 13, 14, 15 and 1. Have a look at plans100.xml to get an impression on how the agents and their plans are described.
To run the simulation, use the following command:
java -cp MATSim_rXXXXX.jar org.matsim.run.Controler examples/tutorial/singleIteration.xml
If everything works as expected, you should see several lines of status output. If you look through this log, you will find messages about network and plans being read, the iteration being run, scoring information and shutdown messages. Please ensure at the end of the log that the message “shutdown completed” does not include the word “unexpected”. 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.
Start again the Visualizer, but this time select the file output/ITERS/it.0/SnapshotCONFIG.vis. You should now again see the network, but the toolbar has additional buttons that let you control the displayed time of day. Change the time to 06:00 and increase the linewidth, until the links are no longer just thin lines, but actually are white rectangles with black borders. If you have checked “Agents” in the toolbar, you should now also see some blue dots representing the single agents.
Click “Play” to watch the agents move through the network, or increment the time in single steps using the buttons in the toolbar.
Events are very simple information information units which are generated by the mobility simulation. Open the events-file output/ITERS/it.0/0.events.txt in a text editor 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.
Open the configuration file configs/singleIteration.xml in a text editor and look at the various settings (You may want to ignore the settings in module planCalcScore for now). Try to change some settings in the module simulation (e.g. setting an endTime of 07:00 or changing the snapshotperiod) and run the simulation again. You may also want to visualize the output again to see if the simulation really did what you intended to do it.
NB: The simulation will not overwrite any files in the specified output-directory. It will not even start if the output-directory is not empty. Make sure that the output-directory is either completely empty or is completely missing (though the direct parent of the specified output-directory must exist). If the directory is missing, the simulation will create the directory for you.
If you have Google Earth™ installed on your machine, you may want to change the snapshotFormat to “googleearth”. If you re-run the simulation, you will find the file 0.googlearth.kmz in output/ITERS/it.0/, which can be opened in Google Earth.
Run the following command:
java -cp MATSim_rXXXXX.jar org.matsim.run.Controler examples/tutorial/multipleIterations.xml
This will run 10 full iterations. In each iteration, 10% of the agents will try to find a faster path to travel from link 1 to link 20. Look at the some of the iterations in the visualizer and try to understand what’s going on. Then look at the configuration file and compare it to the singleIteration.xml-file.
Change the number of iterations and run it again. If the number of iterations was chosen high enough, all alternative routes should have about the same amount of traffic / congestion at peak time.
Change the ModuleProbability_2 in the multipleIterations.xml-file to a higher value, e.g. 0.9, and change ModuleProbability_1 to a lower value, e.g. 0.1. Run the simulation again and look at some consecutive iterations in the visual¬izer. What effect can you observe?
You can also change the strategy being used: Replace the value of Module_2 with TimeAllocationMutator. Run the simulation again and have a look at the results. What does the TimeAllocationMutator do?
You can also combine the ReRoute- and the TimeAllocationMutator-strategy: Create two additional parameters in the module strategy with the names ModuleProbability_3 and Module_3 and assign this strategy the TimeAllocationMutator, while Module_2 remains with ReRoute. Run the simulation again and have a look at the results.
With such a setup (BestScore, ReRoute, TimeAllocationMutator), you could also simulate larger scenarios.
What if you want additional re-planning strategies, e.g. location choice? You can implement such modules on your own and use them together with MATSim. You have two possibilities for creating your own re-planning module:
We will only look at the second possibility here. If you are interested in creating your module directly in MATSim, please have a look at the chapter “Creating a Custom Controler” to get an idea how and where you can include your own module.
Your external re-planning module must be an executable. MATSim will call your executable with the path of a configuration file as its only argument. Your executable thus must be able to parse MATSim configuration files in order to be used with MATSim. In the configuration file, the path to a plans file is set (module scenario, parameter inputPlansFilename) that contains the plans that your module should read and modify. A second parameter workingPlansFilename contains the path to a file where you must write the modified plans to. Additionally, workingEventsTxtFilename and networkFilename contains the paths to the events and network file which may be of use to your module.
To instruct MATSim to use your module for re-planning, you can add an entry to the configuration file. Have a look at the module strategy in examples/tutorial/externalReplanning.xml to see how MATSim can use external modules.
We provide for testing reasons a very simple external re-planning executable. The executable is a simple jar-file containing a single Java class. The example code just takes the given plans as input and writes them out unmodified to the specified output location. The source code for the example is available within the jar-file.
Run the provided example with the following command:
java -cp MATSim_r4776.jar org.matsim.run.Controler examples/tutorial/externalReplanning.xml
In the log, you should see entries that the external executable was called. Additionally, any output of the external executable is written to its own log file in the corresponding iteration-directory (output/ITERS/it.*/)
What if you already have your own mobility simulation, but are missing the agent optimization / re-planning part? Well, you can use your own mobility simulation together with MATSim as long as you are able to read in our plans and network and generate events.
The external mobility simulation will be called with a configuration file as its only argument. In the con¬figuration file, you find parameters describing the location of the network file, the location of the plans file, and the location of the events file. Your mobility simulation should read network and plans and generate events.
We provide for testing reasons a very simple example of an external mobility simulation that just out¬puts a few hard-coded events. You can run the example with:
java -cp MATSim_r4776.jar org.matsim.run.Controler examples/tutorial/externalMobsim.xml
Have a look at the configuration file to understand how the run is configured to use the external mobsim.
If you intend to write your own mobility simulation, please read the documentation about events in the Developer’s Guide (http://www.matsim.org/docs/devguide). The events are a very important aspect in MATSim as they provide feedback from the mobility simulation to the re-planning parts of MATSim. Without (or with wrong) feedback from the mobility simulation, no useful re-planning is possible.
For simple scenarios, the configuration file offers enough flexibility to specify different simulation set¬ups. But as soon as you want to run more complex scenarios or want to better integrate your own code into MATSim, you will have to get known the important classes of MATSim so you can use them in your code, and better inject your code into MATSim. In the following sections, you will learn how to implement your own controler, which you will be able to extend as you like it. While creating your own controler, you will learn enough about MATSim classes and the “philosophy” behind MATSIm that you should be able to understand most of our code.
In a first step, we will just load some the plans and network and run them once through the mobility simulation. Start by creating a new class MyControler that contains a static main method.
At the moment, we will hard code required filenames into the code so it is easier to understand now, but switch later to using configuration files. Define some final String variables for both the network and the plans filename:
final String netFilename = "./examples/equil/network.xml";
final String plansFilename = "./examples/equil/plans100.xml";
The Scenario class contains all the important data containers that MATSim uses, like Network and Population. MATSim provides both data structures and corresponding readers and writers. We will first read the network with a specialized reader into the data structure provided by a Scenario:
Scenario scenario = new ScenarioImpl();
new MatsimNetworkReader(scenario.getNetwork()).readFile(netFilename);
For the population, the code looks similar. Note that the population reader uses the complete scenario object. This allows the reader to e.g. create references to links in the network:
new MatsimPopulationReader(scenario).readFile(plansFilename);
The mobility simulation will create events, for which we have to provide a data structure as well.
Events events = new Events();
Events cannot be stored within this data structure because of the huge amount of events a large-scale simulation is likely to generate. Instead, the events are processed on-the-fly by so-called events han¬dlers. We will add such a handler that just writes all the events to a file:
EventWriterTXT eventWriter = new EventWriterTXT("./output/events.txt");
events.addHandler(eventWriter);
Finally, we can instantiate a mobility simulation and run it. In this example, we will use the Queue-Simulation:
QueueSimulation sim = new QueueSimulation(scenario, events); sim.run();
After the simulation was run, we have to close the event writer to ensure all data is flushed to disk and that the file is properly closed:
eventWriter.closeFile();
You should now be able to compile and run this example. You can also find the complete code for this example in src/MyControler1.java. You can compile the code with:
javac -cp MATSim_r4763.jar:src src/MyControler1.java(On Windows, replace : with ;)
and can run it with:
java -cp MATSim_r4763.jar:src MyControler1(On Windows, replace : with ;)
Make sure the directory output exists; otherwise the events cannot be written.
If you run the example above, all you can see is some information output on the console and the written events. To make it more interesting, we add now output for the visualizer. Before running the mobility simulation (sim.run();), open a writer for the visualizer:
sim.openNetStateWriter("./output/simout", netFilename, 10);
This command will advise the QueueSimulation to write the network state every 10 seconds to a file beginning with “simout”.
We can start the visualizer automatically after the simulation finished with:
String[] visargs = {"./output/simout"};
NetVis.main(visargs);
When you run this example (you can find the complete code for it in src/MyControler2.java), the visualizer should open automatically after the simulation finished.
Many aspects of MATSim can be configured. The actual configuration is stored in a config object. To create such an object,
use:Config config = Gbl.createConfig(null);
This configuration can then be used when creating a new scenario:
Scenario scenario = new ScenarioImpl(config);
We can set the start and end time of the simulation by adjusting the configuration settings:
config.simulation().setStartTime(Time.parseTime("05:55:00"));
config.simulation().setEndTime(Time.parseTime("08:00:00"));
Add these lines before the QueueSimulation is instantiated to have an effect on the simulation.
Instead of setting all configuration settings manually in the code, we can also use a configuration file. To read a configuration file, replace the call to Gbl.createConfig(null); with:
Config config = Gbl.createConfig(new String[] {"examples/tutorial/myConfig.xml"});
Now you can change settings like the start or end time of the simulation in the file configs/myConfig.xml. You find the example code in src/MyControler3.java.
For each plan, a score can be calculated that reflects how well the plan performed during the simula¬tion. If the agent traveled a long time, maybe was even stuck in a traffic jam, the score will be slower than when the agent could travel with free flow speed and had more time to perform activities.
Add the following lines to your code before the simulation is run:
CharyparNagelScoringFunctionFactory factory = new CharyparNagelScoringFunctionFactory(config.charyparNagelScoring());
EventsToScore scoring = new EventsToScore(scenario.getPopulation(), factory);
events.addHandler(scoring);
and the following line after the simulation is run:
scoring.finish();
EventsToScore collects events and uses them to calculate how long the agent was traveling and how long the agent was performing activities. The scoring function calculates the actual scores for traveling or performing an activity. We provide a default scoring function, CharyparNagelScoringFunction, to calculate the effective scores. This two-tier approach makes it possible to only replace the calculation of the score with a more specialized function without having to re-implement all the event-handling functionality. Because the scoring object cannot know when the last event for an agent is handled and thus when the final score for an agent can be calculated, a call to scoring.finish() is necessary. In this call, the final scores for all agents are calculated and assigned to the executed plans.
To calculate the scores, the scorer needs additional settings, which can be done in the configuration file. Make sure that your code loads the configuration file configs/myConfigScoring.xml (instead of examples/tutorial/myConfig.xml).
You can calculate the average score of all plans with:
PlanAverageScore average = new PlanAverageScore();
average.run(scenario.getPopulation());
System.out.println("The average score is " + average.getAverage());
You find the complete example in src/MyControler4.java.
If you want to run multiple iterations, you will need to encapsulate the call to the QueueSimulation in a loop:
for (int iteration = 0; iteration <= 10; iteration++) {
QueueSimulation sim = new QueueSimulation(scenario, events);
sim.openNetStateWriter("./output/simout", netFilename, 10);
sim.run();
}
But this is not yet very interesting, as in every iteration the exact same plans are executed. We need to define some re-planning that modifies the plans between runs of the mobility simulation.
Re-planning is a central concept in MATSim, as it is in all agent-based simulation. Without re-planning (sometimes also called agent-learning) the agents would perform the same plans in every iteration. Re-planning is done by applying so-called strategies to the plans. The javadoc for the package org.matsim.demandmodeling.replanning is a good starting point to get accustomed to the terms used to describe re-planning. A strategy can consist of zero or more strategy modules that modify the plans. A strategy manager coordinates the re-planning process. Start by creating a new StrategyManager and adding two strategies to it:
StrategyManager strategyManager = new StrategyManager();
PlanStrategy strategy1 = new PlanStrategy(new BestPlanSelector());
PlanStrategy strategy2 = new PlanStrategy(new RandomPlanSelector());
strategyManager.addStrategy(strategy1, 0.9);
strategyManager.addStrategy(strategy2, 0.1);
As an agent can have more than one plan, we have to tell the strategy which plan should be modified. The first strategy will select the plan with the best score from the agent, while the second strategy will select a random plan from the agent. When adding the strategy to the strategyManager, a weight has to be specified that defines how likely an agent will be modified with the added strategy.
Now we can add a strategy module to one of the strategies:
TravelTimeCalculatorArray ttimeCalc = new TravelTimeCalculator(scenario.getNetwork());
TravelTimeDistanceCostCalculator costCalc = new TravelTimeDistanceCostCalculator(ttimeCalc,config.charyparNagelScoring());
strategy2.addStrategyModule(new ReRouteDijkstra(scenario.getNetwork(), costCalc, ttimeCalc));
events.addHandler(ttimeCalc);
The actual strategy module added is the ReRoute-module. This module calculates the fastest route through the network from one location to another. Because the travel time on the network can vary depending on how many other agents are on the road (maybe causing traffic jams), the ReRoute-module needs some way to figure out the actual travel time on a link at a specified time. That’s what the TravelTimeCalculator is for: It analyzes the events from the mobility simulation and calculates the actual travel time on the links. This is why it has to be added to the events as a handler. The ReRoute-module will then query the TravelTimeCalculator when it has to find the fastest route. Additionally, the routing process needs link costs to find the cheapest route. The TravelTimeDistanceCostCalculator calculates link costs based on the actual travel times and the distance.
The first strategy remains without an actual StrategyModule. It will just select the plan with the best score of an agent for the next execution of the mobility simulation.
In the iteration loop, we can now call the strategyManager to re-plan the agents after the mobility simulation ran and the score is updated:
strategyManager.run(scenario.getPopulation());
If you run this example (you can find it in src/tutorial/MyControler5.java), you should see a similar output than in one of the previous, config-file only, examples.
Congratulations, you have just written your first useful MATSim controler. You can now start to extend it, add your own re-planning modules or implement your own mobility simulation. A good starting point may be to improve your current controler by eliminating some of the flaws. As an example, currently the events of each iteration overwrite the previous iteration’s events. You may want to create a new eventWriter for every iteration. In that case, do not forget to remove the old eventWriter with events.removeHandler(eventWriter). Or you may just re-init the eventWriter with a new filename: eventWriter.init(newFilename).
Another possibility is to move some hard coded settings to the configuration file and using config.getParam(moduleName, paramName) to access the values. The number of iterations may be a good example of a value that could be specified in the configuration file.
You can find additional documentation on our website in the developer’s guide at www.matsim.org.
If you plan to set up your own scenario, you need a network and a description of a population. Have a look at the provided example files to get a better understanding of the file formats. The creation of the population can be based on a variety of data (census, commuter matrices, …), whatever is available. The page “Building a new Scenario” (http://matsim.org/docs/new-scenario) gives further information about that topic.
If you want to customize your analysis, reading the Event and Controler Programming tutorials is highly recommended.
Have fun with MATSim! We would be happy to hear from you what for you are using MATSim.
This tutorial will make you familiar with MATSim. You will learn
how to run and simulate a simple scenario,
to understand the configuration settings so you can change them correspondingly for your own scenarios,
how to interpret the output of the simulations
Finally, the tutorial will give an introduction at the code so you will be able to extend the previously mentioned examples to create more sophisticated simulations.
This version of the tutorial matches the code in the Matsim Spring 2010 release 0.1.0. You can download the release following the instructions in the download section of matsim.org. After the download is completed follow the instructions that you can find in the README.txt within the .zip file.
If you instead plan to use the latest code from the subversion repository, you will need to keep the following path-change in mind :
The classpath (-cp in commands) is not MATSim.jar, but consists of the directory that contains the compiled classes (usually classes or bin) as well as of all the jar-files in the directory libs and libs/geotools . This results in a huge number of jars to be added to the classpath and may not work as expected (jar hell problem). We strongly recommend to go this way only as expert and to build the project with maven.
In most cases, however, you will not need to check out the repository but can just stick to either the current release or the nightly build. See the last part of this tutorial for more information about including either of them into Eclipse
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.

MATSim is written in Java 1.6. You will need at least the Java Runtime Environment (JRE) 6 or newer to run the examples and the Java Development Kit (JDK) 6 or newer to compile your own code that uses MATSim functionality.
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, open a console / command prompt, navigate to your MATSim directory and paste the following:
java -D java.library.path=libs/jogl-1.1.1/jogl-1.1.1-linux-i586/lib/ -cp matsim-0.1.0-SNAPSHOT.jar org.matsim.run.OTFVis
To run OTFVis properly, you will need to configure the correct path to your native jogl-library. More on this can be found in the Using OTFVis section.
If everything works out, you will now be able to select a network file (you may need to select „MATSim network or config file“ from the dropdown menu first). After a moment, you will see the network visualized. Now you can also configure the visualizer further, e.g. by changing the colors of the links or by displaying their names.
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.
As outlined in the previous step, the scenario is described at least by a network and a population with plans.
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, so all you have to do is to run:
java -cp MATSim.jar tutorial.config.example1mobsim.MyControler1
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. 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.
java -cp MATSim.jar tutorial.config.example2vis.MyControler2
will run this one for you.
Note: If you encounter an out of memory error, you will need to increase the memory Java is allowed to use. Use at least 512MB here. Modify the above command by adding the corresponding Java VM argument:
java -cp MATSim.jar -Xmx512M tutorial.config.example2vis.MyControler2
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.
Also, 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.
Again, run the controler by:
java -cp MATSim.jar tutorial.config.example5iterations.MyControler5
After a while, check out your 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.
Usually, in each iteration a certain percentage of the agents receives a new plan, which is set by the replanning module (see next chapter). 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 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 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.
java -cp MATSim.jar tutorial.config.example5iterations.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:
java -cp MATSim.jar org.matsim.run.Controler <config-File>
For example, simulate 2000 agents as in the original equil scenario by Raney and Nagel (2006) instead of only 100 agents by following these steps:
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.java -cp MATSim.jar -Xmx512M org.matsim.run.Controler examples/tutorial/config/example5-config-2000agents.xmljava -cp MATSim.jar -Xmx512M org.matsim.run.OTFVis -convert output/example5-2000agents/ITERS/it.50/50.events.xml.gz examples/equil/network.xml output/example5-2000agents/ITERS/it.50/50.otfvis.mvi 60output/example5-2000agents/ITERS/it.50/50.otfvis.mvi.Of course, you could also automate this process, allowing you to run them on double-click. Depending on your operating system, you might want to proceed as described here (scripting the Controler on Mac OS or Linux) or here (scripting OTFVis, Windows example).
Configuration-Files will allow you a relatively easy start with MATSim. However, for more advanced usage you will most likely end up programming customized tools. Also, you may want to make yourself familiar with the MATSim API.
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 a text editor 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 scenario. Now you could continue extending your configurations and run your own scenarios. If you plan to do that, you need a network and a description of a population. Have a look at the provided example files to get a better understanding of the file formats. The creation of the population can be based on a variety of data (census, commuter matrices, …), whatever is available. The page “Building a new Scenario” gives further information about that topic.
If you want to customize your analysis, reading the Event and Controler Programming tutorials is highly recommended.
If you plan to use the nightly build rather than the release, you are highly recommended to read this page.
If you plan to program your own extensions for MATSim it will be useful to include the current MATSim into your projects. Ithis is really simple. All you need to do is open Eclipse and create your own Java-Project. Open the project properties by right-clicking the Project folder and select Java Build Path tab. Click „Add external JARs...“ and select the MATSim.jar from your release or nightly build folder. Under „JRE System Library“, set the Native library location and change it to your current jogl-library (as defined above).

You may now include any MATSim code you might need.
N.B. If you want to modify the MATSim code for yourself, you will probably prefer to acces MATSim through Maven and SVN.
For most up-to-date informations on MATSim, you should check out our mailing lists.
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.