Tutorials

We have prepared some tutorials which should help you getting started with MATSim.

Learning MATSim in 3 Days: Tutorial for the Annual MATSim User Meeting

MATSim Meeting 2009 in Berlin
MATSim Meeting 2010 in Zürich

Tutorial 2010 Video

01 - Installation & Getting started

Instructor: K. Meister
Co-instructors: R. Waraich, C. Dobler

Learning goals

The tutorial participants will ...

  • get in touch with the MATSim software: First, guided looks at networks, plans, config files, OTFVis etc.
  • learn to use MATSim with the Eclipse IDE: Run controler, run visualizer, view XML files etc.
  • learn to overcome hard-/software problems with own computer when using MATSim with Eclipse

Get started here!

1) Introduction

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 Overview

Prerequisites

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:

  • Operating system
    You can use the operating system of your own choice for which Java and Eclipse are available (e.g. Windows XP and above, Mac OS X, GNU/Linux). Make sure you have administrative rights for your computer. They might be required for the installation of a missing program or the modification of some computer setting.
  • Web browser
    Make sure a web browser such as Mozilla Firefox is installled on your laptop.
  • File archiver
    A program to handle file archives (*.zip, *.gz) is required. While such a tool is typically bundled with Mac OS X and GNU/Linux, it has to be manually installed for Windows. A recommended tool for Windows is 7-Zip.
  • Java
    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. It is best to use the JDK from the beginning. Download and install the newest version of the "Java SE Development Kit" (JDK 6.0 Update xy) from java.sun.com.
  • Eclipse
    This guide uses the Eclipse Integrated Development Environment (IDE) as an interface to the MATSim software, as well as as input and ouput files. Download and install Eclipse from eclipse.org. The package "Eclipse IDE for Java Developers" is sufficient for our needs.
  • Google Earth
    MATSim is able to generate output in the format of *.kmz files which can be viewed with Google Earth. Download and install the latest version from earth.google.com.

Furthermore, an active internet connection is required to successfully run the examples in the subsequent sections.

Using MATSim with Eclipse

This  version of the tutorial matches the code in the MATSim Spring 2010 release. The version number is 0.1.x, with 'x' being the number of latest official bugfix release. Make sure always to use the latest bugfix release. For reasons of simplicity, we use the string "matsim-0.1.x" when the version number is referred to.

In order to access code and data, the Eclipse IDE is used instead of the command line. Take the following steps in order install MATSim in Eclipse.

  • Download the current release (matsim-0.1.x.zip, replace x with the number of the bugfix release) from the sourceforge download page and save it on your desktop.
  • Unzip the file. A folder (matsim-0.1.x) appears.
  • Start Eclipse.
  • Start a new Java Project: Click File -> New -> Java Project
  • Choose a project name, e.g. matsim-0.1.x
  • Choose "Create project from existing source", and set the directory to the matsim-0.1.x folder on your desktop.
  • Make sure a JRE/JVM 6 is set in section JRE.
  • Click Next.
  • In the "Java Settings" dialogue, click the Libraries tab.
  • Make MATSim source code visible in Eclipse:
    • In the JARs list, choose matsim-0.1.x-sources.jar and click Remove.
    • In the JARs list, choose matsim-0.1.x.jar and expand it.
    • Click Source attachment: (None), then click Edit....
    • Click Workspace....
    • Choose matsim-0.1.x/matsim-0.1.x-sources.jar, then click OK.
  • Set the native Java-OpenGL library for the visualization used later in this guide:
    • In the JARs list, choose the JRE System Library and expand it.
    • Click Native library location: (None), and click Edit....
    • Click Workspace....
    • Depending on your operating system (OS) and your machine type (MACHINE), choose matsim-0.1.x/libs/jogl-1.1.1/jogl-1.1.1-OS-MACHINE/lib.
    • Click OK.
  • Click 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.

  • read the release notes (README.txt, CHANGELOG.txt)
  • conveniently browse the source code of MATSim (packages in Referenced Libraries - matsim-0.1.x.jar). For this, make sure that the package presentation is hierarchical: Click the small triangle at the top right of the Package Explorer, then choose Package presentation - Hierarchical.

Next, we take a look at an example scenario.

2) Scenarios

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).

Networks

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.

Visualising a network

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,

  • Navigate to Referenced Libraries - matsim-0.1.x.jar.
  • Right-click on it, choose Run As - Java Application.
  • In the topmost field, start typing "OTFVis". Executable classes with a name matching your input remain in the Matching items list below.
  • Make sure OTFVis is selected in this list.
  • Click OK.
  • A file-open dialog appears. Select MATSim net or config file (*.xml).
  • Navigate the network.xml file mentioned above in your matsim-0.1.x folder.

After a moment, you will see the network visualized. If the network is not visible or any other problem occurs, information about the problem can be found in the console output which is displayed at the bottom right of the Eclipse workspace. In this case, you may re-run the visualization by choosing Run - Run History - OTFVis.

Now you can also configure the visualizer further, e.g. by changing the colors of the links or by displaying their names. Read more about the usage options of OTFVis here and about technical issues here.

Plans

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/

A single iteration

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:

  • Navigate to Referenced Libraries - matsim-0.1.x.jar.
  • Right-click on it, choose Run As - Java Application.
  • In the topmost field, start typing "MyControler1". Again, executable classes with a name matching your input remain in the Matching items list below.
  • Make sure MyControler1 - tutorial.config.example1mobsim is selected.
  • Click 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

  • some basic statistics across iterations, e.g. aggregate score information in the file scorestats.txt,
  • a logfile of the console output in logfile.log, and
  • a folder named ITERS where MATSim writes the output files of the iterations.

In 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:

  • From the menu, choose Run - Run Configurations... (Eclipse 3.5) or Run - Open Run Dialog... (Eclipse 3.3)
  • In the list of run configurations on the left side, choose Java Application - MyControler2.
  • Select the Arguments tab.
  • In the text field labeled VM arguments, type "-Xmx512M".
  • Click 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.

3) Running iterations

Iterations

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.

  • Re-run OTFVis by selecting Run - Run History - OTFVis
  • As the file format, make sure OTFVis movie file (*.mvi) is selected.
  • Navigate to output/example5/ITERS/it.10/10.otfvis.mvi in your matsim-0.1.x folder and click Open. The OTFVis starts.
  • Click the play button to visualize the traffic along the timeline, and modify the layout via the 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.

Modifying the Re-Planning

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.

  • The 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:

  • ModuleProbability_1 to a lower value, e.g. 0.1
  • ModuleProbability_2 to a higher value, e.g. 0.9.

Run the simulation again and look at some consecutive iterations in the visualizer. What effect can you observe?

Trip based iterations

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.

4) Running your own configurations

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.

  • Create a copy of example5-config.xml in the same folder. Name the copy example5-config-2000agents.xml
  • Open the new config file.
    • In the plans module, change the value of the parameter inputPlansFile to:
      "./examples/equil/plans2000.xml.gz
      "
      This tells the controler to use a different initial plans file with 2000 agents provided in the official release.
    • In the controler module, change the value of the parameter outputDirectory to:
      "./output/example5-2000agents"
    • In the module controler, increase the value of the parameter lastIteration from 10 to 50. The learning procedure will have progressed substantially after 50 iterations.
    • In the 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 your new configuration:
    • In the menu, select Run - Run Configurations... (or Run - Open Run Dialog...).
    • In the list on the left side, select Java Application.
    • Click the blank sheet/plus symbol in the left upper corner (New launch configuration).
    • In the Main class dialog, click Search....
    • Start typing "Controler". Make sure to select Controler - org.matsim.run from the Matching items list, and click OK.
    • In the Name: field, type a descriptive name for this run, e.g. "Controler - 2000 agents".
    • Click the Arguments tab.
    • In the Program arguments text field, paste the following text:
      examples/tutorial/config/example5-config-2000agents.xml
    • Click Run. Wait for the 50 iterations to finish successfully.
  • Now let's manually generate the OTFVis visualization of the results of the last iteration:
    • In the menu, select Run - Run Configurations... (or Run - Open Run Dialog...).
    • In the list on the left side, select Java Application - OTFVis. If this item is not available, generate a new launch configuration as described above, choosing OTFVis as the main class.
    • Click the copy symbol on top of the list of the left side.
    • In the Name: field, type "OTFVis - convert".
    • Click the Arguments tab.
    • In the 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
    • In the VM arguments tab, paste the following text:
      -Xmx512M
    • Click Run.
  • Run OTFVis as before, opening the file output/example5-2000agents/ITERS/it.50/50.otfvis.mvi in order to visuallize the result of iteration 50.
  • Generate mvi files also for the results of other iterations, e.g. every 10th iteration, and compare them to each other.

5) Basic analysis

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

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.

6) What's next?

Congratulations! You have just run your first MATSim scenarios. Depending on your interest, you might continue with one of the following options:

  • Run your own scenario
    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.
  • Generate custom analyses
    Read more in the Events Programming tutorials.
  • Generate custom simulations
    Read more in the Controler Programming tutorials.
  • Read about MATSim
    See the reference list at the end of this page.
  • Stay up-to-date about MATSim
    by subscribing to one or more of our mailing lists.

If you wish access to different/more recent versions of the MATSim software then just the official release, consider the two following options:

  • Use a nightly build.
  • Directly access the SVN repository at Sourceforge, as described here.

References

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.

02 - Introduction & Overview

Instructor: M Balmer
Co-instructors: F. Ciari, M. Zilske
Lecture type: Presentation
You will learn: A short theoretical overview of what's coming in the next two days

03 - Demand and Supply: Network

0. Introduction

Instructor: Michael Zilske
Co-instructors: Francesco Ciari, Christoph Dobler
Lecture type: Presentation with exercises

 

  • Visit http://download.geofabrik.de/osm/europe/ and download the switzerland.osm.bz2 file. Unpack it using a bunzip2 utility for your platform.
  • Visit 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.
  • Visit OpenStreetMap and, using the export tab, select a region of interest. In this tutorial, we will use the Zurich metropolitan area. Make note of the coordinates.
  • Create an OpenStreetMap excerpt containing only roads within the region of interest. Try this command line:
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
  • Create another excerpt containing only big roads, but this time without any geographic constraints:

osmosis --rx file=switzerland.osm --tf accept-ways highway=motorway,motorway_link,trunk,trunk_link,primary,primary_link --used-node --wx switzerland-bigroads.osm
  • Merge the two networks using the following command:
osmosis --rx file=switzerland-bigroads.osm --rx zurich.osm --merge --wx merged-network.osm
  • Use a bit of Java code to convert the merged OpenStreetMap network to the MATSim format like this:
String osm = "merged-network.osm";
Scenario sc = new ScenarioImpl();
Network net = sc.getNetwork();
CoordinateTransformation ct = 
TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84, TransformationFactory.WGS84_UTM35S);
OsmNetworkReader onr = new OsmNetworkReader(net,ct);
onr.parse(osm); 
new NetworkWriter(net).write("network.xml");	
  • Use OTFVis to view your network. Congratulations.

035 - Preparing an Initial Demand

The process of creating an initial demand (the "population" of the scenario) can be quiet challanging, as a lot of different data sources may be used, depending on what's available. The good thing about MATSim is, that you can start with a fairly simple initial demand and improve it later.

Initial Plans

A simple description of agents is as follows:

 <person id="1">
  <plan>
    <act type="home" x="20" y="-5" end_time="06:00:00"  />
    <leg mode="car"  />
    <act type="work" x="80" y="5" end_time="16:00:00"  />
    <leg mode="car"  />
    <act type="home" x="20" y="-5"  />
  </plan>
</person> 

Each person needs a unique identifier id and at least one plan. The plan contains acts and legs. The activities need at least the type, a coordinate-pair (x, y), and an end time (end_time). Legs between activities need a mode, usually set to "car", but do not need any route information at this stage.

NOTE: There is also an activity duration attribute.  At this point (may'10), this is essentially deprecated (because the functional differentiation between "dur" and "end_time" did not work that well).

Trip-based initial demand

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.

Activity end times

end_time does not have to be an exact value; with certain set-ups, the simulation can modify these attributes to find better values on its own.

On the other hand, if you are coming from time-dependent OD matrices, you should  "smear out" the activity end times (= trip departure times) over the time period of the validity of the matrix, and then not use the "TimeAllocationMutator" later.

The simulation expects all activities to take place on links. To assign each activity a link based on its coordinates, use the tool org.matsim.run.XY2Links. As an argument, pass it a configuration file which contains the information about the network, input-plans and output-plans, e.g.:

java -cp <class-to-matsim-jar>/matsim.jar org.matsim.run.XY2Links config.xml

The tool will then read all plans from the input-file and search for each activity the nearest link from the network. The plans with this additional information are then written to the output-file. That output-file could then be used to start the simulation with org.matsim.run.Controler (see the Getting-Started Tutorial).

Attached are a very small sample network, a very simplistic plans file and a configuration file that can be used with XY2Links.

More complicated situations

In more complicated situations, it often makes sense to program the initial demand generation in Java.  See matsim.org/node/340.

04 - Demand and Supply: Population

0. Introduction

Instructor: Francesco Ciari, Christoph Dobler
Co-instructor: Michael Zilske
Lecture type: Presentation with exercises

You will learn:

  • Knowing the entry points in the software to create a synthetic population and the associated travel demand
  • Having an idea, where to get the data to build an own scenario

1. Minimal Scenario

You should already have seen the following for a relatively "minimalistic" introduction: matsim.org/node/110 .  Contains information about how to map coordinate-based activity locations to links ("XY2Links").

2. Using the MATSim Data Containers 

3. Data Sources: Example CH

4. From Data to Containers: Initial Demand Generation

matsim.org/node/340

matsim.org/uploads/320/data_conversion_demand_modelling_gis_49fdc6ca54.pdf 

05 - Config Parameters

0. Introduction

Instructor: R. Waraich
Co-instructors: C. Dobler, M. Zilske
Lecture type: Tutorial
You will learn:

  • Meaning of additional configuration parameters
  • Calibration (e.g. flowCapacityFactor and storageCapacitiyFactor)

Try it out yourself...

01 - Introduction

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.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

02 - Calibration

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.

  • Try it out yourself: Look at the mentioparameters in the network file located at "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.

  • Try it out by changing the configuration parameters:
    • Open the configuration file "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.
    • Inorder to use a larger population (2000 agents), change the value of the parameter "inputPlansFile" to "examples/equil/plans2000.xml.gz".
    • Add the strategy module with the following settings:
    	<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>
    • Change the value of "lastIteration" to 10 in the configuration file
    • Run MyControler1
    • Now change the value of the parameter "outputDirectory" to "./output/example1_2"
    • Then set both scaling factors to 0.1 as shown below (by adding the "simulation" module)
 	<module name="simulation">
		<param name="flowCapacityFactor" value="0.1"   />
		<param name="storageCapacityFactor" value="0.1"   />
	</module>
  • Now run 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:

  • One way to improve performance is by turning off outputs, which are not nessecary for this excercise. For example the events file should not be written out after each iteration (located at "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" />
  • Furthermore, for this excercise a different (and faster) micro-simulation can be used by changing the module name from "simulation" to "JDEQSim". A documentation of this micro-simulation called JDEQSim is found here.
  • Often the performance can be further increased by adding a module called "parallelEventHandling" into the configuration file (see below), if your machine has more than one CPUs/core available. The documentation of this module is available here. The meaning and importance of event handling will be explained later in the tutorial.
    	<module name="parallelEventHandling">
        	<param name="numberOfThreads" value="1" />
    	</module>
  • Change the values of both scaling factors to 1.0.
  • Change the value of the parameter "outputDirectory" to "./output/example1"
  • Change the value of "lastIteration" to 50 in the configuration file
  • Run MyControler1
  • You can see how the score in MATSim develops over 50 iterations, by looking at the following output file "output/example1/scorestats.png"

Now you are ready to start with the calibration excercise (see next chapter).

 

 

03 - Exercise 1

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:

  • The calibrated "storageCapacitiyFactor" is between 0.5 and 1.0 and the "flowCapacityFactor" between 0 and 0.5.
  • Tryout changing the scaling factors separatly to find out what effect they have.
  • When you have found the calibarted factors, als look at the score file located at "output/example1/scorestats.png"

 

 

 

04 - Exercise 2

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).

  • Change the values of both scaling factors to 0.2.
  • Run MyControler1 (for 50 iterations)
  • Now change the value of the parameter "outputDirectory" to "./output/example1_4"
  • Set the value of the paramter "ModuleProbability_3" to "0.001"
  • Run MyControler1 (for 50 iterations)
  • Now change the value of the parameter "outputDirectory" to "./output/example1_5"
  • Set the value of the paramter "ModuleProbability_3" to "0.1"
  • Set the value of the paramter "ModuleProbability_2" to "0.001"
  • Change the value of "lastIteration" to 200 in the configuration file
  • Run MyControler1 (for 200 iterations)
  • Compare the scores of the both runs (found in "output/example1/scorestats.png", "output/example1_4/scorestats.png" and "output/example1_5/scorestats.png").
  • Compare also the leg histograms (between the runs and also the different iterations of the last run).

What do you observe? What can we learn from this?

 

06 - Looking Closer at Simulation Results: Analysis, Validation and Visualization

0. Introduction

Instructor: A. Horni
Co-instructors: F. Ciari, D. Grether
Lecture type: Presentation with exercises


Learning Objectives:

  • Creating and analyzing traffic count comparisons
  • Getting a rough idea of further validation measures
  • Using the On-The-Fly-Visualizer (OTFVis)

 

Slides

Content:

 

Find this tutorial @: http://www.matsim.org/node/412

 

1. Traffic Counts 

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:

  • Include variance, max, min, median in station plots not only average value
  • Include length and vehicle type classes (e.g., trucks vs. motorcycles) in station plots.

1.1 Output Formats 

  • Tables in text files:

  • KML file for Google Earth:

 

  • HTML to browse the count stations by link:

 

1.2. Preprocessing

Example CH:

 

 

 

1.3 Parameters 

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]

1.4. Post Creation 

Take ...

playground.anhorni.kti.CountsAnalyser or
playground.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)

 

2. Validation Issues 

2.1.Further Validation Measures: Examples 

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

Wechsler

 


Spideranalysis

Example.: Westumfahrung ZH, 2009

 Spinne

 

Volumes

Example.: Westumfahrung ZH, 2009

 

 

2.2. Problem and Future Work

  • Lack of Validation Data and System Specification
    • Level of analysis and modeling (e.g. count data vs. avg. trip length, route switcher analysis etc.)
    • Ensemble runs ?  confidence intervals etc. (computational costs!)

 

  • Future Measures
    • Travel speeds (e.g., based on GPS data)
    • Facility loads (e.g., based on license plate data or retailer consumer card data)

 

=> A lot of interesting future work!

 

3. Visualizers  

                                                        

OTFVis user guide

OTFVis presentation 2009

 

Exercises: 

1. OTFVis

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

Hints:

  • Compare 2 Westumfahrung runs simultaneously with OTFVis. Use wuIST.mvi (base case) and wuWU.mvi (with bypass).
  • Run OTFVis as follows:

 

 

2. Google Earth 

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)

 

07 - Real-World Case Study: Westumfahrung Zürich

Instructor: M. Balmer
Co-instructors: F. Ciari, D. Grether
Lecture type: Presentation
You will learn: Putting it all together. The "Westumfahrung" of Zurich City is used as a real world case study to show, how the steps learned in the tutorial can be used for your own application. 

08 - Programming With JAVA: Events

0. Introduction

Instructor: D. Grether
Co-instructors: M. Rieser, A. Horni
Lecture type: Presentation with exercises
Learning Objectives:

  • What are Events? How works the Model View Controller Pattern in general.
  • How you can analyse simulation output.
  • How to write an event handler for the events of the mobility simulations.
  • How to produce simple charts.

Exercises:

  • Write a very simple event handler producing log output to console.
  • Write a simple event handler calculating total and average travel times.
  • Write a chart writer class that plots the collected data to a chart. 

Teaching Material

  • matsim.org/node/351
  • Slides
  • Solutions for the exercises can be found in the class 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.

 

Programming Events

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.

MATSim 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.

 

1) Controler generated Analysis

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.

 

2) Handling Events

Event Structure

If you have looked at an event file, you will have noticed a column called Event Flag which lists different types of events. Each event type is characterized by the agents' action:

 Event Structure

 

Reading Events

In order to read events, you will need to implement certain EventHandlers from either of the following packages

org.matsim.core.api.experimental.events

org.matsim.core.api.experimental.events

or

org.matsim.core.events

org.matsim.core.events.handler

Creating an Event Handler

For the next steps, you should create (at least) two classes. One called MyEventHandling and another one implementing the actual Handlers, e.g. MyEventHandler1.
The class MyEventHandling contains the main-method and is thus executable:

 

public static void main(String[] args){
...
  //path to events file
  String inputFile = "output/ITERS/it.10/10.events.xml.gz";
  //create an EventsManager object
  EventsManager events = new EventsManagerImpl();
  //create the reader and read the file
  MatsimEventsReader reader =
        new MatsimEventsReader(events);
  reader.readFile(inputFile);
  System.out.println("Events file read!");
...
}

For now, this is not very useful, as MyEventHandler1 (of which we created an instance “handler” and registered it for the event) is not yet written, hence we will need to that.

The handler needs to implement the interfaces and should thus look like this:

public class MyEventHandler1 implements LinkEnterEventHandler,LinkLeaveEventHandler {
//or which Handler what ever is to be implemented
    public void handleEvent(LinkEnterEvent event) {
        //handle something
    }
    public void handleEvent(LinkLeaveEvent event) {
        //handle even more
    }
    public void reset(int iteration) {
        //reset something
    }
}
 

Now, try to create handlers which:

  • write the attributes of the LinkEnter- and LinkLeaveEvents to the console

  • Write an event handler that calculates total time agents spent on the road and the average travel time per agent under the assumption that the size of the population will be given as

parameter.

NB: You will find the solutions in
src/tutorial/programming/example6EventsHandling/MyEventHandler1.java
and MyEventHandler2.java

 

 

3) Creating Charts

MATSim
uses the JfreeChart library to gernerate charts (see

for additional information). The library is somewhat complex to
understand, but we have included the most useful tools in:

MATSim uses the JFreeChart library to gernerate charts (see http://www.jfree.org/jfreechart/ for additional information). The library is somewhat complex to understand, but we have included the most useful tools in:

org.matsim.core.utils.charts

A 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.

 

 

09 - Programming With JAVA: Controler

0. Introduction

Instructor: M. Rieser
Co-instructors: D. Grether, A. Horni
Lecture type: Presentation with exercises
Learning Objectives:

  • What is the role of the Controler in MATSim?
  • How can the Controler be configured?
  • How can functionality be added to a MATSim run?
     

Teaching Material

Slides: see below

matsim.org/node/355

Exercises:

  • Configure your own Controler that does not write Events in every iteration.
  • Write a Controler Listener that outputs a message at the end of each iteration.
  • Combine an EventHandler with a Controler Listener to output statistical information at the end of each iteration. 

Programming a Controler

Beside handling events with EventHandlers in the Events Tutorial, using Controlers is yet another powerful way of analysing data in MATSim.

1) Creating and Configuring

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 to
org.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.

 

2) Controler Listeners

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.

 

99 - Admin

Feedback Form

Additional tutorials

This section contains those tutorials that are not used at the annual tutorial.  The main reasons for this are: (i) too specialized; (ii) out of focus for intended user meeting audience.

Using DEQSim with MATSim

This tutorial is deprecated, since a version of DEQSim rewritten in Java is now available.

 

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".

Using Nightly Builds of MATSim

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.

Initial setup to use a MATSim nightly build

Using a nightly build of MATSim is as simple as following these 3 steps:

  1. Download the current MATSim jar-file (MATSim_r####.jar).
  2. Download the current collection of required 3rd-party libraries into the same directory as the MATSim jar-file (MATSim_libs_r####.zip).
  3. Unzip the collection of 3rd-party libraries, you should then get a directory 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.

Updating to a newer MATSim nightly build

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.

 

Running the nightly build as a shell script

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.

 

Evacuation Tutorial

This tutorial describes the EvacuationQueueSimulation. Because the evacuation package is not part of the current release you  have to checkout MATSim from SVN.

zz_old

Contains old material, left here for reference.

[Old] Getting Started with 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 integrate an external, custom mobility simulation,
  • how to integrate a custom, external re-planning module.

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:

  •     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 depending jar-files 

Also see here for more modern ways to obtain and install MATSim.  The tutorials have not yet been adapted.

1) Introduction

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.

 


2) Description of a Scenario

Note: "NetVis" is deprecated.  New tutorials are under construction, but not yet there.  kai, apr'10

A scenario consists of at least a network and a population with plans. The network is a repre­sentation 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 "equil" Scenario

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.

Running a Single Iteration

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 infor­mation 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.

Visualizing the Simulation-Results

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 dis­played 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.

Reading Events

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.

Modifying the Settings

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.

Running Multiple Iterations

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.

Modifying the Re-Planning

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.

3) Using an External Re-Planning Module

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:

  • Write the module in Java and make use of functionality provided by MATSim. In this case, you’re advised to integrate your module at code-level. This means you should be able to directly access and modify code of MATSim.
  • Write the module in Java or any other language independently of MATSim. Your module should then run stand-alone. This way, you could also just write a wrapper to use existing code.

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.*/)

4) Using an External Mobility Simulation

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.

5) Creating a Custom Controler

Note: All the following will probably work.  But it does not use the api, and so we make no promises regarding the future availability of the methods.  A new tutorial is under construction, but not there yet.  kai, apr'10

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.

Reading network and plans

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);

Setting up Events

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);

Running the Mobility Simulation

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.

Writing Visualizer Output

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.

Using Configuration Settings

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.

Scoring Plans

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.

Running Multiple Iterations

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.

Adding Re-Planning

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.

6) What's next?

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.

Getting Started with 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

 

1) Introduction

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 Overview

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.


 

 

2) Scenarios

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).

Networks

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.

Visualising a network

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

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.

 

3) Running Iterations

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/

A simple configuration

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

  • some basic statistics across iterations, e.g. aggregate score information in the file scorestats.txt,
  • a logfile of the console output in logfile.log, and
  • a folder named ITERS where MATSim writes the output files of the iterations.

In 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.

Iterations

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.

Modifying the Re-Planning

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.

  • The 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:

  • ModuleProbability_1 to a lower value, e.g. 0.1
  • ModuleProbability_2 to a higher value, e.g. 0.9.

Run the simulation again and look at some consecutive iterations in the visualizer. What effect can you observe?

Trip based iterations

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

Running your own configurations

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:

  • Create a copy of example5-config.xml in the same folder. Name the copy example5-config-2000agents.xml
  • Open the new config file.
    • In the plans module, change the value of the parameter inputPlansFile to:
      "./examples/equil/plans2000.xml.gz
      "
      This tells the controler to use a different initial plans file with 2000 agents provided in the official release.
    • In the controler module, change the value of the parameter outputDirectory to:
      "./output/example5-2000agents"
    • In the module controler, increase the value of the parameter lastIteration from 10 to 50. The learning procedure will have progressed substantially after 50 iterations.
    • In the 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 your new configuration with the command:
    java -cp MATSim.jar -Xmx512M org.matsim.run.Controler examples/tutorial/config/example5-config-2000agents.xml
  • Manually generate the OTFVis visualization of the results of the last iteration by running:
    java -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 60
  • Run OTFVis as before, opening the file output/example5-2000agents/ITERS/it.50/50.otfvis.mvi.
  • Generate mvi files also for the results of other iterations, e.g. every 10th iteration, and compare them to each other.

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.

 

4) Basic Analysis

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

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.

 

5) What's next

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.

Using the Nightly Build

If you plan to use the nightly build rather than the release, you are highly recommended to read this page.

Including MATSim in Eclipse

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).

Including MATSim in Eclipse

 

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.

References

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.