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.