We have prepared some tutorials which should help you getting started with MATSim.
Quickstart >>moreThis is the fastest way to get a working MATSim simulation, based on example input data provided by the MATSim repository. |
![]() |
Learning MATSim in 8 Lessons >>moreUntil April 2011 the tutorial, found here, was used for the annual MATSim tutorial. In mid of 2011, the new tutorial "Learning MATSim in 8 Lessons" was created. If you are head of a research lab, planning to use MATSim, please feel free to join us at the annual tutorial and user meeting or contact senozon AG or Prof. Dr. Kay W. Axhausen (ETH Zürich) for a MATSim tutorial in your lab. If you are a lecturer, please have a look at "Teachers Stuff for the MATSim Tutorial" as well.
|
![]() |
Extensions to "Learning MATSim in 8 Lessons" >>moreIn this section you will find non-standalone modules covering user-defined attributes. Prerequisite is the successful finishing of "Learning MATSim in 8 Lessons". |
![]() |
GIS-based Evacuation Simulation Tutorial >>more
|
![]() |
Simulation of Public Transport >>more |
Using Nightly Builds of MATSim >>more |
Using DEQSim with MATSim >>moreThis tutorial is deprected since DEQSim is rewritten in Java. The new version is called JDEQSim. See also here. |
(0) Download the release and unzip it.
(1) Go the the directory where you find matsim-0.2.0.jar .
(2) Then type
java -Xmx2000m -cp matsim-0.2.0.jar org.matsim.run.Controler examples/tutorial/singleIteration.xml
This should produce a new output directory. Meaning of the parameters:
-Xmx2000m : Increases the Java heap space to 2000MB of memory. If you have less memory, try smaller values, but the Java default is too small.-cp matsim-0.2.0.jar : The Java-typical jar file.org.matsim.run.Controler : The class where the main method for running "iterations" resides. examples/tutorial/singleIteration.xml : The xml file that contains all of the configuration of the run. The file can be edited.org.matsim.run.Controler" line again, you first need to erase some contents of the output directory.(3) Next type
java -Xmx2000m -cp matsim-0.2.0.jar org.matsim.run.OTFVis -swing output/singleIteration/ITERS/it.0/0.otfvis.mvi
Meaning of the parameters:
org.matsim.run.otfvis : The class where the main class for the visualization resides.-swing : Use the so-called "Swing" mode of the visualizer, which is slower but does not need an additional library (see here).output/singleIteration/ITERS/it.0/0.otfvis.mvi : The mvi ("movie") file that contains information which allows to generate movies.This should produce a visualizer window that looks as follows:

(4) The logfile, with the above example in output/singleIteration/logfile.log , contains, between a lot of other information, also a dump of a the full matsim configuration. If there are interesting parameters, you could try to copy then into your own config file, modify them, and re-run.
In my (kn's) view, one can actually get quite far in this way, i.e. by just editing the config file. The main problem is how to obtain the network and in particular the so-called initial demand for your own scenario. If you can't get that from somewhere else, it is probably better to go through the "Learning MATSim in 8 Lessons" tutorial.
1. Introduction >>more[30 minutes] Lecturers: ... During this lesson, you will be given a general overview of MATSim. The basic principles of MATSim will be highlighted and you will for example know why it is called a co-evolutionary model. Furthermore, the practical experiences gathered in a couple of large-scale projects will be reported to you. The general context of microsimulations as a sampling tool is briefly introduced such that you know how to apply these methods |
|
2. Installation >>more[60 minutes] Lecturers: ... In this lesson, we will install all the components necessary to run MATSim and to develop your own code. These are the Java SE Development Kit, Eclipse as the software development environment and of course MATSim. |
![]() |
3. Getting Started: Running the Simulation For the First Time >>more[150 minutes] Lecturers: ... In this lesson you will run MATSim for the first time. You will also have a first look into the configuration file, a key part when using MATSim. The complete scenario is handed out to you. However, during the next lessons we will reconstruct it such that you understand its basic components and such that you are able to build a scenario for your study region. |
![]() |
4. Generating the Input >>more[300 minutes] Lecturers: ... |
|
|
If you like to daydream, do not do it in this lesson! This lessons is about one of the crucial steps in setting up any MATSim scenario: the generation of the input data. These data is derived from various sources. Basically, any data that you can get for your study region! In a short presentation we will make you familiar with the input data for Switzerland. "But, I am not simulating Switzerland!" you may say. No worries! The procedures are always similar. Finally, in this lesson you will generate the input given the source data. |
|
5. Looking at the Output >>more[120 minutes] Lecturers: ... |
|
|
Events are the essence of MATSim. Hence, many online analyses and also post-precessing analyses are based on events. You will get in touch with events in this lesson. This forms the basis for Lesson 7, where you will develop your own events handler. In the second part of this lesson, the two most useful analyses tools of MATSim are presented. These are on the one hand a powerful visualizer tool developed and distributed by senozon AG. On the other hand the count data analyzer will be introduced. |
![]() |
6. Configuring the Scenario >>more[90 minutes] Lecturers: ... In this lesson, we will look closer at the configuration file. You will also get a rough idea of the MATSim scoring and the replanning modules of MATSim.
|
![]() |
7. Extending Your Controler >>more[120 minutes] Lecturers: ... If you want to add analyses that are be executed online (i.e., in the course of the iterations) you can add our own controler listeners. In this lesson you will further develop your own controler and add your own events handler to it.
|
![]() |
8. Bringing It All Together: Policy Study >>more[120 minutes] Lecturers: ... In this lesson we will bring all the components together and do a policy study using our scenario created.
|
![]() |
Links:.....................................................................
The powerpoint file for this lesson can be downloaded here (25 MB).
Follow the links to, first, install necessary software on your machine and, second, learn some very basic concepts about Java programming.
But first, let us organize our folder structure such that we will find the various downloads easier again:
During the Lessons, more folder structures will be defined. Please follow the recommended structure. It will make it easier for you and you will not get lost in the "folder-jungle".
MATSim is written in Java. To run java you need a JRE and to develop Java code you must install a JDK. An installer containing both can be downloaded for example at: download the Java Development Kit (JDK) from Oracle
In case you are not familiar with Java or other object oriented programming languages, we have put together some basics that might help you to get through Java parts of this tutorial here.
Note: You can check if Java is already installed on your machine by opening the command Prompt (Start --> Accessoires --> Command Prompt) and typing in java -version.
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03, mixed mode)
If you see something like the above, you already have Java installed on your machine.
Most of the core MATSim developers use Ecplise as a software development environment. This tutorial is thus based on Ecplise although other environments could be used. Download the newest "Eclipse IDE for Java De Classic 3.6.2 version at: download the software development environment Eclipse
In order to use eclipse you simply unpack the downloaded eclipse.zip file in a folder of your choice and start the programm by double clicking eclipse.exe.
We will work with Ecplise. Basically there are two ways of getting MATSim working in eclipse.
For committers (developers with their own playground in MATSim): You can find here a description for downloading the latest version of the source code using Subversion (svn) and Maven.
For non-committers (or nor-yet-committers): You can either download a jar file as an official release or as a nightly build. Just follow the procedure below.
For this tutorial we use 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, in the following 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 to install MATSim in Eclipse.
File -> New -> Java ProjectUse default location" checkboxLocation", choose the unzipped matsim-0.3.x folder.JRE.Next.Libraries tab.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.OK to confirm the "Source Attachment Configuration" DialogFinish.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.When starting to work with a new dataset that contains geographical data (e.g. coordinates), having a look at the data with a Geographic Information System (GIS) tool is often useful. In a later lesson, we will visualize traffic count stations and assign them to links in the network.
QGis is an Open Source GIS licensed under GNU General Public License. It runs on Windows, Linux as well as Mac OS.
Homepage: http://www.qgis.org/en.html
Download: http://www.qgis.org/wiki/Download
Please download and install the newest standalone version available for your OS. During the installation you can additionally select some sample dataset to be installed. We will not use them during our course, but if you want to start working this GIS tool, it might be a good idea to have some sample data to work with.
If you want to change the language settings oif your QGIS version, go to the menue Settings, click on Options... scroll down to Locale and tick the Override system locale checkbox. Then you can choose your language in the drop-down menu on the right.
Some of MATSim's output data is given in the KML data format which can be visualized using Google Earth. You can download and install Google Earth from here. Uncheck the checkboxes concerning the use of Chrome if you don't want to install or make it you standard browser.
In order to install Google Earth you simply have to double click downloaded .exe file and follow the installation assistant. (Beware that an internet connection is required for installing and running Google Earth.
During this tutorial, you have to work quite often with text files, especially with xml files. Therefore, we recommend to use either the editor which is included in Eclipse or an external editor that supports syntax highlighting.
Some free examples are:
Since we are using several different compression formats (.zip, .gz, .bz2, etc.) you need a program that is able handle those formats. A convienient tool under windows is for example 7-Zip.
If you do not have a similar tool installed, download 7-Zip from the link above and install it using the installation wizard by double clicking on the .exe or .msi file recommended for your Windows version.
senozon, a private company in Switzerland working on and with MATSim, is developing a visualizer for MATSim. For this tutorial, we can use a feature-limited free version of the visualizer. You can download it from here. Note that you also have to generate a license-file on the same page to use the visualizer. The license-file will allow you to use the visualizer for up to 6 months.
After you downloaded the visualizer, unzip the downloaded file and start the application. On the first start, it will ask you for the license file, that you should have received by email.
If you want to test the visualizer at this point, you can use the sample data provided on the senozon download page and follow the instructions given here.
For those users that have not yet worked with Java or other object oriented programming languages, here are some tipps and explanations that might be usefull when working through the tutorial.
In order to run a Java program you need a main method. The main method alway looks like this:
public static void main(String[] args) {
}The class the main method is located in is sometimes referred to as main class but can have an abritrary name. When you start a Java program you always do this by specifying the main class. In addition, some programs need input parameters. These are called program arguments and called through the String[] args parameter of the main method.
Software like MATSim, that contains a lot of classes, is usually organized in packages. These packages do not only give a certain structure to the code but also impact the way you can reference other classes. Moreover, there can be several classes with the same name in different packages.
Thus, If you want to reference another class in your program it is not only important that you get the class name right, but also the path to the class including the entire package structure.
Comments in a Java class contain text or code that is not executed when you run your program. On the one hand, they are used to add some explanation to your code. On the other hand, the can be used to temporarily exclude certain parts of the code from the execution.
There are two types of comments in Java: // an /* */ :
// this line is not excuted
/* This block is not executed */
You will hear in more detail about the input components in Lesson 4. Thus, only a brief overview is given here. Often these files are handled in MATSim in the compressed format gzip with the extension ".gz".
Network (network.xml)
The network file gives information about the transport infrastructure. A MATSim network contains links and nodes each with its specific attributes such as the node coordinates or the link capacity.
Plans / Population (plans.xml)
Plans represent the population and the demand of a scenario. Usually, you will not create plans by writing into the actual plans files but will generate your demand by either using the API or your own code. You will hear more on population demand generation in Lesson 4.
Configuration file (config.xml)
The controler needs one argument and that is the configuration file. As long as you do not write code, the configuration file is your way to adapt the behavior of MATSim.
Additional input:
During this tutorial you will use facilities (facilities.xml.gz) and count data (counts.xml). Facilities are an optional part of MATSim. They can roughly be interpreted as buildings. Count data is one of the most important sources for validation as obviously they are associated to a small measurement error, in contrary to e.g., survey data.
Now it is time to run the simulation. There are some example scenarios which can be started without modifiying anything in MATSim. You might want to look at them later. But we are continuing with setting up our own java project already here.
Create your own java project:
File -> New -> Java ProjectmyProjectNextJava Settings click the tab LibrariesAdd JARs ...matsim-0.3.x foldermatsim-0.3.x.jarOK twiceFinishCreate your own controler:
New -> FolderFolder name and enter inputoutput foldersrc folder in myProject and click New -> PackagetutorialFinishNew -> ClassMyFirstControlerWhich method stubs would you like to create? select public static void main(String[] args)Finishpublic static void main(String[] args) {String configFile = args[0] ; Config config = ConfigUtils.loadConfig(configFile); Controler controler = new Controler(config); //controler.setOverwriteFiles(true) ; controler.run() ;
Controler. There is an option to instruct Eclipse to organize the imports automatically. If you see red lines this option is deactivated in your configuration. For the moment just move the mouse over the word Controler. A dialog appears which suggests some quickfixes. Double-click on the (first) entry Import 'Controler' (org.matsim.core.controler)Copy the input files to your project:
plans.xml.gz), the network file (network.xml), the facilities file (facilities.xml.gz) and the config file (config.xml) and copy them to the input folder. You may have to refresh the Eclipse view afterwards (right-click your project and click Refresh).save as. Do not open the xml files in the browser for copying them into a text editor! Browsers usually add some characters for better visualization, which produce erros during xml parsing in MATSim.Run the simulation:
Run and click Run Configurations...Java Application in the left box and press the New buttonmyProject if it is not yet autofilledSearch... button to choose the Main classMyFirstControler and click OKArguments tab and type under Program arguments the path to the config file, i.e., input/config.xmlApply -XX:MaxPermSize=100m -Xmx1500m in VM arguments.RunS H U T D O W N --- regular shutdown completed appears everything went fine.If you want to rerun the scenario again, you have to clean the output folder. For safety reasons MATSim does not overwrite files in the output folder and exits if files are in there. For small sceanrios this looks incomfortable but imagine that you accidentally overwrite a run that took 10 days. You will be grateful to MATSim that it refuses to continue overwriting this work. If it falls on your nerves at the moment just open the MyFirstControler and remove the comment in front of controler.setOverwriteFiles(true) ; If you don't know how comments work in Java please check the Section 2.2.3.
Storing log messages into a file:
Sometimes you want to have a closer look into the logging information of your run. In all Run Configurations... you set up you can define a file location where the run dumps all logging messages:
Run and click Run Configurations...MyFirstControler in the left boxCommon tabFile at Standard Input and OutputWorkspace...MyProject > output and click OK${workspace_loc:/myProject/output}/MyFirstControler.logWhenever you run MyFirstControler all logging messages will now be written to the given file.
Your simulation finished after 1 iteration. As you have learned earlier, MATSim is based on the principle of evolution. Clearly, no evolutionary process is able to find an optimum in only one iteration, not even a local one. Hence, try to increase the number of iterations to 10. Open the configuration file and try it!
Has it worked out? Yes? Great! But where are the counts? Download the counts file (counts.xml) and copy it to the input folder. Now, open the configuration file again and try to add the traffic counts. You need the set the path to the counts input file. Additionally, you need to set the counts scale factor correctly. Please note, that we are using a 1% sample in this example. So the scale factor is 100. Illogical? Yes at first sight. But we are actually scaling the simulated values and not the counted values although that factor is given in the counts section of the configuration file.
Now it is time to have a look at the visualizer. When you start it, you should see a large, black area. This is where the traffic will be visualized. On the right side of this area, you see a smaller area with 5 icons on the top ("Controls"). Click the first icon ("Data Sources"). Now you can either drag and drop files into this section (e.g. a network.xml, or events.xml.gz), or click the green "+" at the bottom to select a file to be added. Use either option to add first network.xml to the list of available data and then events.xml.gz. Now the visualizer knows about our data, and we can tell it how to visualize it.
Next, click on the second icon ("Layers") in the "Controls" section. Initially, you will see only the background layer listed. Click on the green '+' to select the data you want to have displayed. It should already suggest to visualize the network with the loaded network.xml, so just click "Add". After a short moment, the network should be shown in the visualization area. Click the green '+' again, but this time choose "Vehicles" as layer type. The events.xml.gz file will be already pre-selected. Click on "Add". As any layer depending on the events, a "Load Data" button will appear at the bottom of the layer tag. Click it to extract the vehicles' positions from the events.
Zoom in to the Zurich area, and change the time with the slider below the visualization area to see how the vehicles move around.
After you have got in touch in with plans, networks and facilities in Lesson 3, we will look a little bit closer at these components in this lesson.
In this lesson, the creation of the main inputs for MATSim - network, plans, facilities and counts - is presented for a Swiss large-scale project recently done with MATSim (project "Westumfahrung Zürich"). This presentation is intended to give you a feeling which kind of data is needed and where you can potentially get them for your region of interest.
In this section, you will learn about one of the crucial steps for every MATSim project: The generation of a MATSim scenario, in other words the generation of demand and supply of the model. To get a rough idea how to accomplish that for your study area, we will again have a glimpse at the the initial demand creation for the region of Zurich in Switzerland.
Links ...............................................................
The MATSim plans file describes the MATSim population and its travel demand. A basic plans file could look as follows:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE plans SYSTEM "http://www.matsim.org/files/dtd/plans_v4.dtd"> <plans> <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> </plans>
The file stars with an xml preamble. 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). The last activity should not have an end time. Legs between activities need a mode, usually set to "car", but do not need any route information at this stage. The simulation expects all activities to take place on links (or in facilities, see below). When you run MATSim, it will automatically reference all activities with their nearest link. The plans file which MATSim puts in its output directory will contain the link ids for all activities, as well as routes for all legs.
At the moment two versions of the plans file are in use, v4 and v5. The plans file is an xml file and the coresponding DTD files can be found here (v4) and here v(5) respectively. Not all attributes are used already in MATSim. For example, the attribute employed does not yet have have an influence on the MATSim modules such as the replanning or the network loading simulation.
Besides a plan file and a config file the network file is the third mandatory input to MATSim. An example network is given as follows:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE network SYSTEM "http://www.matsim.org/files/dtd/network_v1.dtd"> <network name="example"> <nodes> <node id="0" x="505046.8125" y="137967.7969" /> <node id="1" x="520580.9063" y="147882.7969" /> <node id="2" x="594615.5" y="199259.2969" /> ... </nodes> <links capperiod="01:00:00" effectivecellsize="7.5" effectivelanewidth="3.75"> <link id="0" from="0" to="1" length="6243.0" freespeed="27.77777777777778" capacity="4000.0" permlanes="2.0" oneway="1" modes="car" origid="1" type="12" /> <link id="1" from="1" to="0" length="6243.0" freespeed="27.77777777777778" capacity="4000.0" permlanes="2.0" oneway="1" modes="car" origid="1" type="12" /> <link id="2" from="1" to="2" length="949.0" freespeed="33.333333333333336" capacity="4000.0" permlanes="2.0" oneway="1" modes="car" origid="2" type="10" /> ... </links> </network>
Network files are xml files that contain links and nodes. Links are defined by a start and an end node. (from="node" and to="node") Further important link attributes are (amongst others) length, capacity (vehicles per hour), free-flow speed and number of lanes. Recently an attribute specifying by which transport modes the link can be traveled was added. (modes) The coordinates are associated with the nodes (x, y).
More details about the attributes of facilities can be found in the DTD file here.
Facilities are an optional but helpful input component. MATSim agents perform activities at links or alternatively in facilities. Facilities can roughly be interpreted as buildings. However, this is not 100% correct. For Switzerland for example a facility is an artifical construct which represents an aggregate of all the buildings in a specific hectare (an area of 100 m x 100 m). Facilities are always connected to exactly one network link. Facilities can contain the attribute opening hours. If defined they are taken into account by the corresponding scoring function. You will hear more about scoring in Lesson 6.
An example file could look as follows:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE facilities SYSTEM "http://www.matsim.org/files/dtd/facilities_v1.dtd"> <facilities name="Facilities Switzerland"> <facility id="1" x="490737.8315400954" y="113215.09035687144" desc="..."> <activity type="home"> </activity> </facility> <facility id="2" x="482291.26945313875" y="131578.94780462672" desc="..."> <activity type="work"> <capacity value="20.0" /> <opentime day="mon" start_time="08:00:00" end_time="18:45:00" /> <opentime day="tue" start_time="08:00:00" end_time="18:45:00" /> <opentime day="wed" start_time="08:00:00" end_time="18:45:00" /> <opentime day="thu" start_time="08:00:00" end_time="18:45:00" /> <opentime day="fri" start_time="08:00:00" end_time="18:45:00" /> <opentime day="sat" start_time="08:00:00" end_time="17:00:00" /> </activity> <activity type="shop"> <capacity value="2000.0" /> <opentime day="mon" start_time="08:00:00" end_time="18:30:00" /> <opentime day="tue" start_time="08:00:00" end_time="18:30:00" /> <opentime day="wed" start_time="08:00:00" end_time="18:30:00" /> <opentime day="thu" start_time="08:00:00" end_time="18:30:00" /> <opentime day="fri" start_time="08:00:00" end_time="18:30:00" /> <opentime day="sat" start_time="08:00:00" end_time="16:00:00" /> </activity> </facility> </facilities>
More details about the attributes of facilities can be found in the DTD file here.
|
By end of 2009 a new bypass around Zurich was built. The planning of this bypass included developing efficient accompagnying measures. These measures were designed to help reducing the transit traffic through the city center of Zurich. A wide range, from constructional measures to control schedules for the traffic lights are now applied. MATSim was one tool to assess the efficiency of these measures. In this lesson we present the main steps done for setting up the MATSim scenario for this project. This give you a feeling from for the data requirements in practice. A complete report on the project can be found here [1]. |
![]() |
MATSim is able to handle planning networks and also navigation networks. Planning networks are often available from local or national planning authorities. In Switzerland a planning network is available by the Federal Office for Spatial Development ARE. Planning networks usually feature a much lower resolution. Most of these networks only capture car roads and only seldom public transport lines. For the project described in this section a network with 60'000 links and 24'000 nodes was used, consisting only of car roads.
Navigation networks are typically much more expensive, as they are provided by commercial companies. For Switzerland networks from NAVTEQ and Teleatlas are available.
A comparison of the Swiss planing network "ivtch" and a corresponding navigation network can be seen in the figures below.


When buying networks some cleaning steps are usually necessary, e.g., removing dead ends of the network. Some tools are provided in MATSim (org.matsim.core.network.algorithms.*)
An alternative for buying a network is to generate it yourself from OpenStreetMap. The quality of the OpenStreetMap network is increasing fast in many parts of the world, already reaching the quality of navigation networks in many European countries and other cities around the world. It is developed in a web collaboration and available for free. We will generate a network from OpenStreetMap in the next lesson.
The Swiss population is derived from the Swiss census of Population of the year 2000. The census gives very detailed information, i.e. every Swiss resident is captured. The derivation of a popualtion is thus a simple one-to-one transformation. Home locations are known at hectare level and corresponding work locations are given at municipality level by the commuter matrices, building constraints for the derivation of the initial demand as described in the next section.
If this information is only available at an aggregated level population synthesizers can be applied as described, e.g. in [2]. In the near future such a population synthesizer should be available for MATSim.
The travel demand is derived from the Swiss National Travel Survey for the years 2000 and 2005. This public use sample (PUS) contains approximately 30'000 person days. Information on trip purposes and modes used are given.
The day activity chains are drawn from this survey. For mode choice a MNL discrete choice model was developed.
A complete description of the demand generation is given for example in [3,4].
Activities can be performed at any link in MATSim. Essentially, only a network (supply side) and a popualtion with its travel demand (demand side) is needed to run a scenario. However, activity locations can be described at more detail if MATSim facilities are used. For Switzerland facilities are derived from the Swiss Business Census (work, shop, educatioon and leisure locations) and from the Swiss census (home locations). More than 1.5 million locations are generated. A detailed report is given in [5]. An crucial attribute of activity locations are in general the opening hours. Without taking into account the opening hours too many agents clearly avoid traffic jams by shifting their activities to the night! However, including disaggregate data for the opening hours usually means a lot of manual collection effort.
As you have seen yesterday, MATSim provides automatic visualization of simulated volumes with counted volumes. All you need to do is to provide the counted hourly volumes in an xml file. For Switzerland automatically and manually collected count data exists at national, cantonal and city level. The count stations used for the project are shown in the figure below. As future topic count data comparisons should also indicate a measure of the spread of the count data and not just the averages.

[1]: Balmer, M., A. Horni, K. Meister, D. Charypar, F. Ciari und K. W. Axhausen (2009) Wirkungen der Westumfahrung Zürich: Eine Analyse mit einer agentenbasierten Mikrosimulation, Schlussbericht, Baudirektion Kanton Zürich, IVT, ETH Zürich, Zürich.
[2]: Müller, K. and K.W. Axhausen (2011) Population synthesis for microsimulation: State of the art, paper presented at the 90th Annual Meeting of the Transportation Research Board, Washington, D.C., January 2011.
[3]: Meister, K., M. Rieser, F. Ciari, A. Horni, M. Balmer und K.W. Axhausen (2009) Anwendung eines agentenbasierten Modells der Verkehrsnachfrage auf die Schweiz, Strassenverkehrstechnik, 53 (5) 269-280.
[4]: Ciari, F., M. Balmer and K.W. Axhausen (2008) A new mode choice model for a multi-agent transport simulation, paper presented at the 8th Swiss Transport Research Conference, Ascona, October 2008.
[5]: Meister, K. (2008) Erstellung von MATSim Facilities für das Schweiz-Szenario, Arbeitsberichte Verkehrs- und Raumplanung, 541, Institut für Verkehrsplanung und Transportsysteme (IVT), ETH Zürich, Zürich.
As you have seen in the last lesson, the population is derived from the Swiss census of population. The package to produce the initial demand for Switzerland contains 42 classes. Obviously generating a real-world scenario takes weeks. Being limited by time constraints and also by privacy issues the generation of a real-world population and its travel demand can not be shown with the original data. Synthetic data are used. These data are strongly reduced but syntactically similar to the raw data.
But, before creating a population with tousands or even millions of agents we have to learn creating one single agent. This section explains in detail how to use the MATSim application programming interface (API) for the population creation.
Now we are ready to create the population for the Zurich Scenario.
If you can buy a planning network or a navigation network for your region of interest you are almost finished. Just convert the network to a MATSim xml-based network and perform some network cleaning if necessary. In the last sections we have used the planing network ivtch. We will continue using that network as developing is much faster using a small (i.e., not very dense) network.
However, should you not be so lucky to have a planning network at your hand we will show you in this section how to generate a free network from OpenStreetMap.
In the Zurich scenario we use the (optional input component) facilities. For Switzerland they are derived from the Swiss Business Census (work, shop, leisure and education locations) and the Swiss Census (home locations).
The finished scenario can be seen in this movie file. This movie file can be run with e.g., the VideoLAN player.
Links: .......
POnePersonPopulationGenerator containing a main method. All functionality will be added to this main method in this example.Config config = ConfigUtils.createConfig();
The red underlines again appear and you should again define, which class to use by hover over the lines and set the class. Be aware, that you have to use classes from MATSim! Then, you will probalby see a yellow underline for the config variable. It simply means, that this variable is not used in your code yet.
Scenario sc = ScenarioUtils.createScenario(config);
Network network = sc.getNetwork(); Population population = sc.getPopulation(); PopulationFactory populationFactory = population.getFactory();
Person person = populationFactory.createPerson(sc.createId("1"));
population.addPerson(person);
Plan plan = populationFactory.createPlan(); person.addPlan(plan);
CH1903_LV03 (swiss coordinate reference system), because we also generated the network that way.
CoordinateTransformation ct =
TransformationFactory.getCoordinateTransformation(
TransformationFactory.WGS84, TransformationFactory.CH1903_LV03
);
Coord homeCoordinates = sc.createCoord(8.55744100, 47.3548407);
Activity activity1 =
populationFactory.createActivityFromCoord(
"h6",ct.transform(homeCoordinates)
);activity1.setEndTime(21600);
plan.addActivity(activity1);
plan.addLeg(populationFactory.createLeg("car"));
Activity activity2 =
populationFactory.createActivityFromCoord(
"w10",ct.transform(sc.createCoord(8.51774679, 47.3893719))
);
activity2.setEndTime(57600);
plan.addActivity(activity2);
plan.addLeg(populationFactory.createLeg("car"));
Activity activity3 =
populationFactory.createActivityFromCoord(
"h6",ct.transform(homeCoordinates)
);
plan.addActivity(activity3);
MatsimWriter popWriter = new PopulationWriter(population, network);
popWriter.write("./input/plans.HandMade.xml");
Now, to run this program definine a second run configuration
Run and click Run Configurations...Java Application in the left box and press the New buttonmyProject if it is not yet autofilledSearch... button to choose the Main classPOnePersonPopulationGenerator and click OKArguments have to be defined.Apply -XX:MaxPermSize=100m -Xmx1500m in VM arguments.Runplans.HandMade.xml file.Now you just need to replace the plans file in the input folder and set the input path accordingly in the config file. Run the simulation, and afterwards start the visualizer and look at your agent traveling!
Of course, we want more than one agent. Let's start simple: We will create 100 identical agents by just surounding the agent gerentaion code by a for loop:
for (int i=0; i<100; i++) {
Person person = populationFactory.createPerson(sc.createId("pid"+i));
population.addPerson(person);
...
plan.addActivity(activity3);
}
Be sure, that each agent get a unique Id by using the loop counter i (see sc.createId("pid"+i) ).
Of course, identical agents do not reflect real traffic demand of a region. In the next section we will create heterogenous agents based on real statistical data.
The coordinates given above are taken from geofabrik.These tool uses World Geodetic System (WGS84). But for Switzerland we usually use the Swiss coordinates. So we have to convert the WGS84 coordinates to Swiss coordinates first by using the following MATSim tools:
CoordinateTransformation ct =
TransformationFactory.getCoordinateTransformation(
TransformationFactory.WGS84,TransformationFactory.CH1903_LV03
);
Coord transformedCoordinates = ct.transform(coordinates)Carrefully taking into account he coordinate system is always very important!
In this section we create the persons and their sociodemographics. Your task is to roughly understand the code provided and to fill the gaps in the code. Important code lines and gaps are marked with [[ x ]].
Step-by-Step:
census.txt is derived from the Swiss census. The original census contains 173 variables. In this example we only use a few of them. However, we have left a couple of unused variables in the file such that you get a feeling for the kind of work that is awaiting you in demand creation.Task: Please download census.txt and store it in the MATSim input folder.
CreatePopulationAndDemand which uses CreatePopulation and CreateDemand.Task: Download the classes from here. Adapt the package path and have a first look.
census.txt.Task: Set the paths accordingly at location [[ 0 ]]
Task: Navigate to location [[ 1 ]] and fill in the indices. In order to do that you must consult the file census_variables.txt. Therein the meaning of the variables is explained.
Task: Please find the location where the employment status is set and try to understand what is happening
Task: Try to understand how this is done in the code (location [[ 2 ]]). Try to get a rough idea of quadtrees. This is a data structure that you will use often in demand generation.
swiss_municipalities.txt and randomly assign the work locations in a range of 8km. For the Switzerland demand of course a much more sophisticated procedure was applied. The travel demand is essentially derived from a PUS, the Swiss National Travel Survey.
The following choice dimensions must be taken into account either in the optimization process or in the initial demand creation. If a choice dimension is not part of the optimization it must be created with care in initial demand creation.
Except activity chain choice all choice dimensions are part of the MATSim optimization. It is important to make sure that boundary conditions are taken into account accurately if a choice dimension is part of the optimization. E.g., if you perform time choice, ensure that opening hours are specified. Otherwise far too many agents will shift their activities to the nigth as there is less traffic then.
You will hear more on replanning modules in Lesson 6.
Step-by-Step:
travelsurvey_persons.txt and travelsurvey_trips.txt are derived from the Swiss National Travel SurveyTask: Please download them and store them in the MATSim input folder.
CreatePopulationAndDemand which uses CreateDemand.Task: Download the class CreateDemand from here. Adapt the package path and have a first look.
Task: Navigate to location [[ 3 ]] and set the paths to the two PUS files correctly. Navigate to location [[ 4 ]] and try to understand the method createPUSPlans.
Task: Navigate to location [[ 5 ]] and have a look. Answer the following question. Why do they use the census (without trip information) when they have a PUS population including trips.
CreatePopulationAndDemand
[1]: Ciari, F., M. Balmer and K.W. Axhausen (2008) A new mode choice model for a multi-agent transport simulation, paper presented at the 8th Swiss Transport Research Conference, Ascona, October 2008.
Geting the Switzerland OSM network:
http://download.geofabrik.de/osm/europe/ and download the switzerland.osm.bz2 file. Unpack it using a bunzip2 utility for your platform.
Exctracting the Zurich region from the complete Switzerland file:
Now we cut out the network of the Zurich region by a bounding box. However, to be able to simulate the day chains which intersect the Zurich area but are not fully contained in that area we extend the network. For efficiency reasons we use a smaller density (only big roads) for this network extension. Taking into account traffic that is intersecting the study area is alsways very important. At the least boundary effetcs are minimized by doing so.
http://wiki.openstreetmap.org/wiki/Osmosis and download the latest stable build. At the moment this can be done here.switzerland.osm)
--rx file=path-to-switzerland.osm --bounding-box top=47.701 left=8.346 bottom=47.146 right=9.019 completeWays=true --used-node --wx input/zurich.osm
--rx file=path-to-switzerland.osm --tf accept-ways highway=motorway,motorway_link,trunk,trunk_link,primary,primary_link --used-node --wx input/switzerland-bigroads.osm
--rx file=input/switzerland-bigroads.osm --rx input/zurich.osm --merge --wx input/merged-network.osm
Converting the OSM file to a MATSim network:
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 = "path-to-merged-network.osm";
Config config = ConfigUtils.createConfig();
Scenario sc = ScenarioUtils.createScenario(config);
Network net = sc.getNetwork();
CoordinateTransformation ct =
TransformationFactory.getCoordinateTransformation(
TransformationFactory.WGS84, TransformationFactory.CH1903_LV03);
OsmNetworkReader onr = new OsmNetworkReader(net,ct);
onr.parse(osm);
new NetworkCleaner().run(net);
new NetworkWriter(net).write("output-path-for-network.xml");
}
}
This class can be downloaded here.
For Switzerland the work, shop, leisure and education facilities are derived from the Swiss business census. Home facilities are derived from the Swiss census. But basically, any dwelling unit survey could be used.
This lesson is shorter than the ones before as generating facilities is a somewhat simpler task than generating a population and its travel demand or a network.
Step-by-Step:
business_census.txt and census.txt and copy it to the MATSim input folder.CreateFacilities from here to your source folder. You need to adapt the package path!null value in the assignment opentime = null). Use 18:30 as the end time for shopping. In Switzerland most stores close at this time. In general, this information must be gathered from different sources. Essentially the opening hours could be specified for every single facility, if such data is available. But in this example we are specifying the opening hours globally per activity type.CreateFacilities and have a look at the generated file facilities.xml.gz.
Here, we introduce the Events concept of MATSim and describe the basic Event types as well as their attributes.
The structure of a MATSim log file is presented and discussed.
In this tutorial, we use senozon's new visualizer for displaying the network, vehicles and activities. In this section, you will learn how to visualize the agents' movements and how to follow the plan of a single agent.
We introduce the plots and text files, which MATSim produces in every run.
Comparing real world traffic count data with the traffic counts from the simulation is important when calibrating a scenario. In this part of the tutorial it is shown, how traffic count data is converted into the MATSim counts format and mapped to a traffic network.
Links ...............................................................
In MATSim, Events are used to document changes in the state of an object. Each Event hosts one or multiple attributes. By default, the time when the Event occurred is contained. Additionally, information like the id of the agent who caused the event or the id of the link where the Event occurred could be included.
This picture shows the Events that are created when an agent ends an activity, performs a trip to the next activity and starts that activity. The order in which the Events are created is deterministic and is implied by the dashed arrows.
The basic MATSim Event types as well as their attributes are described in the following list:
ActivityEndEvent: Is created when an agent has just ended an activity.
agentId - the id of the agent who has ended the activity.
linkId - the id of the link where the agent has performed the activity.
facilityId - the id of the facility where the agent has performed the activity.
acttype - the type of the activity that the agent has performed.
ActivityStartEvent: Is created when an agent has just started an activity.
agentId - the id of the agent who has started the activity.
linkId - the id of the link where the agent performs the activity.
facilityId - the id of the facility where the agent performs the activity.
acttype - the type of the activity that the agent performs.
AgentArrivalEvent: Is created when an agent has arrived at an activity right before the activity starts.
agentId - the id of the agent who has just arrived at a facility.
linkId - the id of the link where the facility is located.
legMode - the transport mode the agent used in the preceding leg.
AgentDepartureEvent: Is created when an agent has just ended an activity and is going to depart from the facility where the activity took place.
agentId - the id of the agent who hast just departed from a facility.
linkId - the id of the link where the facility is located.
legMode - the transport mode the agent will use for the next leg.
AgentMoneyEvent: Can be used for different purpose like road pricing.
agentId - the id of the agent who gives or gets money.
AgentWait2LinkEvent: Is created after an agent has departed from a facility. Afterwards the agents has to wait until there is enough space for its vehicle on the link before entering the link.
agentId - the id of the agent who is waiting to enter a link.
linkId - the id of the link that the agent wants to enter.
LinkEnterEvent: Is created after an agent has just entered a link.
agentId - the id of the agent entering the link.
linkId - the id of the link that is entered by the agent.
LinkLeaveEvent: Is created after an agent has just left a link.
agentId - the id of the agent leaving the link.
linkId - the id of the link that is left by the agent.
By default, the MATSim simulation module creates a so called Events-file in every iteration. This file contains every single Event that has been created by the simulation, including all attributes that have been described in the list above. Therefore, the Events-file contains all information that might be used for post-processing of the simulation results (for example in a visualizer as via).
During each MATSim run, a log file is created. This file contains serveral information, that you might need later for your analyses. Additionally, it might be very helpful, if a run has crashed for some unknown reason. Subsequently, we will discuss the structure of a typical log file.
The first rows of each log file look like this:
2011-03-11 08:32:42,274 INFO Gbl:53 JVM: 1.6.0_22; Sun Microsystems Inc.; mixed mode; 64-bit 2011-03-11 08:32:42,276 INFO Gbl:57 OS: Linux; 2.6.26-2-amd64; amd64 2011-03-11 08:32:42,276 INFO Gbl:60 CPU cores: 8 2011-03-11 08:32:42,278 INFO Gbl:61 max. Memory: 3925.375MB (4116054016B) 2011-03-11 08:32:42,278 INFO Gbl:89 MATSim-Build: r14574 (2011-03-11 08:32:23) 2011-03-11 08:32:42,279 INFO Controler:313 Used Controler-Class: org.matsim.core.controler.Controler
They include information on
Next, the input config file is parsed and dumped. By doing so, the config parameters that have been used for the run can be easily reproduced.
2011-03-11 08:32:42,318 INFO MatsimConfigReader:100 trying to read config from ../matsim/mysimulations/ZH4EPFL/config.xml 2011-03-11 08:32:42,458 INFO MatsimConfigReader:118 using config_v1-reader. 2011-03-11 08:32:42,458 INFO MatsimXmlParser:213 Trying to load http://www.matsim.org/files/dtd/config_v1.dtd. In some cases (e.g. network interface up but no connection), this may take a bit. 2011-03-11 08:32:42,553 INFO GlobalConfigGroup:95 setting number of threads to: 4 2011-03-11 08:32:42,630 INFO Controler:676 Checking consistency of config... 2011-03-11 08:32:42,631 INFO Controler:678 Complete config dump after reading the config file: 2011-03-11 08:32:42,656 INFO Controler:681 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE config SYSTEM "http://www.matsim.org/files/dtd/config_v1.dtd"> <config> ... </config> 2011-03-11 08:32:42,657 INFO Controler:682 Complete config dump done.
Afterwards, the Scenario (population, network, facilities, counts) is loaded using the information from the config file and the default EventHandlers are initialized.
2011-03-11 08:32:42,657 INFO Controler:682 Complete config dump done. 2011-03-11 08:32:42,668 INFO ScenarioLoaderImpl:125 loading scenario from base directory: /scenario/ 2011-03-11 08:32:42,668 INFO ScenarioLoaderImpl:159 loading network from ../network.xml.gz 2011-03-11 08:32:42,673 INFO MatsimNetworkReader:93 using network_v1-reader. 2011-03-11 08:32:42,673 INFO MatsimXmlParser:213 Trying to load http://www.matsim.org/files/dtd/network_v1.dtd. In some cases (e.g. network interface up but no connection), this may take a bit. 2011-03-11 08:32:45,195 INFO ScenarioLoaderImpl:203 loading facilities from ../facilities.xml.gz 2011-03-11 08:32:45,200 INFO MatsimFacilitiesReader:110 using facilities_v1-reader. 2011-03-11 08:32:45,200 INFO MatsimXmlParser:213 Trying to load http://www.matsim.org/files/dtd/facilities_v1.dtd. In some cases (e.g. network interface up but no connection), this may take a bit. 2011-03-11 08:32:45,259 INFO ActivityFacilitiesImpl:110 facility # 1 2011-03-11 08:32:45,260 INFO ActivityFacilitiesImpl:110 facility # 2 2011-03-11 08:32:45,261 INFO ActivityFacilitiesImpl:110 facility # 4 ... 2011-03-11 08:33:31,688 INFO ActivityFacilitiesImpl:110 facility # 1048576 2011-03-11 08:33:43,917 INFO ScenarioLoaderImpl:225 loading population from ../plans.xml.gz 2011-03-11 08:33:43,923 INFO MatsimPopulationReader:90 using plans_v4-reader. 2011-03-11 08:33:43,923 INFO MatsimXmlParser:213 Trying to load http://www.matsim.org/files/dtd/plans_v4.dtd. In some cases (e.g. network interface up but no connection), this may take a bit. 2011-03-11 08:33:44,051 INFO PopulationImpl:173 person # 1 2011-03-11 08:33:44,052 INFO PopulationImpl:173 person # 2 2011-03-11 08:33:44,053 INFO PopulationImpl:173 person # 4 ... 2011-03-11 08:33:56,026 INFO PopulationImpl:173 person # 65536 2011-03-11 08:33:56,532 INFO EventsManagerImpl:155 adding Event-Handler: org.matsim.core.trafficmonitoring.TravelTimeCalculator 2011-03-11 08:33:56,533 INFO EventsManagerImpl:159 org.matsim.core.router.util.PersonalizableTravelTime 2011-03-11 08:33:56,533 INFO EventsManagerImpl:159 org.matsim.core.router.util.LinkToLinkTravelTime 2011-03-11 08:33:56,533 INFO EventsManagerImpl:159 org.matsim.core.api.experimental.events.handler.LinkEnterEventHandler 2011-03-11 08:33:56,533 INFO EventsManagerImpl:236 > org.matsim.core.api.experimental.events.LinkEnterEvent ... 2011-03-11 08:33:56,669 INFO EventsManagerImpl:167 2011-03-11 08:33:56,675 INFO TimeAllocationMutator:62 mutation range = 7200 2011-03-11 08:33:56,699 INFO PreProcessLandmarks:96 Putting landmarks on network... 2011-03-11 08:33:56,720 INFO LandmarkerPieSlices:97 Filling sectors... 2011-03-11 08:33:56,819 INFO LandmarkerPieSlices:108 Refining landmarks... 2011-03-11 08:33:56,825 INFO LandmarkerPieSlices:110 done 2011-03-11 08:33:56,825 INFO PreProcessLandmarks:100 done in 125 ms 2011-03-11 08:33:56,826 INFO PreProcessLandmarks:102 Calculating distance from each node to each of the 16 landmarks... 2011-03-11 08:33:58,741 INFO PreProcessLandmarks:125 done in 1915 ms 2011-03-11 08:33:58,751 INFO EventsManagerImpl:155 adding Event-Handler: org.matsim.analysis.LegHistogram 2011-03-11 08:33:58,752 INFO EventsManagerImpl:159 org.matsim.core.api.experimental.events.handler.AgentDepartureEventHandler 2011-03-11 08:33:58,752 INFO EventsManagerImpl:236 > org.matsim.core.api.experimental.events.AgentDepartureEvent ... 2011-03-11 08:33:58,753 INFO EventsManagerImpl:167 2011-03-11 08:33:58,758 DEBUG PlansScoring:50 PlanScoring loaded ScoringFunctionFactory 2011-03-11 08:33:58,758 INFO EventsManagerImpl:155 adding Event-Handler: org.matsim.core.scoring.EventsToScore 2011-03-11 08:33:58,759 INFO EventsManagerImpl:159 org.matsim.core.api.experimental.events.handler.AgentArrivalEventHandler 2011-03-11 08:33:58,759 INFO EventsManagerImpl:236 > org.matsim.core.api.experimental.events.AgentArrivalEvent ... 2011-03-11 08:33:58,761 INFO EventsManagerImpl:167 2011-03-11 08:33:58,767 INFO MatsimCountsReader:90 using counts_v1-reader. 2011-03-11 08:33:58,767 INFO MatsimXmlParser:213 Trying to load http://matsim.org/files/dtd/counts_v1.xsd. In some cases (e.g. network interface up but no connection), this may take a bit.
Subsequently, the configuration is dumped, which is used by the simulation. Note, that this configuration might be different from the input config file. If e.g. some config parameters are not included in the file, they are set to their default values.
2011-03-11 08:33:59,318 INFO Controler:676 Checking consistency of config... 2011-03-11 08:33:59,318 INFO Controler:678 Config dump before doIterations: 2011-03-11 08:33:59,323 INFO Controler:681 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE config SYSTEM "http://www.matsim.org/files/dtd/config_v1.dtd"> <config> ... </config> 2011-03-11 08:33:59,324 INFO Controler:682 Complete config dump done.
Then, the population is prepared for the first iteration. It is ensured, that each trip has a valid route (when using a initially created population, the route might be empty).
2011-03-11 08:33:59,383 INFO Counter:51 [PersonPrepareForSim] handled person # 1 2011-03-11 08:33:59,383 INFO Counter:51 [PersonPrepareForSim] handled person # 4 ... 2011-03-11 08:33:59,514 INFO Counter:57 [PersonPrepareForSim] handled person # 67239
Afterwards, the iterative optimization process starts. First, all EventsHandlers are resetted. If it is the first or a tenth iteration, the plans are dumped to a file. Then, the simulation starts. After the simulation has finished, some statistics are plotted (mean daily travel time, mean trip duration, mean score and so on).
2011-03-11 08:33:59,514 INFO Controler:466 ################################################### 2011-03-11 08:33:59,514 INFO Controler:467 ### ITERATION 0 BEGINS 2011-03-11 08:33:59,516 INFO EventsManagerImpl:188 resetting Event-Handlers 2011-03-11 08:33:59,516 INFO EventsManagerImpl:195 org.matsim.core.trafficmonitoring.TravelTimeCalculator 2011-03-11 08:33:59,517 INFO EventsManagerImpl:195 org.matsim.analysis.CalcLegTimes 2011-03-11 08:33:59,517 INFO EventsManagerImpl:195 org.matsim.analysis.LegHistogram 2011-03-11 08:33:59,517 INFO EventsManagerImpl:195 org.matsim.core.scoring.EventsToScore 2011-03-11 08:33:59,519 INFO EventsManagerImpl:155 adding Event-Handler: org.matsim.core.events.algorithms.EventWriterXML 2011-03-11 08:33:59,519 INFO EventsManagerImpl:159 org.matsim.core.events.algorithms.EventWriter 2011-03-11 08:33:59,519 INFO EventsManagerImpl:159 org.matsim.core.events.handler.BasicEventHandler 2011-03-11 08:33:59,519 INFO EventsManagerImpl:236 > org.matsim.core.api.experimental.events.Event 2011-03-11 08:33:59,520 INFO EventsManagerImpl:167 2011-03-11 08:33:59,520 INFO PlansDumping:49 dumping plans... 2011-03-11 08:34:08,121 INFO PopulationWriter:167 Population written to: ../output/ITERS/it.0/0.plans.xml.gz 2011-03-11 08:34:08,121 INFO PlansDumping:52 finished plans dump. 2011-03-11 08:34:08,130 INFO QSim:166 Using QSim... 2011-03-11 08:34:09,121 INFO QSim:698 SIMULATION (NEW QSim) AT 00:03:10 (it.0): #Veh=67239 lost=0 #links=1 #nodes=1 simT=0.0s realT=0s; (s/r): 0.0 2011-03-11 08:34:09,121 INFO Gbl:48 used RAM: 1737935376B = 1697202kB = 1657MB free: 2189178352B = 2087MB total: 3927113728B = 3745MB 2011-03-11 08:34:09,520 INFO QSim:698 SIMULATION (NEW QSim) AT 01:00:00 (it.0): #Veh=67239 lost=0 #links=48 #nodes=3 simT=3410.0s realT=1s; (s/r): 3410.0 2011-03-11 08:34:09,520 INFO Gbl:48 used RAM: 1737935376B = 1697202kB = 1657MB free: 2189178352B = 2087MB total: 3927113728B = 3745MB 2011-03-11 08:34:10,940 INFO EventsManagerImpl:148 event # 1 2011-03-11 08:34:10,946 INFO EventsManagerImpl:148 event # 2 2011-03-11 08:34:10,947 INFO EventsManagerImpl:148 event # 4 ... 2011-03-11 08:35:11,771 INFO QSim:698 SIMULATION (NEW QSim) AT 70:00:00 (it.0): #Veh=1 lost=0 #links=1 #nodes=0 simT=251810.0s realT=63s; (s/r): 3996.9841269841268 2011-03-11 08:35:11,771 INFO Gbl:48 used RAM: 2272570480B = 2219307kB = 2167MB free: 1804293008B = 1720MB total: 4076863488B = 3888MB 2011-03-11 08:35:12,043 INFO QSim:698 SIMULATION (NEW QSim) AT 71:00:00 (it.0): #Veh=1 lost=0 #links=1 #nodes=0 simT=255410.0s realT=63s; (s/r): 4054.126984126984 2011-03-11 08:35:12,044 INFO Gbl:48 used RAM: 2276333600B = 2222982kB = 2170MB free: 1800529888B = 1717MB total: 4076863488B = 3888MB 2011-03-11 08:35:12,315 INFO Controler:484 ### ITERATION 0 fires after mobsim event 2011-03-11 08:35:12,755 INFO EventsHandling:127 [0] average trip duration is: 5883 seconds = 01:38:03 2011-03-11 08:35:12,756 INFO Controler:486 ### ITERATION 0 fires scoring event 2011-03-11 08:35:12,869 INFO Controler:488 ### ITERATION 0 fires iteration end event 2011-03-11 08:35:12,873 INFO EventsManagerImpl:172 removing Event-Handler: org.matsim.core.events.algorithms.EventWriterXML 2011-03-11 08:35:18,370 INFO TravelDistanceStats:177 -- average of the average leg distance per plan (executed plans only): 28742.750015201498 2011-03-11 08:35:18,370 INFO TravelDistanceStats:178 -- average of the average leg distance per plan (worst plans only): 28742.750015201498 2011-03-11 08:35:18,370 INFO TravelDistanceStats:179 -- average of the average leg distance per plan (all plans): 28742.750015201498 2011-03-11 08:35:18,370 INFO TravelDistanceStats:180 -- average of the average leg distance per plan (best plans only): 28742.750015201498 2011-03-11 08:35:18,436 INFO ScoreStats:172 -- avg. score of the executed plan of each agent: 102.05968788012211 2011-03-11 08:35:18,436 INFO ScoreStats:178 -- avg. score of the worst plan of each agent: 102.05968788012211 2011-03-11 08:35:18,436 INFO ScoreStats:179 -- avg. of the avg. plan score per agent: 102.05968788012211 2011-03-11 08:35:18,436 INFO ScoreStats:180 -- avg. score of the best plan of each agent: 102.05968788012211 2011-03-11 08:35:18,444 INFO LegHistogramListener:76 number of legs: 216565 100% 2011-03-11 08:35:18,444 INFO LegHistogramListener:83 number of car legs: 216565 100.0% 2011-03-11 08:35:19,577 INFO Controler:492 ### ITERATION 0 ENDS 2011-03-11 08:35:19,578 INFO Controler:493 ###################################################
Finally, after the last iteration has ended, the shut down process is started. There, the latest plans as well as the network is written to the output folder.
2011-03-11 10:52:27,940 INFO Controler:505 S H U T D O W N --- start regular shutdown. 2011-03-11 10:52:54,047 INFO PopulationWriter:167 Population written to: ../output/output_plans.xml.gz 2011-03-11 10:52:54,049 INFO NetworkWriter:46 Writing network to file: ../output/output_network.xml.gz... 2011-03-11 10:52:54,877 INFO NetworkWriter:49 done. 2011-03-11 10:53:26,791 INFO Controler:537 S H U T D O W N --- regular shutdown completed.
At this point, we will have a closer look at the data with the senozon visualizer that we already used in Lesson 3 .
First, we load the network and the vehicles following the instructions in Lesson 3.
Note that loading huge event files can take up large amounts of memory. Start with loading 4-8 million events, observe how much RAM is used, before loading larger events files. To reduce the number of events loaded, you can either modify the events-file (e.g. on Linux: gzcat events.txt.gz | head -n 4000000 | gzip > events-sample4m.txt.gz) or limit the loading of events to a certain time period (under "Data Sources", where you added the events file).
After having some data loaded, it may be necessary to click once on the magnifying glass in the toolbar to zoom to the full extent of the loaded data.
If you want to have a look at the activities, please note that the activities layer is currently rather slow at displaying a large number of activities. It should only be activated when looking at small areas or when a scenario with a small number of agents is loaded.
Click on the last icon in the Controls section, so show the available interactive queries. Also, in the toolbar, click the blue icon with the white "i" in it. This makes your mouse-clicks being handled by the queries, as opposed to moving the visualization area around (click on the icon with the 4 arrows to switch back). Depending on the chosen query, you can:
As a start, make sure to have the "Vehicles" layer displayed, select "Show Agent Plan", and then click on a vehicle in the visualization area. The plan of that agent should be shown, with information about trips and activities (if the "Activities" Layer is loaded). Let the time continue, and observe how this single agent moves through the network and spends its time at an activity location.
Normally, a new query will replace a previous one. If you want to keep a query result, “flag” it by clicking on the little flag-icon. Note: not all queries are useful or applicable, depending on the data you have loaded.
The visualizer offers a layer of type "XY-Plotter" which is useful to quickly validate some input data. XY-Plotter simply plots dots at specific locations given in a file. The file must contain two columns of data, separated with a tab. The first column contains the x- coordinate, while the second contains the y-coordinate. The filename must end in “.xy” in order to be correctly recognized as a data source. This way, you can quickly visualize e.g. the position of network-nodes, activity locations, bus-stops etc. before converting them to the correct MATSim format, just by giving the coordinates in a simple text file. An example for such a text file is provided in the sample data provided on senozon's Visualizer download page.
MATSim creates several plots and text files during a simulation run, which can be used to analyze the results. We list those plots, describe their content and where you can find them. Some of them are created once for every run (they are stored in the output directory), others for every iteration (you find them in the directory of every iteration: ITERS/it.0 ... ITERS/it.xyz). However, please note, that the sample data used belows is from a "real world" MATSim scenario and not from the sample data that we use in this scenario. Therefore, you get an impression of what the results should look like but you cannot directly compare them to the results you create in this tutorial.
The score statistics are available as picture (scorestats.png) as well as a text file (scorestats.txt). They show the average best, worst, executed and average of all plans of an agent for every iteration.
ITERATION avg. EXECUTED avg. WORST avg. AVG avg. BEST 0 55.46765195286742 55.46765195286742 55.46765195286742 55.46765195286742 1 100.81338928590587 87.00888537259954 95.13534115494251 103.26179693728729 2 117.30442427414418 93.77342449505699 107.50133737829196 120.72747694353225 3 162.55440027791488 117.73999639316389 141.47605156620594 164.1856219665122 ... 100 178.34411061980995 176.80687419405862 178.94997562564544 180.25125747482224
The leg travel distance statistics is comparable to the score statistics, but instead of the score, the travel distance is ploted. The files are named traveldistancestats.png and traveldistancestats.txt.
ITERATION avg. EXECUTED avg. WORST avg. AVG avg. BEST 0 28742.750015201498 28742.750015201498 28742.750015201498 28742.750015201498 1 28648.360068406604 28745.348173034345 28695.555041804153 28645.788287343483 2 28601.267057252593 28749.02499586157 28670.362327059902 28594.874682563106 3 28534.155528743267 28746.32773291162 28636.37488661348 28526.915645433135 ... 100 28282.230805402305 28324.836917643 28298.25921314283 28285.969330279393
The stopwatch file (stopwatch.txt) contains the durations of actions like the replanning or the execution of the mobility simulation for every iteration. This data might be helpful for performance analyses (e.g. how long does the replanning take compared to the mobility simulation?).
Iteration BEGIN iteration BEGIN replanning END replanning BEGIN dump all plans END dump all plans BEGIN mobsim END mobsim BEGIN compare with counts END compare with counts END iteration replanning dump all plans mobsim compare with counts iteration 0 16:19:26 16:19:26 16:19:34 16:19:34 16:20:32 16:20:44 00:00:08 00:00:57 00:01:18 1 16:20:44 16:20:44 16:20:48 16:20:48 16:20:58 16:20:58 16:21:45 16:21:53 00:00:03 00:00:09 00:00:47 00:01:08 2 16:21:53 16:21:53 16:21:56 16:21:56 16:22:50 16:22:57 00:00:03 00:00:53 00:01:03 3 16:22:57 16:22:57 16:23:00 16:23:01 16:23:52 16:24:00 00:00:03 00:00:51 00:01:03 ... 100 18:09:57 18:09:57 18:10:00 18:10:00 18:10:26 18:10:26 18:11:31 18:11:42 18:11:51 18:12:02 00:00:03 00:00:25 00:01:05 00:00:09 00:02:05
A leg histogram depicts the number of agents that arrive, depart or are en route per time unit. Histograms are created for each transport mode and, additionally, for the sum of all transport modes. Each file starts with the iteration number and ends with the transport mode (e.g. 1.legHistogram_car.png or 1.legHistogram_all.png). Moreover, a textfile is created (e.g. 1.legHistogram.txt) that contains the data for all transport modes.
The trip durations text file (e.g. 1.tripdurations.txt) lists the number of trips and their durations on a time bin level for each acitivity pair (e.g. from work to home or from home to shopping).
pattern 0+ 5+ 10+ 15+ 20+ 25+ 30+ 35+ 40+ 45+ 50+ 55+ 60+ e0.5---h16 0 1 0 0 0 0 0 0 0 0 0 0 0 e0.5---h2 1 1 0 0 1 0 0 0 0 0 0 0 0 e0.5---h23 1 1 0 0 0 0 0 0 0 0 0 0 0
When working with count data, you unfortunately have to do a lot of work by hand. This is mainly due to two reasons. On the one hand, you typically get data from different sources (e.g. from the federal office for roads, the canton and the city) which do not use the same data format, therefore you have to convert them.
Often, different time spans are taken into account (e.g. a whole week, only week days or only mid-week days). Additionally, some counting stations can differ various kinds of vehicles while others cannot. Therefore, you have to ensure that the data from all of your sources is comparable.
On the other hand, you have to map the count stations to your network. Depending on the dataset, you might be able to select the link where a station is located automatically, but still you have to define the direction, in which the station counts. Typically, the direction is given by the destination where the road leads to. Therefore, having some basic knowledge on the geography of the investigated region will be very helpful.
We have provided you with a sample of eight count stations, which you can download here. If you cannot open the file (its format is Microsoft Excel), please install OpenOffice, which is Open Source. Please save the file on your computer since you have to add some data later. The file contains the mean traffic counts for each hour of the day, once respecting all days of a week (average daily traffic volume), once only respecting working days (average weekday traffic volume). Additionally, information on the directions in which the values are measured, are contained. We also added fields, where you can later insert the id of the link on which the station is located.
This figure shows the location of the count stations as well as the locations that are used to define the directions. E.g. direction Zurich means that vehicles are counted, which drive towards Zurich.

The file contains data that you can find here (unfortunately, the homepage is only available in german and french):
http://www.portal-stat.admin.ch/sasvz/files/de/00.xml
http://www.portal-stat.admin.ch/sasvz/files/de/01-ZH_09.xml
http://www.portal-stat.admin.ch/sasvz/files/de/03.xml
To map the count stations to the network, we will use QGis, which you have installed on the first day of this tutorial. As a first step, you have to create two shape files (one containing the nodes, one containing the links), which is a common GIS data format, containing the data from your network. >>more
However, you can skip this step because we have provided the shape files of the network below.
Please load the files with QGis via Layer – Add Vector Layer. Use then the Browse Button to select the file. Additionally, you find here another shape file that contains the positions of the count stations as point data. Unzip the files to the same directory as the other network files. After loading all three files, you should see them listed in the left column and visualized in the main window. You can adapt parameters like colour and line width by double clicking on the entry in the left column.
Your task is now to assign them to the network. To do so, we first adapt the visualization properties of the three files. The colours are chosen randomly when loading the data, therefore some of them might be quite similar. If that is the case, please change them.
After setting these parameters, you should see a picture like this:
Now, you have to assign two links to each count station (remember, each station counts in two directions). You can do this by performing the following steps for each station:
You can create the counts inputs file in two different ways. On the one hand, you can do it in your demand generation code like:
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");However, to do so, you need information on the link ids as well as the count volumes which you might import from a text file.
On the other hand, you can create your counts data directly as xml file. Below, you find an example for a counts file that contains a single station.
<?xml version="1.0" encoding="UTF-8"?>
<counts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://matsim.org/files/dtd/counts_v1.xsd" name="IVTCH" desc="ASTRA_and_ZH_stations" year="2005" layer="0">
<count loc_id="111780" cs_id="ASTRA001">
<volume h="1" val="14.83"></volume>
<volume h="2" val="4.62"></volume>
<volume h="3" val="2.49"></volume>
<volume h="4" val="1.93"></volume>
<volume h="5" val="5.38"></volume>
<volume h="6" val="12.70"></volume>
<volume h="7" val="52.78"></volume>
<volume h="8" val="156.86"></volume>
<volume h="9" val="159.99"></volume>
<volume h="10" val="156.34"></volume>
<volume h="11" val="187.67"></volume>
<volume h="12" val="224.57"></volume>
<volume h="13" val="208.28"></volume>
<volume h="14" val="219.92"></volume>
<volume h="15" val="247.27"></volume>
<volume h="16" val="268.12"></volume>
<volume h="17" val="303.67"></volume>
<volume h="18" val="368.89"></volume>
<volume h="19" val="288.11"></volume>
<volume h="20" val="168.45"></volume>
<volume h="21" val="102.43"></volume>
<volume h="22" val="66.99"></volume>
<volume h="23" val="55.99"></volume>
<volume h="24" val="37.84"></volume>
</count>
</counts>When writing counts data directly into an XML file, you can use this template.
Use the template and the data from the sample file that contains the counts as well as station to link mapping. We model a typical work day, therefore take the counts data from the corresponding columns (average weekday traffic volume). Please fill in the following fields (just set the first three fields to arbitrary values if you do not need them):
The Excel file helps you with adding count stations in XML format. For Count Station number 20, string construction is already defined to easily copy paste this count station into your XML template. Do that also for the other count stations.
Now edit your config.xml again and make the following settings:
<module name="counts" > <param name="countsScaleFactor" value="100" /> <param name="inputCountsFile" value="./input/counts.xml" /> <param name="outputformat" value="kml" /> </module>
Now run the simulation again! As mentioned, the counts module runs only 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. kml is the file format used by Google Earth, kmz is a zipped kml file which can also be read directly 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).
If you had problems mapping the count stations to the network (or if you run out of time), you will find here a file containing all stations mapped to the network.
Below, you find the code which converts a MATSim network into two shape files - one containing the links, one containing the nodes. Please use the network file that we have prepared and that you could download in Section 5.4 of the tutorial.
import java.util.ArrayList;
import java.util.Collection;
import org.geotools.feature.AttributeType;
import org.geotools.feature.AttributeTypeFactory;
import org.geotools.feature.DefaultAttributeTypeFactory;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureType;
import org.geotools.feature.FeatureTypeBuilder;
import org.matsim.api.core.v01.Scenario;
import org.matsim.api.core.v01.network.Link;
import org.matsim.api.core.v01.network.Network;
import org.matsim.api.core.v01.network.Node;
import org.matsim.core.config.Config;
import org.matsim.core.network.LinkImpl;
import org.matsim.core.scenario.ScenarioUtils;
import org.matsim.core.utils.geometry.geotools.MGC;
import org.matsim.core.utils.gis.ShapeFileWriter;
import org.matsim.core.utils.misc.ConfigUtils;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.impl.CoordinateArraySequence;
public class CreateNetworkSHP {
public static void main(String[] args) throws Exception {
Config config = ConfigUtils.createConfig();
config.network().setInputFile("network.xml");
Scenario scenario = ScenarioUtils.loadScenario(config);
Network network = scenario.getNetwork();
GeometryFactory geoFac = new GeometryFactory();
CoordinateReferenceSystem crs = MGC.getCRS("EPSG:21781"); // EPSG Code for Swiss CH1903_LV03 coordinate system
Collection<Feature> features = null;
AttributeType geom = null;
AttributeType id = null;
AttributeType fromNode = null;
AttributeType toNode = null;
AttributeType length = null;
AttributeType type = null;
AttributeType capacity = null;
AttributeType freespeed = null;
FeatureType ftRoad = null;
FeatureType ftNode = null;
features = new ArrayList<Feature>();
geom = DefaultAttributeTypeFactory.newAttributeType("LineString", Geometry.class, true, null, null, crs);
id = AttributeTypeFactory.newAttributeType("ID", String.class);
fromNode = AttributeTypeFactory.newAttributeType("fromID", String.class);
toNode = AttributeTypeFactory.newAttributeType("toID", String.class);
length = AttributeTypeFactory.newAttributeType("length", Double.class);
type = AttributeTypeFactory.newAttributeType("type", String.class);
capacity = AttributeTypeFactory.newAttributeType("capacity", Double.class);
freespeed = AttributeTypeFactory.newAttributeType("freespeed", Double.class);
ftRoad = FeatureTypeBuilder.newFeatureType(new AttributeType[] {geom, id, fromNode, toNode, length, type, capacity, freespeed}, "link");
for (Link link : network.getLinks().values()) {
Coordinate fromNodeCoordinate = new Coordinate(link.getFromNode().getCoord().getX(), link.getFromNode().getCoord().getY());
Coordinate toNodeCoordinate = new Coordinate(link.getToNode().getCoord().getX(), link.getToNode().getCoord().getY());
Coordinate linkCoordinate = new Coordinate(link.getCoord().getX(), link.getCoord().getY());
LineString ls = new LineString(new CoordinateArraySequence(new Coordinate [] {fromNodeCoordinate, linkCoordinate, toNodeCoordinate}), geoFac);
Feature ft = ftRoad.create(new Object [] {ls , link.getId().toString(), link.getFromNode().getId().toString(),link.getToNode().getId().toString(), link.getLength(), ((LinkImpl)link).getType(), link.getCapacity(), link.getFreespeed()}, "links");
features.add(ft);
}
ShapeFileWriter.writeGeometries(features, "network_links.shp");
features = new ArrayList<Feature>();
geom = DefaultAttributeTypeFactory.newAttributeType("Point", Point.class, true, null, null, crs);
id = AttributeTypeFactory.newAttributeType("ID", String.class);
ftNode = FeatureTypeBuilder.newFeatureType(new AttributeType[] {geom, id}, "node");
for (Node node : network.getNodes().values()) {
Coordinate nodeCoordinate = new Coordinate(node.getCoord().getX(), node.getCoord().getY());
Point point = geoFac.createPoint(nodeCoordinate);
Feature ft = ftNode.create(new Object[] {point, node.getId().toString()}, "nodes");
features.add(ft);
}
ShapeFileWriter.writeGeometries(features, "network_nodes.shp");
}
}
MATSim offers several different MobSims (Mobility Simulations). We discuss their features and whether they are still supported or out of date. Moreover, we show, how a MobSim is selected and configured in the config file.
Due to performance reasons, often only small samples of a population is simulated. When doing so, parameters in the config file for the MobSim as well as the counts have to be adapted to create valid results.
MATSim offers several Replanning Modules to optimize the plans of the agents. In this section, those modules are described. Moreover, it is shown, how they are configured via the config file. Questions like "Which modules will be used?" and "Which share of agents uses a specific replanning module per iteration?" will be answered.
In this section, the default MATSim scoring function as well as its parameters in the config file are discussed.
One major part of MATSim is the execution of the agents' plans, which is done by a MobSim (Mobility Simulation). In the history of MATSim, several MobSims have been developed. Some of them are still in use, others are obsolete and no longer supported today. However, if you work with MATSim, they might come up from time to time.
First, we will list all obsolete and current MobSims, then we will show how to select a MobSim in the config file.
The parameter to select a MobSim in the config file is located in the controler module. Currently supported values are: queueSimulation, qsim, multimodalQSim and jdeqsim.
<module name="controler" > <param name="firstIteration" value="0" /> <param name="lastIteration" value="100" /> <param name="outputDirectory" value="./output" /> <param name="eventsFileFormat" value="xml" /> <param name="mobsim" value="qsim" /> </module>
For each MobSim, an additional module is available in the config file.
Due to performance reasons, often a sample population (1%, 10%, 25% of the entire population) is simulated. Typically, the population can be scaled down to a 10% sample before significant artefacts occur. When scaling down the population, also the network has to be scaled to keep the traffic flows consistant. This is done by scaling the flow and storage capacity of a link by the same factor as the population.
Please note, that:
In the config file, you will find for each MobSim the two parameters for the flow and storage capacity of a link, which are named flowCapacityFactor and storageCapacityFactor. Please ensure that you set them for the MobSim that you have set in the controler module!
We use a 1% sample, therefore they have to be set to 0.01. Run the simulation twice - once with factors of 1.0, once with 0.01 and compare the results.
MATSim offers some default replanning modules. First, we will show, how the modules are defined in the config file. Afterwards, we describe them as well as their parameters.
Some replanning modules adapt the structure of a plan (e.g. the start- and end time of an activity), others select a plan for an agent (each agent holds multiple plans and executes them alternatively; however, a module can also select the same plan that is already selected).
Below, you find an example of the module that defines the replanning in the config file. The first entry defines that each agent can store up to 4 plans. The Replanning module, which adapts a plan, do this by cloning an existing plan and then adapting the new plan. By doing so, an agent increases the amount of plans in its memory. If the amount of plans exceeds the maximum value, the worst plan is deleted.
Each module is defined by three parameters. The first one specifies the module itself. The next one defines the probability that the module will be chosen by an agent (each agents chooses exactly one replanning module per iteration). Finally, the last parameter can be used to disable a replanning module after a certain number of iterations. Please note that this affects the probability of the remaining modules to be selected (P = pModule / sum(pModules) - therefore, it is not necessary that the sum of all probabilities equals 1.0).
<module name="strategy" > <param name="maxAgentPlanMemorySize" value="4" /> <param name="Module_1" value="TimeAllocationMutator" /> <param name="ModuleProbability_1" value="0.1" /> <param name="ModuleDisableAfterIteration_1" value="20" /> <param name="Module_2" value="ReRoute_Landmarks" /> <param name="ModuleProbability_2" value="0.1" /> <param name="ModuleDisableAfterIteration_2" value="null" /> <param name="Module_3" value="SelectExpBeta" /> <param name="ModuleProbability_3" value="0.8" /> <param name="ModuleDisableAfterIteration_3" value="null" /> </module>
Replanning modules that adapt the structure of a plan are (the name in the brackets has to be used as name in the config file):
Replanning modules that select a plan are (again, use the name in the brackets in the config file):
Now it is time for some experiments. Set the number of iterations to ten. Then run a simulation with each of the following parameter set and check the score statistics plot to see the effects:
For these experiments, please compare the Leg Histograms of the last iteration of each run.
By default, MATSim uses the so called Charypar Nagel Scoring Function, which is described in detail in [1].
Besides some other parameters, the plansCalcScore module in the config file contains the parameters for this scoring function. Basically, they describe the amount of (dis-)utility an agent gains, for certain actions. Arriving later than scheduled at an activity e.g. results in a disutility of 18.0 monetary units per hour.
<module name="planCalcScore" > <param name="earlyDeparture" value="0.0" /> <param name="lateArrival" value="-18.0" /> <param name="performing" value="6.0" /> <param name="traveling" value="-6.0" /> <param name="waiting" value="0.0" /> </module>
We start our "how to extend the Controler" with a short look on the basic parameters, that can be set in the Controler before running it.
Initial, the times when activity can be performed in MATSim were defined in the config file. However, when the facilities were introduced, the possibility to set different opening times for each facility, was created. To use those information instead of the values in the config file, a different Scoring Function has to be used. In this lesson, we will learn how to do that.
You will hear more about events in this section. You will also learn how to write your own events handler. This handler can be used to do post-processing analyses. On the other hand the handler can be incorporated as an events listener in the course of the iterations. In the next section you will learn how to do that.
Not making empty promises, you will program your own controler listener in this lesson. The controler listener is the events handler you programmed just some minutes ago. You will add the listener to your controler created in Lesson 3.
Links ...............................................................
For now, we can already run a simulation – now it is time to customize them. You will better understand what is the role of the Controler in MATSim and how it can be configured. You will also know how functionalilty can be added to a MATSim run. In Lesson 3, you have already created your first, own Controler. Now it is time to learn more about the possibilities to configure a Controler. Now, you will get to know some basic controler parameters that you can set before running the controler.
Besides setting factories for components like the scoring function (which you you will learn in the next part of this lesson), several parameters can be set, which influence the I/O behavior of MATSim. The Controler offers the following methods to do so:
You can add them to your controler, directly before the controler.run() command:
... controler.setCreateGraphs(false); controler.setDumpDataAtEnd(false); controler.setOverwriteFiles(true); controler.setWriteEventsInterval(0); controler.run(); ...
Before facilities were introduced in MATSim, the opening times had to be defined in the config file. However, today, the opening times can be set for each facility individually. To use these opening times instead of the values that are defined in the config file, a different scoring function has to be used. To use this new scoring function, which is called CharyparNagelOpenTimesScoringFunction, you have to adapt the MyFirstControler that you created in session 3 of this tutorial. Adapt the code like this and use Eclipse to organize the import of the new classes:
... String configFile = args[0] ; Config config = ConfigUtils.loadConfig(configFile); Controler controler = new Controler(config); //controler.setOverwriteFiles(true) ; // get objects that are required as parameter for the CharyparNagelOpenTimesScoringFunctionFactory PlanCalcScoreConfigGroup planCalcScoreConfigGroup = controler.getConfig().planCalcScore(); ActivityFacilities facilities = controler.getFacilities(); // create the CharyparNagelOpenTimesScoringFunctionFactory CharyparNagelOpenTimesScoringFunctionFactory factory = new CharyparNagelOpenTimesScoringFunctionFactory(planCalcScoreConfigGroup, facilities); // set the CharyparNagelOpenTimesScoringFunctionFactory as default in the controler controler.setScoringFunctionFactory(factory); controler.run() ; ...
In Lesson 5.1. we already discussed the Event types that are used by MATSim. In this lesson, you will learn how to write your own EventsHandler. You probably think now "What is an EventsHandler?!". Basically, it is a Object that is informed each time, when an event of a certain type is created. The EventsHandler then can access the information contained, e.g. to conduct some analysis.

An EventsHandler can either be used while the simulation is running or as post-processing tool - both will produce the same results. However, the second one requires a bit less coding, therefore we will first focus on that one in this part of the lesson. Using a Handler during a running simulation will be introduced in the next part of this lesson. So lets start to learn how to write your own EventsHandler!
To do so, you have to define which Event types you need for your analysis. The handler that we want do develop should be able to count the number of trips that have been conducted. To do so, we could either count the number of departure or arrival events. However, we decide to count both of them and compare the results. Therefore, we create a new class, that implements the AgentArrivalEventHandler as well as the AgentDepartureEventHandler.
import org.matsim.core.api.experimental.events.AgentArrivalEvent;
import org.matsim.core.api.experimental.events.AgentDepartureEvent;
import org.matsim.core.api.experimental.events.handler.AgentArrivalEventHandler;
import org.matsim.core.api.experimental.events.handler.AgentDepartureEventHandler;
public class TripCounter implements AgentDepartureEventHandler, AgentArrivalEventHandler {
@Override
public void handleEvent(AgentArrivalEvent event) {
}
@Override
public void handleEvent(AgentDepartureEvent event) {
}
@Override
public void reset(int iteration) {
}
}
Add two int variables to count the arrivals and departures separately. Reset them in the reset method which is called at the beginning of each iteration.
...
private int departureCount = 0;
private int arrivalCount = 0;
...
@Override
public void reset(int iteration) {
departureCount = 0;
arrivalCount = 0;
}
...Now, increase the counts every time a corresponding event is created. Please note, that you could also access the attributes of the event (time, agentId, linkId, ...). By using that information, e.g. only trips of a certain agent could be counted.
...
@Override
public void handleEvent(AgentArrivalEvent event) {
arrivalCount++;
}
@Override
public void handleEvent(AgentDepartureEvent event) {
departureCount++;
}
...
Finally, write a method printCounts that prints the results.
public void printCounts() {
System.out.println("Departures: " + departureCount);
System.out.println("Arrivals: " + arrivalCount);
}To test our EventsHandler, we write a simple class, which we call ReadEvents, that reads an events file and prints the counts:
import org.matsim.core.api.experimental.events.EventsManager;
import org.matsim.core.events.EventsManagerImpl;
import org.matsim.core.events.MatsimEventsReader;
public class ReadEvents {
public static void main(String[] args) {
// The filename of the input file. Point this to the location where your event file is.
String inputFile = "output/ITERS/it.10/run0.10.events.xml.gz";
// Create an EventsManager instance. This is MATSim infrastructure.
EventsManager eventsManager = new EventsManagerImpl();
// Create an instance of the custom EventHandler which you just wrote. Add it to the EventsManager.
TripCounter handler = new TripCounter();
eventsManager.addHandler(handler);
// Connect a file reader to the EventsManager and read in the event file.
MatsimEventsReader reader = new MatsimEventsReader(eventsManager);
reader.readFile(inputFile);
System.out.println("Events file read!");
// Print the counts from the TripCounter
handler.printCounts();
}
}
Now, try to extend your handlers:
Access the attributes of the events and e.g. print the Id of an agent who departs as well as the time to the console.
Calculate the total trip travel time of all agents. To do so, you have to combine information from departure and arrival events. Use a Map<Id, Double> to store the id and the time when an agent departs. For each arrival event, there should be a corresponding entry in the map. Read that entry to calculate the trip travel time and then remove the entry from the map.
Count the number of links that are passed. To do so, your Handler has to implement the LinkEnterEventHandler or the LinkLeaveEventHandler (or implement both and compare the counts).
In this lesson you will create your own controler listener and add it to your Controler. Let us start with a look at the structure of the Controler. It can be extended at any of the following points:

At any of those extension points, ControlerEvents and created, which can be used in combination with ControlerListeners to interact with the Controler. The following ControlerListeners are available:
A sample Listener class might look like this:
import org.matsim.core.controler.events.StartupEvent;
import org.matsim.core.controler.listener.StartupListener;
public class MyControlerListener implements StartupListener {
@Override
public void notifyStartup(StartupEvent event) {
...
}
}We want to write a ControlerListener, that creates an instance of the EventHandler (TripCounter) that you created in a previous part of this lection and registers it at the EventManager. Moreover, we want the count values to be printed at the end of each iteration. To do so, we need a class that implements a StartupListener and an IterationEndsListener.
import org.matsim.core.controler.events.IterationEndsEvent;
import org.matsim.core.controler.events.StartupEvent;
import org.matsim.core.controler.listener.IterationEndsListener;
import org.matsim.core.controler.listener.StartupListener;
public class MyControlerListener implements StartupListener, IterationEndsListener {
@Override
public void notifyStartup(StartupEvent event) {
...
}
@Override
public void notifyIterationEnds(IterationEndsEvent event) {
...
}
}Finally, we have to create the instance of the EventHandler, register it as EventHandler at the EventsManager and ensure, that its print method is called after every iteration.
...
private TripCounter tripCounter;
@Override
public void notifyStartup(StartupEvent event) {
// create an instance of the TripCounter
tripCounter = new TripCounter();
// register the TripCounter at the EventsManager
event.getControler().getEvents().addHandler(tripCounter);
}
@Override
public void notifyIterationEnds(IterationEndsEvent event) {
// print the counter values
tripCounter.printCounts();
}
...
As a last step, you have to add the MyControlerListener to your MyFirstControler as shown below:
public class myFirstControler {
public static void main(String[] args) {
String configFile = args[0] ;
Controler controler = new Controler( configFile ) ;
controler.setOverwriteFiles(true) ;
controler.addControlerListener(new MyControlerListener());
controler.run() ;
}
}
Now you can test your code by running the controler. If everything is fine, you can go on with two more exercises:
Write a Controler Listener that outputs a message at the begin and end of each iteration.
The EventHandler as well as the ControlerListener that you have written can be combined into a single file. Try to do so!
The plan of constructing a tunnel underneath the Zurich lake frequently comes up in Zurich. Let us add a high capacity link from Wollishofen [8.52026, 47.34708] to Tiefenbrunnen [8.55983, 47.35103] and see what happens in the rest of the city. Especially interesting are the effects on the Hardbrücke [8.52434, 47.39269], a road very highly loaded during the whole day and often a spot with annoying traffic jams.
For adding the two new links try to identify the respective two nodes by using the GIS files in QGis as in Lesson 5 or use the google earth files provided below. Add then one link in each direction connecting the nodes in the planning network that was handed out to you in Lesson 3.
Feel free to investigate your own ideas. If you find out something interesting we could also report it here afterwards ...
Lesson 1: Shanghai: Andreas Horni; Seoul: Michael Balmer; Singapore: Michael Balmer
Lesson 2: Shanghai: Andreas Horni; Seoul: Nadine Schüssler; Singapore: Michael Balmer & Pieter Fourie
Lesson 3: Shanghai: Andreas Horni; Seoul: Nadine Schüssler; Singapore: Pieter Fourie
Lesson 4: Shanghai: Andreas Horni; Seoul: Michael Balmer; Singapore: Michael Balmer
Lesson 5: Shanghai: Christoph Dobler; Seoul: Nadine Schüssler; Singapore: Pieter Fourie
Lesson 6: Shanghai: Christoph Dobler; Seoul: Nadine Schüssler; Singapore: Pieter Fourie
Lesson 7: Shanghai: Christoph Dobler; Seoul: Michael Balmer; Singapore: Michael Balmer
Lesson 8: Shanghai: Andreas Horni, Seoul: Nadine Schüssler; Singapore: Pieter Fourie
Extension A: Shanghai: -; Seoul: -; Singapore: Michael Balmer
Extension B: Shanghai: -; Seoul: -; Singapore: Michael Balmer
Extension A: Working with User Defined Attributes >>more[150 minutes] Lecturers: ... You got your own model and your specialized attributes and parameters that you want to connect with MATSim? We will learn how to transform and assign extended information to MATSim Objects.
|
|
Extension B: Using User Defined Attibutes for the MATSim Relaxation Process >>more[150 minutes] Lecturers: ... In Extension A you have learned how to extend MATSim objects with user defined attributes and how to use them for your analysis. But something is not satisfying: Agents do not react on these additional information, i.e. they do not change their behavior. In this lesson you will learn how to include your extension into the agent mobility behavior.
|
|
Links ....................................................
To enrich MATSim objects with additional, user defined attributes, values and parameters, you can use the quite simple concept of MATSim's ObjectAttributes. But wait! What are MATSim objects? The answer is: "Everything that contains an Id." Therefore, you can assign additional information to persons, node and links of the network, to facilities, and so on.
Very often, the assignment of extended information has to be done during the generation of your scenario (see Lesson 5). Then, these data will be used during the MATSim runs and finally, analysis are performed using the enriched data. In Lesson 8, we already learned, how to implement your own analysis. In this Lesson, we will
containing a main method. All functionality will be added to this main method in this example.Scenario scenario = ScenarioUtils.loadScenario(ConfigUtils.loadConfig(args[0]));
ObjectAttributes agentAttributes = new ObjectAttributes();
for (Person p : scenario.getPopulation().getPersons().values()) {
// TODO: do the assingment of the attribute.
}private static Random random = MatsimRandom.getRandom(); public static final String ECAR_ATT = "eCar"; private static final double SHARE_IN_ZURICH = 0.8; private static final double SHARE_OUTSIDE_ZURICH = 0.2;
for loop:
PlanElement pe = p.getSelectedPlan().getPlanElements().get(0);
Activity homeActivity = (Activity)pe;
Coord c = homeActivity.getCoord();
if ((c.getX() >= 676000) && (c.getX() <= 687000) && (c.getY() >= 244000) && (c.getY() <= 251500)) {
if (random.nextDouble() < SHARE_IN_ZURICH) { agentAttributes.putAttribute(p.getId().toString(),ECAR_ATT,true); }
else { agentAttributes.putAttribute(p.getId().toString(),ECAR_ATT,false); }
}
else {
if (random.nextDouble() < SHARE_OUTSIDE_ZURICH) { agentAttributes.putAttribute(p.getId().toString(),ECAR_ATT,true); }
else { agentAttributes.putAttribute(p.getId().toString(),ECAR_ATT,false); }
}
new ObjectAttributesXmlWriter(agentAttributes).writeFile("./input/agentAttributes.xml");
In this step we will use the eCar attribute to analyse traffic volumes produced by e- and non-eCars. Similar to Lesson 7.3 we will implement an EventsHandler and a main method that parses trough the events using the handler.
ECarVolumeCalculator as an LinkLeaveEventHandler
public class ECarVolumeCalculator implements LinkLeaveEventHandler {
private final ObjectAttributes agentAttributes;
private final Network network;
private final Map<Id,Tuple<Integer,Integer>> carCnt = new TreeMap<Id,Tuple<Integer,Integer>>();
public ECarVolumeCalculator(ObjectAttributes agentAttributes, Network network) {
this.agentAttributes = agentAttributes;
this.network = network;
reset(0);
}
@Override
public void reset(int iteration) {
carCnt.clear();
for (Id linkId : network.getLinks().keySet()) {
carCnt.put(linkId, new Tuple<Integer, Integer>(0,0));
}
}
@Override
public void handleEvent(LinkLeaveEvent event) {
Boolean eCar = (Boolean)agentAttributes.getAttribute(event.getPersonId().toString(),CreateAgentAttributes.ECAR_ATT);
Tuple<Integer,Integer> tuple = carCnt.get(event.getLinkId());
if (eCar) {
carCnt.put(event.getLinkId(),new Tuple<Integer, Integer>(tuple.getFirst()+1,tuple.getSecond()));
}
else {
carCnt.put(event.getLinkId(),new Tuple<Integer, Integer>(tuple.getFirst(),tuple.getSecond()+1));
}
}
public void writeTable(String filename) throws FileNotFoundException, IOException {
BufferedWriter writer = IOUtils.getBufferedWriter(filename);
writer.write("linkId,eCars,oCars\n");
for (Entry<Id,Tuple<Integer,Integer>> e : carCnt.entrySet()) {
writer.write(e.getKey().toString()+","+e.getValue().getFirst()+","+e.getValue().getSecond()+"\n");
}
writer.close();
}
}
Map<Id,Tuple<Integer,Integer>> carCnt stands for.handleEvent(LinkLeaveEvent event) method is doing.ReadEvents2 class:
public class ReadEvents2 {
public static void main(String[] args) throws SAXException, ParserConfigurationException, IOException {
String inputFile = "output/ITERS/it.10/run0.10.events.xml.gz";
Scenario scenario = ScenarioUtils.loadScenario(ConfigUtils.loadConfig(args[0]));
ObjectAttributes agentAttributes = new ObjectAttributes();
new ObjectAttributesXmlReader(agentAttributes).parse("./input/agentAttributes.xml");
EventsManager events = new EventsManagerImpl();
ECarVolumeCalculator handler = new ECarVolumeCalculator(agentAttributes,scenario.getNetwork());
events.addHandler(handler);
MatsimEventsReader reader = new MatsimEventsReader(events);
reader.readFile(inputFile);
System.out.println("Events file read!");
handler.writeTable("./output/ECarCounts.csv");
}
}
ReadEvents2 and the ReadEvents of Lesson 7.3 main routine?ECarCounts.csv file.Well, now, we got a nice table containing eCar and non-eCar volumes per link. But we would like to present that as a common figure of the network. For that, we use a QGis functionality that combines a shape file with an attribute table.
ECarCounts.csv fileNow you can color the links according to different values for eCars as well as for non-eCars.
volumes non-electric cars:
volumes electric cars:
This lesson really goes into the deep of MATSim where you will use several programming concepts. Furthermore, You will learn a lot about the plug-and-play architecture of MATSim. More precisely:
First of all, let's think about a case study that need the information about the car types used. We want to know how agents would react on their daily schedule if driving with a non-electric-car would cost a very, very high fee. Apart from the already used replanning modules from the previous lessons we would allow the agents to stay at home for the whole day rather than travelling around. In other words, we will extend the search space of the agents by another dimesion (activity chain dimension). Therefore,
MyPlanStrategyModule:
public class MyPlanStrategyModule implements PlanStrategyModule {
public MyPlanStrategyModule(Controler controler) {}
@Override
public void prepareReplanning() {}
@Override
public void handlePlan(Plan plan) {
for (int i=plan.getPlanElements().size()-1; i>0; i--) {
plan.getPlanElements().remove(i);
}
}
@Override
public void finishReplanning() {}
}
MyPlanStrategy:
public class MyPlanStrategy implements PlanStrategy {
PlanStrategy planStrategyDelegate = null ;
public MyPlanStrategy(Controler controler) {
planStrategyDelegate = new PlanStrategyImpl( new RandomPlanSelector() );
MyPlanStrategyModule mod = new MyPlanStrategyModule(controler) ;
addStrategyModule(mod) ;
}
@Override
public void addStrategyModule(PlanStrategyModule module) {
planStrategyDelegate.addStrategyModule(module);
}
@Override
public int getNumberOfStrategyModules() {
return planStrategyDelegate.getNumberOfStrategyModules();
}
@Override
public void run(Person person) {
planStrategyDelegate.run(person);
}
@Override
public void init() {
planStrategyDelegate.init();
}
@Override
public void finish() {
planStrategyDelegate.finish();
}
@Override
public PlanSelector getPlanSelector() {
return planStrategyDelegate.getPlanSelector();
}
@Override
public String toString() {
return planStrategyDelegate.toString();
}
}
public MyPlanStrategy(Controler controler) Constructor, since there, the strategy to use our replanning module is defined. Try to understand what happen there.MyFirstControler, we just define the strategy in the config.xml file:
<module name="strategy">
<param name="maxAgentPlanMemorySize" value="5" />
<param name="ModuleProbability_1" value="0.7" />
<param name="Module_1" value="BestScore" />
<param name="ModuleProbability_2" value="0.1" />
<param name="Module_2" value="ReRoute" />
<param name="ModuleProbability_3" value="0.1" />
<param name="Module_3" value="TimeAllocationMutator" />
<param name="ModuleProbability_4" value="0.1" />
<param name="Module_4" value="tutorial.MyPlanStrategy" /> <!-- !!!HERE!!! -->
</module>
eCar custom attribute play?The last question above can be answered by "No role at all!". This is clear recalling that MATSim's relaxation process is an evolutionary algorithm. Therefore, the agent behavior lies in the utility function (fitness function of an EA). Our replanning module play only the role of a mutation operator of the EA.
public class ECarScoringFunction implements BasicScoring {
private double score = 0;
private Plan plan;
private ObjectAttributes agentAttributes;
private static final double UTIL_OF_USING_NON_ECAR = -100.0;
public ECarScoringFunction(Plan plan, ObjectAttributes agentAttributes) {
this.plan = plan;
this.agentAttributes = agentAttributes;
}
@Override
public void finish() {
boolean usesCar = false;
for (int i=1; i<plan.getPlanElements().size(); i=i+2) {
Leg leg = (Leg)plan.getPlanElements().get(i);
if (leg.getMode().equals(TransportMode.car)) { usesCar = true; }
}
if (usesCar) {
if ((Boolean)agentAttributes.getAttribute(plan.getPerson().getId().toString(),CreateAgentAttributes.ECAR_ATT)) {
this.score += 0;
}
else {
this.score += UTIL_OF_USING_NON_ECAR;
}
}
}
@Override
public double getScore() {
return this.score;
}
@Override
public void reset() {
this.score = 0;
}
}
Next, we want to add this term to the default scoring function called CharyparNagelScoringFunction which is created by the CharyparNagelScoringFunctionFactory. Therefore, we need to extend this factory:
public class ECarScoringFunctionFactory extends CharyparNagelScoringFunctionFactory {
private final ObjectAttributes agentAttributes;
public ECarScoringFunctionFactory(PlanCalcScoreConfigGroup config, ObjectAttributes agentAttributes) {
super(config);
this.agentAttributes = agentAttributes;
}
@Override
public ScoringFunction createNewScoringFunction(Plan plan) {
ScoringFunctionAccumulator scoringFunctionAccumulator = (ScoringFunctionAccumulator)super.createNewScoringFunction(plan);
scoringFunctionAccumulator.addScoringFunction(new ECarScoringFunction(plan,agentAttributes));
return scoringFunctionAccumulator;
}
}
ECarScoringFunctionFactory. That you have already seen in Lesson 6.4. We will do the same in MyFirstControler:PlanCalcScoreConfigGroup planCalcScoreConfigGroup = controler.getConfig().planCalcScore(); ECarScoringFunctionFactory factory = new ECarScoringFunctionFactory(planCalcScoreConfigGroup,agentAttributes); controler.setScoringFunctionFactory(factory);
agentAttributes yet. Well, simply define it before and fill it with the data from our agentAttributes.xml file created before:
ObjectAttributes agentAttributes = new ObjectAttributes();
new ObjectAttributesXmlReader(agentAttributes).parse("./input/agentAttributes.xml");
Please note, that this example is very simplified and quite artificial but it shows the priniple concept of the plug-and-play functionalities of MATSim.
org.matsim.evacuation packageIn this tutorial we want to simulated the evacuation by car of an area in Berlin where the laboratories of the VSP working group are located. The area looks like a peninsular separated by the river Spree and Landwehrkanal. In this scenario it is assumed that the evacuees can leave the area via three different bridges (Dove bridge, March bridge and Gotzkowsky bridge). Area details are shown in the screenshots below.
Ok, here we go:
As for every other MATSim scenario we need a network.xml. This input file can be generated from openstreemap data.

map.osm. This file, however, can not be used with MATSim directly. We first have to converted into a MATSim compatible format.map.osm file into a network.xml file as described in Demand and Supply: Networkorg.matsim.evacuation.tutorial.NetworkFromOSM. You can run it by entering:
java -cp <MATSim release file> org.matsim.evacuation.tutorial.NetworkFromOSM \
<path to osm input file> <path to network.xml output file>network.xml is still not very useful for an evacuation simulation. This is because the multi-destination evacuation problem has to be transformed in a single-destination problem. Meaning we have to connect all links that lead out of the evacuation area to a super sink where we can route to. Therefore we have to define the evacuation area in a separate xml file.map.osm into qgis





evacuationArea.shp
java -cp <MATSim release file> org.matsim.evacuation.tutorial.EvacuationAreaGenerator \
<path to network.xml> <path to path to evacuationArea.shp> <path to output evacuationarea.xml>
Since we do not have real population data for the given area we invent a population. Let's say there are 5000 people with car that have to evacuate. Furthermore let's assume the car are some how equal distributed over the evacuation area.
java -cp <MATSim release file> org.matsim.evacuation.tutorial.PopulationGenerator \
<path to evacuationArea.shp> <path to network.xml> \
<path to output population.xml> <number of evacuees>The <code>config.xml</code> wraps the paths of the input files and simulation specific parameters together. Below a minimal sample config is given. In order to functioning the paths to the input directory and output directory have to be adapted:
<?xml version="1.0" ?> <!DOCTYPE config SYSTEM "http://www.matsim.org/files/dtd/config_v1.dtd" [ <!ENTITY INPUTBASE "/home/laemmel/arbeit/evacuationTutorial/"> <!ENTITY OUTPUTBASE "/home/laemmel/arbeit/evacuationTutorial/output/"> ] > <config> <!-- ====================================================================== --> <module name="qsim"> <param name="endTime" value="09:00:00" /> </module> <!-- ====================================================================== --> <!-- Params for EvacuationQSimControler --> <module name="evacuation"> <param name="inputEvacuationAreaLinksFile" value = "&INPUTBASE;/evacuationarea.xml"/> </module> <!-- ====================================================================== --> <module name="controler"> <param name="outputDirectory" value="&OUTPUTBASE;" /> <param name="eventsFileFormat" value="xml" /> <param name="firstIteration" value="0" /> <param name="lastIteration" value="0" /> </module> <!-- ====================================================================== --> <module name="plans"> <param name="inputPlansFile" value="&INPUTBASE;/population.xml" /> </module> <!-- ====================================================================== --> <module name="network"> <param name="inputNetworkFile" value="&INPUTBASE;/network.xml" /> </module> <!-- ====================================================================== --> <module name="planCalcScore"> <param name="BrainExpBeta" value="10" /> <param name="traveling" value="-6" /> <!-- Activity indices (the numbers after the '_') go from 0 to n. The ordering doesn't matter. --> <param name="activityType_0" value="h" /> <!-- home --> <param name="activityPriority_0" value="1" /> <param name="activityTypicalDuration_0" value="12:00:00" /> <param name="activityMinimalDuration_0" value="08:00:00" /> </module> <!-- ====================================================================== --> <module name="strategy"> <param name="maxAgentPlanMemorySize" value="4" /> <!-- 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" /> </module> <!-- ====================================================================== --> </config>
java -cp <MATSim release file> org.matsim.evacuation.run.EvacuationQSimControler <path to config.xml>
For simulating public transport (pt) in MATSim, you need:
In the following, those topics are described in more details. At the end of this tutorial, you find some example files that you can directly use to run a public transport simulation.
Each link has a list of available transport modes. If no modes are specified, the simulation assumes that only "car" is allowed on such links. For public transport, you can add links with modes="train" or modes="bus", for example. It is also possible that links support more than one transport mode, e.g. modes="car,bus".
... <links capperiod="1:00:00"> <link id="1" from="1" to="2" length="1000.00" capacity="2000" freespeed="12" permlanes="1" modes="car" /> <link id="101" from="101" to="102" length="1000.00" capacity="2000" freespeed="12" permlanes="1" modes="bus" /> <link id="201" from="201" to="202" length="1000.00" capacity="2000" freespeed="12" permlanes="1" modes="train" /> <link id="301" from="301" to="302" length="1000.00" capacity="2000" freespeed="12" permlanes="1" modes="bus,tram" /> ...
The description of pt vehicles can be split into two parts: In a first part, vehicle types have to be described, specifying how many passengers such a vehicle can transport (Note that the term "vehicle" can refer to multiple vehicles in reality, e.g. a train with several wagons should be specified as one long vehicle with a high number of seats). In the second part, actual vehicles have to listed. Each vehicle has an identifier and is of a previously specified vehicle type.
<vehicleType id="1">
<description>Small Train</description>
<capacity>
<seats persons="50"/>
<standingRoom persons="30"/>
</capacity>
<length meter="50.0"/>
</vehicleType>
<vehicle id="tr_1" type="1"/>
<vehicle id="tr_2" type="1"/> In the first part, the stop locations need to be defined, giving each a coordinate, an identifier and a reference to a link in the network. The stop can only be served by vehicles driving on that specified link.
<transitStops> <stopFacility id="1" x="1050" y="1050" linkRefId= "11"/> <stopFacility id="2" x="2050" y="2940" linkRefId= "24"/> ...
Optionally, one can also specify a name for the stop and if other vehicles are blocked when a pt vehicle is waiting at a stop. This last attribute is useful to model e.g. the difference of bus stops, where one bus stop has a bay, while at another stop, the bus has to stop on the actual road.
<transitStops> <stopFacility id="1" x="1050" y="1050" linkRefId= "11" name="2nd Street" isBlocking="true" /> <stopFacility id="2" x="2050" y="2940" linkRefId= "24" name="Main station" isBlocking="false" /> ...
After the stop locations, the different pt lines, their routes and schedules are described:
<transitLine id="Blue Line">
<transitRoute id="1to3">
<transportMode>train</transportMode>
<routeProfile>
<stop refId="1" departureOffset="00:00:00"/>
<stop refId="2" arrivalOffset="00:03:20" departureOffset="00:04:00"/>
<stop refId="3" arrivalOffset="00:07:20" departureOffset="00:10:00" awaitDeparture="true"/>
...
<stop refId="n" arrivalOffset="00:28:00" />
</routeProfile>
<route>
<link refId="11"/>
<link refId="398"/>
<link refId="24"/>
...
<link refId="130"/>
</route>
<departures>
<departure id="01" departureTime="06:00:00" vehicleRefId="tr_1" />
<departure id="02" departureTime="06:15:00" vehicleRefId="tr_2" />
...
</departures>
</transitRoute>
</transitLine>The transportMode describes on which links in the network this line runs.
The routeProfile describes the stops this route serves, while the route itself describes the series of links in the network the pt driver has to drive along. All the specified stops should occur along this route in the specified order. Details:
departureOffset and arrivalOffset refer to departureTime in "departures".arrivalOffset="00:03:20" means an arrival at "06:00:00"+"00:03:20", i.e. at "06:03:20". Or at "06:15:00"+"00:03:20", i.e. at "06:18:20".departureOffset="00:04:00" means departures at "06:04:00" and "06:19:00".departureOffset is required for all stops except the last onearrivalOffset is optional for all stops except the last oneawaitDeparture specifies that a transit driver should wait until the scheduled departure time if it is early at the stop. This is useful to ensure connections at larger stops.The departures list the time, when a vehicle departs at the first specified stop. It also specifies, with which vehicle (defined in the file previously mentioned) the route is served.
In the configuration, you have to enable the simulation of public transport:
<module name="scenario"> <param name="useTransit" value="true" /> <param name="useVehicles" value="true" /> </module>
You have to use a mobility simulation that support public transport, currently this is only the so-called "QSim".
<module name="qsim"> <param name="startTime" value="00:00:00" /> <param name="endTime" value="30:00:00" /> </module>
(If you have an existing config file with a module named "simulation", you can just rename "simulation" to "qsim" to ensure that QSim is used). It is strongly advised that you specify an end time for the simulation. Sometimes, if agents are too late, they arrive at pt stops way after the last bus/train/... departed and will thus wait at the station forever, and the simulation will also run forever.
The controler should write files in xml-format, as only this format supports the additional pt events:
<module name="controler"> <param name="eventsFileFormat" value="xml" /> </module>
For replanning, if you use TimeAllocationMutator, you have to use a special transit-aware version of it:
<module name="strategy"> <param name="ModuleProbability_*" value="0.1" /> <param name="Module_*" value="TransitTimeAllocationMutator" /> </module>
If you want the agents to perform mode choice, add the mode choice replanning module:
<module name="strategy"> <param name="ModuleProbability_*" value="0.1" /> <param name="Module_*" value="TransitChangeLegMode" /> </module>
This replanning module needs additional configuration:
<module name="changeLegMode"> <param name="modes" value="car,pt" /> </module>
Last but not least, you have to specify the paths to the additional pt-related input files:
<module name="transit"> <param name="transitScheduleFile" value="transitschedule.xml" /> <param name="vehiclesFile" value="transitVehicles.xml" /> <param name="transitModes" value="pt" /> </module>
The pt simulation generates additional events related to the public transport:
TransitDriverStarts: This contains information about which driver departs at what time, specifying the transit vehicles the driver steers and along which line and routeVehicleArrivesAtFacility, VehicleDepartsAtFacility: contains information when a transit vehicle arrives and departs at a stop facilityPersonEntersVehicle, PersonLeavesVehicle: contains information about passengers entering and leaving transit vehiclesThese events allow you to build your own analyses, e.g. the number of passengers entering and leaving per stop facility, the average load of transit vehicles, etc.
The following steps allow you to run the provided example simulation:
pt-tutorial" within the release-directory. The directory "pt-tutorial" should be on the same level as the "matsim-0.2.0.jar" or the "libs" directory included in the release.pt-tutorial" directoryjava -Xmx512m -cp matsim-0.2.0.jar org.matsim.run.Controler pt-tutorial/config.xml
output/pt-tutorial, so make sure the output-directory exists (create it if missing) and is empty.
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.
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".
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.
Alternative material that seems to fit into the 2011-04 tutorial but that was not used.
Presenter: A. Horni
Lecture type: Presentation with exercises
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)

d) Configure a ZH simulation based on network.xml such that counts are plotted only within a restricted area: center ~ Bellevue and radius = 5km.
Download the files
Inspect the network nodes (nodes.* , zh.tif) by GIS and define the count section of the configuration file (see Section Parameters).
Run playground.anhorni.kti.CountsAnalyser with linkstats.txt
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.
MATSim uses the JFreeChart library to generate 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.
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).
Some tutorial version of unknown lineage
Presenter: Nadine Schüssler
Lecture type: Presentation
Presenters: C. Dobler and F. Ciari
Lecture type: Presentation with exercises
...
The process of creating an initial demand (the "population" of the scenario) can be quite challenging, 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.
NOTES:
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.
NOTES:
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. When you run MATSim, it will automatically reference all activities with their nearest link. The plans file which MATSim puts in its output directory will contain the link ids for all activities, as well as routes for all legs.
In most situations, you will not create a plans file by hand, but write a Java program which generates it from some data source or by some algorithm. See matsim.org/node/340.
Presenter: A. Horni
Lecture type: Presentation with exercises
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.
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)

Presenter: R.A. Waraich
Lecture type: Presentation with exercises
...
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.
Instructor: M. Rieser
Co-instructors: D. Grether, A. Horni
Lecture type: Presentation with exercises
Learning Objectives:
Exercises:
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.
Presenter: (not assigned)
Lecture type: Presentation
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 fit all togehter.
As of now the following tutorial is deprecated since it refers to an earlier version of MATSim. An update for this tutorial is not available at the moment. This is partly because we had to make a lot of adaptations of the evacuation package for the Padang project. Through these adaptations, however, the package is no longer useable in a generic way. We are working hard to provide a functioning evacuation tutorial in future.
This tutorial describes the EvacuationQueueSimulation. Because the evacuation package is not part of the current release you have to checkout MATSim from SVN.