Ejemplo n.º 1
0
  public static void main(final String[] args) {
    Gbl.startMeasurement();

    final String netFilename = "../schweiz-ivtch-SVN/baseCase/network/ivtch-osm.xml";
    final String plansFilename = "../runs-svn/run684/it.1000/1000.plans.xml.gz";
    String outputFilename = "../matsimTests/run684/DailyEnRouteTime/";
    String tollFilename = "../matsimTests/toll/KantonZurichToll.xml";

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario).readFile(netFilename);

    Population population = scenario.getPopulation();

    //        ConfigUtils.addOrGetModule(scenario.getConfig(), RoadPricingConfigGroup.GROUP_NAME,
    // RoadPricingConfigGroup.class).setUseRoadpricing(true);
    RoadPricingReaderXMLv1 tollReader =
        new RoadPricingReaderXMLv1(
            (RoadPricingSchemeImpl) scenario.getScenarioElement(RoadPricingScheme.ELEMENT_NAME));
    tollReader.parse(tollFilename);

    DailyEnRouteTime ert =
        new DailyEnRouteTime(
            (RoadPricingScheme) scenario.getScenarioElement(RoadPricingScheme.ELEMENT_NAME));

    System.out.println("-->reading plansfile: " + plansFilename);
    new MatsimPopulationReader(scenario).readFile(plansFilename);

    ert.run(population);
    ert.write(outputFilename);

    System.out.println("--> Done!");
    Gbl.printElapsedTime();
    System.exit(0);
  }
Ejemplo n.º 2
0
  /** @param args */
  public static void main(final String[] args) {
    // final String netFilename = "./test/yu/ivtch/input/network.xml";
    final String netFilename = "../data/ivtch/input/network.xml";
    // final String netFilename = "./test/yu/equil_test/equil_net.xml";
    // final String plansFilename = "../runs/run264/100.plans.xml.gz";
    final String plansFilename = "../data/ivtch/carPt_opt_run266/ITERS/it.100/100.plans.xml.gz";
    // final String plansFilename =
    // "./test/yu/equil_test/output/100.plans.xml.gz";
    // final String outFilename = "./output/legsCount.txt.gz";
    // final String outFilename =
    // "../data/ivtch/carPt_opt_run266/legsCount.txt";

    Gbl.startMeasurement();

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario).readFile(netFilename);

    Population population = scenario.getPopulation();

    System.out.println("-->reading plansfile: " + plansFilename);
    new MatsimPopulationReader(scenario).readFile(plansFilename);

    CarIllegal cl = new CarIllegal();
    cl.run(population);

    System.out.println("--> Done!\n-->There is " + cl.getCount() + " illeagel drivers!");
    Gbl.printElapsedTime();
    System.exit(0);
  }
Ejemplo n.º 3
0
 /**
  * @param facilitiesFile
  * @return
  */
 @Deprecated // use centralized infrastructure
 public static ActivityFacilities readActivityFacilities(String facilitiesFile) {
   ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
   ActivityFacilities facilities = scenario.getActivityFacilities();
   new MatsimFacilitiesReader(scenario).readFile(facilitiesFile);
   return facilities;
 }
Ejemplo n.º 4
0
  /** @param args */
  public static void main(String[] args) {
    String //
        // netFilename = "../matsim/test/scenarios/chessboard/network.xml", //
        // popFilename = "../matsim/test/scenarios/chessboard/plans.xml", //
        facilitiesFilename = "../matsim/test/scenarios/chessboard/facilities.xml", //
        facilitiesTxtFilename = "../matsimTests/locationChoice/chessboard/facilities.txt";

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    // new MatsimNetworkReader(scenario).readFile(netFilename);
    new MatsimFacilitiesReader((ScenarioImpl) scenario).readFile(facilitiesFilename);

    SimpleWriter writer = new SimpleWriter(facilitiesTxtFilename);
    writer.writeln("Id\tx\ty\tacts\tcapacities");

    ActivityFacilities facilities = scenario.getActivityFacilities();
    for (ActivityFacility facility : facilities.getFacilities().values()) {
      Coord coord = facility.getCoord();
      writer.write(facility.getId() + "\t" + coord.getX() + "\t" + coord.getY() + "\t");

      Map<String, ? extends ActivityOption> activityOptions = facility.getActivityOptions();
      // acts
      writer.write(activityOptions.keySet());
      // capacities
      for (ActivityOption activityOption : activityOptions.values()) {
        writer.write("\t" + activityOption.getCapacity());
      }
      writer.writeln();
      writer.flush();
    }

    writer.close();
  }
Ejemplo n.º 5
0
  /*
   * Reads the network from the network file.
   */
  @Deprecated // use centralized infrastructure
  public static Network readNetwork(String networkFile) {
    ScenarioImpl sc = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());

    sc.getConfig().setParam("network", "inputNetworkFile", networkFile);

    ScenarioUtils.loadScenario(sc);

    return sc.getNetwork();
  }
  public CreateInitialTimeSchedule(
      String networkInFile, double gridDistance, Coord minXY, Coord maxXY, int numberOfAgents) {
    ScenarioImpl sc = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    MatsimNetworkReader netReader = new MatsimNetworkReader(sc);
    netReader.readFile(networkInFile);
    this.net = (NetworkImpl) sc.getNetwork();

    this.tS = CreateStops.createStops(this.net, gridDistance, minXY, maxXY);
    this.veh = VehicleUtils.createVehiclesContainer();
    this.numberOfAgents = numberOfAgents;
  }
Ejemplo n.º 7
0
  /*
   * Reads the population from the plans file.
   */
  @Deprecated // use centralized infrastructure
  public static Scenario readScenario(
      String plansFile, String networkFile, String facilititiesPath) {
    ScenarioImpl sc = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());

    sc.getConfig().setParam("plans", "inputPlansFile", plansFile);
    sc.getConfig().setParam("network", "inputNetworkFile", networkFile);
    sc.getConfig().setParam("facilities", "inputFacilitiesFile", facilititiesPath);

    ScenarioUtils.loadScenario(sc);

    return sc;
  }
Ejemplo n.º 8
0
  /**
   * TODO: write test.
   *
   * @param persons
   * @param outputPlansFileName
   * @param network
   */
  public static void writePersons(
      Collection<? extends Person> persons,
      String outputPlansFileName,
      Network network,
      ScenarioImpl scenario) {
    PopulationWriter popWriter =
        new PopulationWriter(
            PopulationUtils.createPopulation(scenario.getConfig(), scenario.getNetwork()), network);
    popWriter.writeStartPlans(outputPlansFileName);

    for (Person person : persons) {
      popWriter.writePerson(person);
    }

    popWriter.writeEndPlans();
  }
  /**
   * Preparing hot start: Copying recent matsim plans file to a specified location (Matsim config).
   * Matsim will check this location for plans file on run and activates hot start if the plans file
   * is there
   */
  public static void prepareHotStart(ScenarioImpl scenario) {

    M4UControlerConfigModuleV3 module =
        ConfigurationUtils.getMATSim4UrbaSimControlerConfigModule(scenario);
    UrbanSimParameterConfigModuleV3 uspModule =
        M4UConfigUtils.getUrbanSimParameterConfigAndPossiblyConvert(scenario.getConfig());

    String hotStartFile = module.getHotStartPlansFileLocation().trim();
    if (exists(hotStartFile)) {

      String plansFile =
          uspModule.getMATSim4OpusOutput() + InternalConstants.GENERATED_PLANS_FILE_NAME;
      try {
        log.info("Preparing hot start for next MATSim run ...");
        FileCopy.fileCopy(new File(plansFile), new File(hotStartFile));
      } catch (Exception e) {
        log.error("Error while copying plans file, i. e. hot start will not work!");
        e.printStackTrace();
      }

      log.info("Hot start preparation successful!");
    } else {
      log.info("can not prepare hotStart. hotstart-file does not exist: " + hotStartFile);
    }
  }
Ejemplo n.º 10
0
  public static void main(String[] args) {

    String networkFile = "./bb_cl.xml.gz";
    String plansFile = "./baseplan";
    int numberOfAdditionalCopies = 9;
    double radiusOfPerimeter = 1000.0;

    Gbl.startMeasurement();

    ScenarioImpl sc = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());

    Network net = sc.getNetwork();
    new MatsimNetworkReader(sc).readFile(networkFile);

    Population inPop = sc.getPopulation();
    PopulationReader popReader = new MatsimPopulationReader(sc);
    popReader.readFile(plansFile + ".xml.gz");

    DuplicatePlans dp = new DuplicatePlans(net, inPop, "tmp.xml.gz", numberOfAdditionalCopies);
    dp.run(inPop);
    dp.writeEndPlans();

    System.out.println("Dublicating plans finished");
    Gbl.printElapsedTime();

    inPop =
        ((ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig())).getPopulation();
    popReader = new MatsimPopulationReader(new SharedNetScenario(sc, inPop));
    popReader.readFile("tmp.xml.gz");

    ShuffleCoords shuffleCoords =
        new ShuffleCoords(
            net,
            inPop,
            plansFile + "_" + (numberOfAdditionalCopies + 1) + "x.xml.gz",
            radiusOfPerimeter,
            TransformationFactory.getCoordinateTransformation(
                TransformationFactory.DHDN_GK4, TransformationFactory.DHDN_GK4));
    shuffleCoords.setChangeHomeActsOnlyOnceTrue("home");
    shuffleCoords.run(inPop);
    shuffleCoords.writeEndPlans();

    (new File("tmp.xml.gz")).deleteOnExit();

    Gbl.printElapsedTime();
  }
Ejemplo n.º 11
0
  public static void main(String[] args) {
    String netfile = null;
    String outputFileLs = null;
    String outputFileP = null;

    if (args.length == 0) {
      netfile =
          "d:\\Berlin\\berlin-fggeoinfo\\30_Run_20_percent\\20101005_run777_778\\network_modified_20100806_added_BBI_AS_cl.xml.gz";
      //		String netfile = "./test/scenarios/berlin/network.xml.gz";
      EventsCompareConfig.eventsFileOne = "E:/run778/output/ITERS/it.900/run778.900.events.txt";
      EventsCompareConfig.eventsFileTwo = "E:/run777/output/ITERS/it.900/run777.900.events.txt";

      outputFileLs = "e:\\temp\\networkLs_abs.shp";
      outputFileP = "e:\\temp\\networkP_abs.shp";
    } else if (args.length == 3) {
      netfile = args[0];
      outputFileLs = args[1];
      outputFileP = args[2];
    } else {
      log.error("Arguments cannot be interpreted.  Aborting ...");
      System.exit(-1);
    }

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    scenario.getConfig().global().setCoordinateSystem("DHDN_GK4");

    log.info("loading network from " + netfile);
    final Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario).readFile(netfile);
    log.info("done.");

    FeatureGeneratorBuilderImpl builder = new FeatureGeneratorBuilderImpl(network, "DHDN_GK4");
    //		builder.setFeatureGeneratorPrototype(CountVehOnLinksStringBasedFeatureGenerator.class);
    builder.setFeatureGeneratorPrototype(CountVehOnLinksStringBasedFeatureGenerator.class);
    builder.setWidthCoefficient(0.5);
    builder.setWidthCalculatorPrototype(LanesBasedWidthCalculator.class);
    new Links2ESRIShape(network, outputFileLs, builder).write();

    CoordinateReferenceSystem crs = MGC.getCRS("DHDN_GK4");
    builder.setWidthCoefficient(0.01);
    //		builder.setFeatureGeneratorPrototype(CountVehOnLinksPolygonBasedFeatureGenerator.class);
    builder.setFeatureGeneratorPrototype(CountVehOnLinksPolygonBasedFeatureGenerator.class);
    builder.setWidthCalculatorPrototype(CapacityBasedWidthCalculator.class);
    builder.setCoordinateReferenceSystem(crs);
    new Links2ESRIShape(network, outputFileP, builder).write();
  }
Ejemplo n.º 12
0
  public static void runEventsProcessing(Properties properties) {
    boolean isTransit = false;
    ScenarioImpl scenario =
        (ScenarioImpl)
            ScenarioUtils.createScenario(
                ConfigUtils.loadConfig(properties.get("configFile").toString()));
    scenario.getConfig().transit().setUseTransit(true);
    if (!properties.get("transitScheduleFile").toString().equals("")) {
      new TransitScheduleReader(scenario)
          .readFile(properties.get("transitScheduleFile").toString());
      isTransit = true;
    }
    new MatsimNetworkReader(scenario).readFile(properties.get("networkFile").toString());

    EventsManager eventsManager = EventsUtils.createEventsManager();
    EventsToTravelDiaries test;
    // if(linkTrafficComponent.isSelected()){
    // test = new EventsToPlanElements(
    // scenario.getTransitSchedule(), scenario.getNetwork(),
    // scenario.getConfig(),new File(postgresPropertiesComponent.getText())
    // ,tableSuffixComponent.getText());
    // }else{
    if (isTransit) {
      test =
          new EventsToTravelDiaries(
              scenario.getTransitSchedule(), scenario.getNetwork(), scenario.getConfig());

    } else {
      test = new EventsToTravelDiaries(scenario);
    }
    // }
    eventsManager.addHandler(test);
    new MatsimEventsReader(eventsManager).readFile(properties.get("eventsFile").toString());

    try {

      test.writeSimulationResultsToTabSeparated(
          properties.get("outputPath").toString(), properties.get("tableSuffix").toString());

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.out.println("Number of stuck vehicles/passengers: " + test.getStuck());
  }
Ejemplo n.º 13
0
  @Test
  public void testGetDeparturesAtStop()
      throws SAXException, ParserConfigurationException, IOException {
    final String inputDir =
        "test/input/" + TransitScheduleReaderTest.class.getCanonicalName().replace('.', '/') + "/";

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario).readFile(inputDir + INPUT_TEST_FILE_NETWORK);

    TransitScheduleFactory builder = new TransitScheduleFactoryImpl();
    TransitSchedule schedule = builder.createTransitSchedule();
    new TransitScheduleReaderV1(schedule, network)
        .readFile(inputDir + INPUT_TEST_FILE_TRANSITSCHEDULE);

    TransitLine line = schedule.getTransitLines().get(Id.create("T1", TransitLine.class));
    CreateTimetableForStop timetable = new CreateTimetableForStop(line);
    assertNotNull("could not get transit line.", line);

    double[] departures =
        timetable.getDeparturesAtStop(
            schedule.getFacilities().get(Id.create("stop3", TransitStopFacility.class)));

    for (double d : departures) {
      System.out.println("Departure at " + Time.writeTime(d));
    }

    assertEquals("wrong number of departures.", 3, departures.length);
    double baseDepartureTime = Time.parseTime("07:00:00") + Time.parseTime("00:03:00");
    assertEquals(
        "wrong departure time for 1st departure.",
        baseDepartureTime,
        departures[0],
        MatsimTestCase.EPSILON);
    assertEquals(
        "wrong departure time for 2nd departure.",
        baseDepartureTime + 600,
        departures[1],
        MatsimTestCase.EPSILON);
    assertEquals(
        "wrong departure time for 3rd departure.",
        baseDepartureTime + 1200,
        departures[2],
        MatsimTestCase.EPSILON);
  }
Ejemplo n.º 14
0
  /**
   * Tests that a custom scoring function factory doesn't get overwritten in the initialization
   * process of the Controler.
   *
   * @author mrieser
   */
  @Test
  public void testSetScoringFunctionFactory() {
    final Config config = this.utils.loadConfig(null);
    config.controler().setLastIteration(0);

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(config);
    // create a very simple network with one link only and an empty population
    Network network = scenario.getNetwork();
    Node node1 = network.getFactory().createNode(Id.create(1, Node.class), new Coord(0, 0));
    Node node2 = network.getFactory().createNode(Id.create(2, Node.class), new Coord(100, 0));
    network.addNode(node1);
    network.addNode(node2);
    Link link = network.getFactory().createLink(Id.create(1, Link.class), node1, node2);
    link.setLength(100);
    link.setFreespeed(1);
    link.setCapacity(3600.0);
    link.setNumberOfLanes(1);

    final Controler controler = new Controler(scenario);
    controler.getConfig().controler().setCreateGraphs(false);
    controler.getConfig().controler().setWriteEventsInterval(0);
    controler.setScoringFunctionFactory(new DummyScoringFunctionFactory());

    controler.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            bindMobsim()
                .toProvider(
                    new Provider<Mobsim>() {
                      @Override
                      public Mobsim get() {
                        return new FakeMobsim();
                      }
                    });
          }
        });
    controler.setDumpDataAtEnd(false);
    controler.run();

    assertTrue(
        "Custom ScoringFunctionFactory was not set.",
        controler.getScoringFunctionFactory() instanceof DummyScoringFunctionFactory);
  }
Ejemplo n.º 15
0
 /**
  * @param args 0 - Transit schedule file 1 - Last iteration 2 - Iterations interval with events 3
  *     - Output folder 4 - Distance bins file 5 - Distribution result folder
  * @throws java.io.IOException
  */
 public static void main(String[] args) throws IOException {
   ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
   scenario.getConfig().transit().setUseTransit(true);
   new TransitScheduleReader(scenario).readFile(args[0]);
   int lastIteration = new Integer(args[1]);
   int iterationsInterval = new Integer(args[2]);
   for (int i = 0; i <= lastIteration; i += iterationsInterval) {
     EventsManager eventsManager = EventsUtils.createEventsManager();
     TimeDistributionStage timeDistribution =
         new TimeDistributionStage(scenario.getTransitSchedule(), new HashSet<Id>());
     eventsManager.addHandler(timeDistribution);
     new MatsimEventsReader(eventsManager)
         .readFile(args[3] + "/ITERS/it." + i + "/" + i + ".events.xml.gz");
     timeDistribution.printDistribution(
         timeDistribution.getDistribution(
             args[4], new String[] {"car", "bus", "mrt", "lrt", "transit_walk", "walk", "other"}),
         args[5] + "/timeDistribution." + i + ".csv");
   }
 }
Ejemplo n.º 16
0
  public static void main(final String[] args) {
    Gbl.startMeasurement();

    final String netFilename = "../../matsim/examples/equil/network.xml";
    final String plansFilename = "../../matsim/examples/equil/plans100.xml";
    final String outputFilename = "test/input/plans100withPt.xml";

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario).readFile(netFilename);

    Population population = scenario.getPopulation();
    new MatsimPopulationReader(scenario).readFile(plansFilename);

    NewMeaningfullPtPop npwp = new NewMeaningfullPtPop(network, population, outputFilename);
    npwp.run(population);
    npwp.writeEndPlans();

    System.out.println("--> Done!");
    Gbl.printElapsedTime();
    System.exit(0);
  }
Ejemplo n.º 17
0
  private void init(
      final String plansfilePath,
      final String networkfilePath,
      final String facilitiesfilePath,
      final String worldfilePath) {

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());

    this.network = scenario.getNetwork();
    new MatsimNetworkReader(scenario.getNetwork()).readFile(networkfilePath);
    log.info("network reading done");

    // this.facilities=new Facilities();
    this.facilities = scenario.getActivityFacilities();
    new FacilitiesReaderMatsimV1(scenario).readFile(facilitiesfilePath);
    log.info("facilities reading done");

    this.plans = scenario.getPopulation();
    final PopulationReader plansReader = new MatsimPopulationReader(scenario);
    plansReader.readFile(plansfilePath);
    log.info("plans reading done");
    log.info(this.plans.getPersons().size() + " persons");
  }
Ejemplo n.º 18
0
  /** @param args */
  public static void main(final String[] args) {
    Gbl.startMeasurement();

    final String netFilename = "../schweiz-ivtch-SVN/baseCase/network/ivtch-osm.xml";
    final String plansFilename = "../runs_SVN/run669/it.1000/1000.plans.xml.gz";
    final String outputFilename = "../runs_SVN/run669/it.1000/CarAvail";

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario).readFile(netFilename);

    CarAvailStatistics cas = new CarAvailStatistics();

    System.out.println("-->reading plansfile: " + plansFilename);
    new MatsimPopulationReader(scenario).readFile(plansFilename);

    cas.run(scenario.getPopulation());

    cas.write(outputFilename);

    System.out.println("--> Done!");
    Gbl.printElapsedTime();
    System.exit(0);
  }
Ejemplo n.º 19
0
  public void testArriveAtStop() {
    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());

    NetworkImpl network = (NetworkImpl) scenario.getNetwork();
    Node node1 = network.createAndAddNode(Id.create("1", Node.class), new CoordImpl(0, 0));
    Node node2 = network.createAndAddNode(Id.create("2", Node.class), new CoordImpl(1000, 0));
    Node node3 = network.createAndAddNode(Id.create("3", Node.class), new CoordImpl(2000, 0));
    network.createAndAddLink(Id.create("1", Link.class), node1, node2, 1000.0, 10.0, 3600.0, 1);
    network.createAndAddLink(Id.create("2", Link.class), node2, node3, 1000.0, 10.0, 3600.0, 1);

    TransitScheduleFactory builder = new TransitScheduleFactoryImpl();
    PopulationFactory pb = scenario.getPopulation().getFactory();
    Person person = pb.createPerson(Id.create("1", Person.class));
    Plan plan = pb.createPlan();
    person.addPlan(plan);
    Activity homeAct = pb.createActivityFromLinkId("home", Id.create("1", Link.class));
    Leg leg = pb.createLeg(TransportMode.pt);
    TransitStopFacility stop1 =
        builder.createTransitStopFacility(
            Id.create("1", TransitStopFacility.class), scenario.createCoord(100, 100), false);
    TransitStopFacility stop2 =
        builder.createTransitStopFacility(
            Id.create("2", TransitStopFacility.class), scenario.createCoord(900, 100), false);
    TransitStopFacility stop3 =
        builder.createTransitStopFacility(
            Id.create("3", TransitStopFacility.class), scenario.createCoord(1900, 100), false);
    TransitLine line1 = builder.createTransitLine(Id.create("L1", TransitLine.class));
    leg.setRoute(new ExperimentalTransitRoute(stop1, line1, null, stop2));
    Activity workAct = pb.createActivityFromLinkId("work", Id.create("2", Link.class));
    plan.addActivity(homeAct);
    plan.addLeg(leg);
    plan.addActivity(workAct);

    QSim sim = (QSim) new QSimFactory().createMobsim(scenario, EventsUtils.createEventsManager());
    TransitAgent agent = TransitAgent.createTransitAgent(person, sim);
    sim.insertAgentIntoMobsim(agent);
    agent.endActivityAndComputeNextState(10);

    assertFalse(agent.getExitAtStop(stop1));
    assertTrue(agent.getExitAtStop(stop2));
    assertFalse(agent.getExitAtStop(stop3));
    assertTrue(agent.getExitAtStop(stop2)); // offering the same stop again should yield "true"
  }
  public void testTransitRouteCopy() {
    Config config = super.loadConfig(null);
    config.scenario().setUseTransit(true);
    config.scenario().setUseVehicles(true);
    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(config);

    Id<Node> nodeId1 = Id.create("1", Node.class);
    Id<Node> nodeId2 = Id.create("2", Node.class);
    Id<Node> nodeId3 = Id.create("3", Node.class);
    Id<Link> linkId1 = Id.create("1", Link.class);
    Id<Link> linkId2 = Id.create("2", Link.class);

    // build network
    Network network = scenario.getNetwork();
    NetworkFactory nBuilder = network.getFactory();
    Node node1 = nBuilder.createNode(nodeId1, scenario.createCoord(0, 0));
    Node node2 = nBuilder.createNode(nodeId2, scenario.createCoord(1000, 0));
    Node node3 = nBuilder.createNode(nodeId3, scenario.createCoord(2000, 0));
    network.addNode(node1);
    network.addNode(node2);
    network.addNode(node3);
    Link link1 = nBuilder.createLink(linkId1, node1, node2);
    Link link2 = nBuilder.createLink(linkId2, node2, node3);
    network.addLink(link1);
    network.addLink(link2);

    // build schedule
    TransitSchedule schedule = scenario.getTransitSchedule();
    TransitScheduleFactory sBuilder = schedule.getFactory();

    TransitStopFacility stopF1 =
        sBuilder.createTransitStopFacility(
            Id.create("1", TransitStopFacility.class), scenario.createCoord(1000.0, 0), false);
    TransitStopFacility stopF2 =
        sBuilder.createTransitStopFacility(
            Id.create("2", TransitStopFacility.class), scenario.createCoord(2000.0, 0), false);
    stopF1.setLinkId(link1.getId());
    stopF2.setLinkId(link2.getId());
    schedule.addStopFacility(stopF1);
    schedule.addStopFacility(stopF2);

    TransitLine tLine1 = sBuilder.createTransitLine(Id.create("1", TransitLine.class));

    TransitRouteStop stop1 = sBuilder.createTransitRouteStop(stopF1, 0, 0);
    TransitRouteStop stop2 = sBuilder.createTransitRouteStop(stopF2, 100, 100);
    ArrayList<TransitRouteStop> stops = new ArrayList<TransitRouteStop>();
    stops.add(stop1);
    stops.add(stop2);

    NetworkRoute netRoute = new LinkNetworkRouteImpl(link1.getId(), link2.getId());
    netRoute.setLinkIds(link1.getId(), Collections.<Id<Link>>emptyList(), link2.getId());
    TransitRoute tRoute1 =
        sBuilder.createTransitRoute(Id.create("1", TransitRoute.class), netRoute, stops, "bus");

    tRoute1.addDeparture(sBuilder.createDeparture(Id.create("1", Departure.class), 7.0 * 3600));
    tLine1.addRoute(tRoute1);
    schedule.addTransitLine(tLine1);

    // build vehicles
    new CreateVehiclesForSchedule(schedule, scenario.getVehicles()).run();

    // build population
    Population population = scenario.getPopulation();
    PopulationFactory pBuilder = population.getFactory();
    Person person1 = pBuilder.createPerson(Id.create("1", Person.class));
    Plan plan = pBuilder.createPlan();
    Activity homeAct = pBuilder.createActivityFromLinkId("h", linkId1);
    homeAct.setEndTime(7.0 * 3600);
    plan.addActivity(homeAct);
    Leg leg = pBuilder.createLeg(TransportMode.pt);
    ExperimentalTransitRoute tRoute = new ExperimentalTransitRoute(stopF1, tLine1, tRoute1, stopF2);
    leg.setRoute(tRoute);
    plan.addLeg(leg);
    plan.addActivity(pBuilder.createActivityFromLinkId("w", linkId2));
    person1.addPlan(plan);
    population.addPerson(person1);

    // prepare config
    config.controler().setFirstIteration(0);
    config.controler().setLastIteration(1);

    ActivityParams params = new ActivityParams("h");
    params.setTypicalDuration(16.0 * 3600);
    config.planCalcScore().addActivityParams(params);
    params = new ActivityParams("w");
    params.setTypicalDuration(8.0 * 3600);
    config.planCalcScore().addActivityParams(params);

    StrategySettings tam = new StrategySettings(Id.create(1, StrategySettings.class));
    tam.setStrategyName("TimeAllocationMutator");
    tam.setWeight(1.0);
    config.strategy().addStrategySettings(tam);

    // run
    Controler controler = new Controler(scenario);
    controler.getConfig().controler().setWriteEventsInterval(0);
    controler.setCreateGraphs(false);
    controler.run();

    // checks
    assertEquals(1, population.getPersons().size());
    assertEquals(2, person1.getPlans().size());
    assertEquals(
        ExperimentalTransitRoute.class,
        ((Leg) person1.getPlans().get(0).getPlanElements().get(1)).getRoute().getClass());
    assertEquals(
        ExperimentalTransitRoute.class,
        ((Leg) person1.getPlans().get(1).getPlanElements().get(1)).getRoute().getClass());
  }
 private void init(final String plansFilePath, final String networkFilePath) {
   new MatsimNetworkReader(scenario.getNetwork()).readFile(networkFilePath);
   MatsimPopulationReader populationReader = new MatsimPopulationReader(this.scenario);
   populationReader.readFile(plansFilePath);
 }
Ejemplo n.º 22
0
  public static void main(String[] args) {

    //		SubpopulationConfig subPopConfig = new SubpopulationConfig();
    //		subPopConfig.run();
    //		Config config = subPopConfig.getPatnaConfig();
    Config config = ConfigUtils.loadConfig(args[0]);
    Scenario sc = ScenarioUtils.loadScenario(config);

    sc.getConfig().qsim().setUseDefaultVehicles(false);
    ((ScenarioImpl) sc).createVehicleContainer();

    Map<String, VehicleType> modesType = new HashMap<String, VehicleType>();
    VehicleType slum_car =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_car", VehicleType.class));
    slum_car.setMaximumVelocity(60.0 / 3.6);
    slum_car.setPcuEquivalents(1.0);
    modesType.put("slum_car", slum_car);
    sc.getVehicles().addVehicleType(slum_car);

    VehicleType nonSlum_car =
        VehicleUtils.getFactory().createVehicleType(Id.create("nonSlum_car", VehicleType.class));
    nonSlum_car.setMaximumVelocity(60.0 / 3.6);
    nonSlum_car.setPcuEquivalents(1.0);
    modesType.put("nonSlum_car", nonSlum_car);
    sc.getVehicles().addVehicleType(nonSlum_car);

    VehicleType slum_motorbike =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_motorbike", VehicleType.class));
    slum_motorbike.setMaximumVelocity(60.0 / 3.6);
    slum_motorbike.setPcuEquivalents(0.25);
    modesType.put("slum_motorbike", slum_motorbike);
    sc.getVehicles().addVehicleType(slum_motorbike);

    VehicleType nonSlum_motorbike =
        VehicleUtils.getFactory()
            .createVehicleType(Id.create("nonSlum_motorbike", VehicleType.class));
    nonSlum_motorbike.setMaximumVelocity(60.0 / 3.6);
    nonSlum_motorbike.setPcuEquivalents(0.25);
    modesType.put("nonSlum_motorbike", nonSlum_motorbike);
    sc.getVehicles().addVehicleType(nonSlum_motorbike);

    VehicleType slum_bike =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_bike", VehicleType.class));
    slum_bike.setMaximumVelocity(15.0 / 3.6);
    slum_bike.setPcuEquivalents(0.25);
    modesType.put("slum_bike", slum_bike);
    sc.getVehicles().addVehicleType(slum_bike);

    VehicleType nonSlum_bike =
        VehicleUtils.getFactory().createVehicleType(Id.create("nonSlum_bike", VehicleType.class));
    nonSlum_bike.setMaximumVelocity(15.0 / 3.6);
    nonSlum_bike.setPcuEquivalents(0.25);
    modesType.put("nonSlum_bike", nonSlum_bike);
    sc.getVehicles().addVehicleType(nonSlum_bike);

    VehicleType slum_walk =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_walk", VehicleType.class));
    slum_walk.setMaximumVelocity(1.5);
    //		walk.setPcuEquivalents(0.10);
    modesType.put("slum_walk", slum_walk);
    sc.getVehicles().addVehicleType(slum_walk);

    VehicleType nonSlum_walk =
        VehicleUtils.getFactory().createVehicleType(Id.create("nonSlum_walk", VehicleType.class));
    nonSlum_walk.setMaximumVelocity(1.5);
    //		walk.setPcuEquivalents(0.10);
    modesType.put("nonSlum_walk", nonSlum_walk);
    sc.getVehicles().addVehicleType(nonSlum_walk);

    VehicleType slum_pt =
        VehicleUtils.getFactory().createVehicleType(Id.create("slum_pt", VehicleType.class));
    slum_pt.setMaximumVelocity(40 / 3.6);
    //		pt.setPcuEquivalents(5);
    modesType.put("slum_pt", slum_pt);
    sc.getVehicles().addVehicleType(slum_pt);

    VehicleType nonSlum_pt =
        VehicleUtils.getFactory().createVehicleType(Id.create("nonSlum_pt", VehicleType.class));
    nonSlum_pt.setMaximumVelocity(40 / 3.6);
    //		pt.setPcuEquivalents(5);
    modesType.put("nonSlum_pt", nonSlum_pt);
    sc.getVehicles().addVehicleType(nonSlum_pt);

    for (Person p : sc.getPopulation().getPersons().values()) {
      Id<Vehicle> vehicleId = Id.create(p.getId(), Vehicle.class);
      String travelMode = null;
      for (PlanElement pe : p.getSelectedPlan().getPlanElements()) {
        if (pe instanceof Leg) {
          travelMode = ((Leg) pe).getMode();
          break;
        }
      }
      Vehicle vehicle =
          VehicleUtils.getFactory().createVehicle(vehicleId, modesType.get(travelMode));
      sc.getVehicles().addVehicle(vehicle);
    }

    final Controler controler = new Controler(sc);

    //		IOUtils.deleteDirectory(new File(controler.getConfig().controler().getOutputDirectory()));
    controler
        .getConfig()
        .controler()
        .setOverwriteFileSetting(
            true
                ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles
                : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists);
    controler.setDumpDataAtEnd(true);
    controler.getConfig().controler().setCreateGraphs(true);

    controler.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            addPlanStrategyBinding("ChangeLegMode_slum")
                .toProvider(
                    new javax.inject.Provider<PlanStrategy>() {
                      String[] availableModes_slum = {
                        "slum_bike", "slum_motorbike", "slum_pt", "slum_walk"
                      };

                      @Override
                      public PlanStrategy get() {
                        final Builder builder = new Builder(new RandomPlanSelector<Plan, Person>());
                        builder.addStrategyModule(
                            new ChangeLegMode(
                                controler.getConfig().global().getNumberOfThreads(),
                                availableModes_slum,
                                true));
                        builder.addStrategyModule(new ReRoute(controler.getScenario()));
                        return builder.build();
                      }
                    });
          }
        });

    controler.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            addPlanStrategyBinding("ChangeLegMode_nonSlum")
                .toProvider(
                    new javax.inject.Provider<PlanStrategy>() {
                      String[] availableModes_nonSlum = {
                        "nonSlum_car",
                        "nonSlum_bike",
                        "nonSlum_motorbike",
                        "nonSlum_pt",
                        "nonSlum_walk"
                      };

                      @Override
                      public PlanStrategy get() {
                        final Builder builder = new Builder(new RandomPlanSelector<Plan, Person>());
                        builder.addStrategyModule(
                            new ChangeLegMode(
                                controler.getConfig().global().getNumberOfThreads(),
                                availableModes_nonSlum,
                                true));
                        builder.addStrategyModule(new ReRoute(controler.getScenario()));
                        return builder.build();
                      }
                    });
          }
        });

    //		controler.setScoringFunctionFactory(new
    // SubPopulationScoringFactory(controler.getScenario()));
    controler.run();
  }
 /**
  * Class to read a set of four population-related files:
  *
  * <ol>
  *   <li><code>population.xml</code>
  *   <li><code>personAttributes.xml</code>
  *   <li><code>households.xml</code>
  *   <li><code>householdAttributes.xml</code>
  * </ol>
  *
  * These files are usually the result from census or travel survey data, for example using {@link
  * Census2001SampleParser} or {@link NmbmSurveyParser}.
  *
  * @param args
  */
 public ComprehensivePopulationReader() {
   this.sc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
   ((ScenarioImpl) sc).createHouseholdsContainer();
 }
  private final void convertSchedules(
      OTTDataContainer dataContainer, ObjectAttributes trainTypes, boolean isPerformance) {
    TransitScheduleFactory scheduleFactory = scenario.getTransitSchedule().getFactory();
    VehiclesFactory vehiclesFactory = ((ScenarioImpl) scenario).getVehicles().getFactory();

    VehicleType vehicleType =
        vehiclesFactory.createVehicleType(new IdImpl(WagonSimConstants.DEFAULT_VEHICLE_TYPE));
    VehicleCapacity vehicleCapacity = vehiclesFactory.createVehicleCapacity();
    // we do not use this capacity. Therefore it should infinite, otherwise this capacity may exceed
    // before ``our'' capacities are exceeded // dr, oct'13
    vehicleCapacity.setSeats(999999);
    vehicleCapacity.setStandingRoom(999999);
    // we defined the vehicle-enter/leave-time is implicit included in transfer-times which
    // are defined in the transitrouterconfig (for handling see
    // WagonSimTripRouterFactoryImpl#WagonSimRouterWrapper)
    // dr, oct'13
    vehicleType.setAccessTime(0);
    vehicleType.setEgressTime(0);
    vehicleType.setCapacity(vehicleCapacity);
    ((ScenarioImpl) scenario).getVehicles().addVehicleType(vehicleType);

    Date startDate = extractStartDate(dataContainer, isPerformance);
    System.out.println("startDate=" + startDate.toString());

    for (Locomotive locomotive : dataContainer.locomotives.values()) {

      Departure departure = null;
      List<TransitRouteStop> transitRouteStops = new ArrayList<TransitRouteStop>();
      for (StationData stationData : locomotive.trips.values()) {

        TransitStopFacility stopFacility =
            scenario.getTransitSchedule().getFacilities().get(stationData.stationId);
        if (stopFacility == null) {
          throw new RuntimeException(
              "locomotive id="
                  + locomotive.id
                  + ": station id="
                  + stationData.stationId
                  + " not found. Bailing out.");
        }

        double arrivalDelay = Double.NaN;
        double departureDelay = Double.NaN;
        if (departure == null) {
          double lineDepartureOffset =
              (stationData.departure.getTime() - startDate.getTime()) / 1000.0;
          if (!isPerformance) {
            lineDepartureOffset -= stationData.delayDeparture;
          }
          departure = scheduleFactory.createDeparture(locomotive.id, lineDepartureOffset);
          arrivalDelay = 0.0;
        } else {
          arrivalDelay =
              (stationData.arrival.getTime() - startDate.getTime()) / 1000.0
                  - departure.getDepartureTime();
          if (!isPerformance) {
            arrivalDelay -= stationData.delayArrival;
          }
        }
        departureDelay =
            (stationData.departure.getTime() - startDate.getTime()) / 1000.0
                - departure.getDepartureTime();
        if (!isPerformance) {
          departureDelay -= stationData.delayDeparture;
        }

        if (departureDelay < arrivalDelay) {
          throw new RuntimeException(
              "locomotive id="
                  + locomotive.id
                  + ": arrival="
                  + stationData.arrival.toString()
                  + " does not fit with departure="
                  + stationData.departure.toString()
                  + ". ("
                  + departureDelay
                  + "<"
                  + arrivalDelay
                  + ") Bailing out.");
        }

        TransitRouteStop stop =
            scheduleFactory.createTransitRouteStop(stopFacility, arrivalDelay, departureDelay);
        stop.setAwaitDepartureTime(true);
        transitRouteStops.add(stop);
      }

      if (transitRouteStops.size() > 1) {

        // check if train type is given
        if (trainTypes.getAttribute(locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED)
            == null) {
          throw new RuntimeException(
              "locomotive id="
                  + locomotive.id
                  + ": type="
                  + locomotive.type
                  + " is not defined by the train type table. Bailing out.");
        }

        TransitLine line = scheduleFactory.createTransitLine(locomotive.id);
        scenario.getTransitSchedule().addTransitLine(line);
        TransitRoute route =
            scheduleFactory.createTransitRoute(
                line.getId(), null, transitRouteStops, TransportMode.pt);
        line.addRoute(route);

        Vehicle vehicle = vehiclesFactory.createVehicle(route.getId(), vehicleType);
        ((ScenarioImpl) scenario).getVehicles().addVehicle(vehicle);
        departure.setVehicleId(vehicle.getId());
        route.addDeparture(departure);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(), WagonSimConstants.TRAIN_TYPE, locomotive.type);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_SPEED,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_WEIGHT,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_WEIGHT));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_LENGTH,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_LENGTH));

        // the next day
        vehicle = vehiclesFactory.createVehicle(new IdImpl(route.getId() + ".1"), vehicleType);
        ((ScenarioImpl) scenario).getVehicles().addVehicle(vehicle);
        departure =
            scheduleFactory.createDeparture(
                vehicle.getId(), departure.getDepartureTime() + 24 * 3600);
        departure.setVehicleId(vehicle.getId());
        route.addDeparture(departure);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(), WagonSimConstants.TRAIN_TYPE, locomotive.type);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_SPEED,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_WEIGHT,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_WEIGHT));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_LENGTH,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_LENGTH));

        // the day after the next day
        vehicle = vehiclesFactory.createVehicle(new IdImpl(route.getId() + ".2"), vehicleType);
        ((ScenarioImpl) scenario).getVehicles().addVehicle(vehicle);
        departure =
            scheduleFactory.createDeparture(
                vehicle.getId(), departure.getDepartureTime() + 24 * 3600);
        departure.setVehicleId(vehicle.getId());
        route.addDeparture(departure);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(), WagonSimConstants.TRAIN_TYPE, locomotive.type);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_SPEED,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_WEIGHT,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_WEIGHT));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_LENGTH,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_LENGTH));
      } else if (transitRouteStops.size() == 1) {
        System.out.println(
            "locomotive id="
                + locomotive.id
                + ": only one station given. Therefore, no transitLine created.");
      } else {
        System.out.println(
            "locomotive id="
                + locomotive.id
                + ": no station is given. Therefore, no transitLine created.");
      }
    }
  }
  public void run(String[] args) {

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    PopulationReader populationReader = new MatsimPopulationReader(scenario);
    MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario);
    networkReader.readFile(args[0]);
    populationReader.readFile(args[1]);

    // randomly choose a person and run the simple model

    Object[] personArray = scenario.getPopulation().getPersons().values().toArray();

    int numberOfPersons = personArray.length;

    Map<Id, Person> addedMembers = new TreeMap<Id, Person>();

    int i = 0;

    Map<Id, Person> men = new TreeMap<Id, Person>();

    Map<Id, Person> women = new TreeMap<Id, Person>();

    // split the agents into men and women groups

    for (Person p : scenario.getPopulation().getPersons().values()) {

      if (PersonUtils.getSex(p).equals("m")) men.put(p.getId(), p);
      else women.put(p.getId(), p);
    }

    Object[] mArray = men.values().toArray();

    Object[] fArray = women.values().toArray();

    while (i < numMembers) {

      double randomDouble = MatsimRandom.getRandom().nextDouble();

      if (randomDouble < 0.8) {

        randomDouble = MatsimRandom.getRandom().nextDouble();

        if (randomDouble < ageShares[0]) {

          Person addP = findPerson(0, addedMembers, mArray);
        } else if (randomDouble < ageShares[1]) {
          Person addP = findPerson(1, addedMembers, mArray);

        } else if (randomDouble < ageShares[2]) {
          Person addP = findPerson(1, addedMembers, mArray);

        } else if (randomDouble < ageShares[3]) {
          Person addP = findPerson(1, addedMembers, mArray);

        } else {
          Person addP = findPerson(1, addedMembers, mArray);
        }

      } else {

        randomDouble = MatsimRandom.getRandom().nextDouble();

        if (randomDouble < ageShares[0]) {

          Person addP = findPerson(0, addedMembers, fArray);
        } else if (randomDouble < ageShares[1]) {
          Person addP = findPerson(1, addedMembers, fArray);

        } else if (randomDouble < ageShares[2]) {
          Person addP = findPerson(1, addedMembers, fArray);

        } else if (randomDouble < ageShares[3]) {
          Person addP = findPerson(1, addedMembers, fArray);

        } else {
          Person addP = findPerson(1, addedMembers, fArray);
        }
      }

      i++;
    }

    for (Person p : addedMembers.values()) {

      PersonUtils.addTravelcard(scenario.getPopulation().getPersons().get(p.getId()), "ffProgram");
    }

    new PopulationWriter(scenario.getPopulation(), scenario.getNetwork())
        .writeFileV4("./plans_ff_members.xml.gz");
  }
  /** Saving UrbanSim and MATSim results for current run in a backup directory ... */
  private static void saveRunOutputs(ScenarioImpl scenario) {
    log.info("Saving UrbanSim and MATSim outputs ...");

    M4UControlerConfigModuleV3 m4ucModule =
        M4UConfigUtils.getMATSim4UrbaSimControlerConfigAndPossiblyConvert(scenario.getConfig());
    UrbanSimParameterConfigModuleV3 uspModule =
        M4UConfigUtils.getUrbanSimParameterConfigAndPossiblyConvert(scenario.getConfig());
    AccessibilityConfigGroup acm =
        ConfigUtils.addOrGetModule(
            scenario.getConfig(),
            AccessibilityConfigGroup.GROUP_NAME,
            AccessibilityConfigGroup.class);
    int currentYear = uspModule.getYear();

    String saveDirectory = "run" + currentYear;
    String savePath = Paths.checkPathEnding(uspModule.getMATSim4OpusBackup() + saveDirectory);
    // copy all files from matsim4opus/tmp to matsim4opus/backup
    // FileCopy.copyTree(InternalConstants.MATSIM_4_OPUS_TEMP, savePath);
    File saveDir = new File(savePath);
    if (!saveDir.exists())
      if (!saveDir.mkdirs()) log.error("Creating the backup directory " + savePath + " failed!");

    // backup files from matsim output
    try {
      // backup plans files
      FileCopy.fileCopy(
          new File(uspModule.getMATSim4OpusOutput() + InternalConstants.GENERATED_PLANS_FILE_NAME),
          new File(savePath + InternalConstants.GENERATED_PLANS_FILE_NAME));
      // backup matsim config file
      FileCopy.fileCopy(
          new File(uspModule.getMATSim4OpusOutput() + OUTPUT_CONFIG_FILE_NAME),
          new File(savePath + OUTPUT_CONFIG_FILE_NAME));
      // backup score stats
      FileCopy.fileCopy(
          new File(uspModule.getMATSim4OpusOutput() + OUTPUT_SCORESTATS_TXT),
          new File(savePath + OUTPUT_SCORESTATS_TXT));
      FileCopy.fileCopy(
          new File(uspModule.getMATSim4OpusOutput() + OUTPUT_SCORESTATS_PNG),
          new File(savePath + OUTPUT_SCORESTATS_PNG));
      FileCopy.fileCopy(
          new File(uspModule.getMATSim4OpusOutput() + OUTPUT_TRAVELDISTANCESTATS_TXT),
          new File(savePath + OUTPUT_TRAVELDISTANCESTATS_TXT));
      FileCopy.fileCopy(
          new File(uspModule.getMATSim4OpusOutput() + OUTPUT_TRAVELDISTANCESTATS_PNG),
          new File(savePath + OUTPUT_TRAVELDISTANCESTATS_PNG));
      FileCopy.fileCopy(
          new File(uspModule.getMATSim4OpusOutput() + OUTPUT_STOPWATCH),
          new File(savePath + OUTPUT_STOPWATCH));
      // backup last iteration
      int iteration =
          ((ControlerConfigGroup) scenario.getConfig().getModule(ControlerConfigGroup.GROUP_NAME))
              .getLastIteration();
      FileCopy.copyTree(
          uspModule.getMATSim4OpusOutput() + "ITERS/it." + iteration,
          savePath + "ITERS/it." + iteration);

      // backup zone csv file (feedback for UrbanSim)
      if (new File(uspModule.getMATSim4OpusTemp() + UrbanSimZoneCSVWriterV2.FILE_NAME).exists())
        FileCopy.fileCopy(
            new File(uspModule.getMATSim4OpusTemp() + UrbanSimZoneCSVWriterV2.FILE_NAME),
            new File(savePath + UrbanSimZoneCSVWriterV2.FILE_NAME));
      // backup parcel csv file (feedback for UrbanSim)
      if (new File(uspModule.getMATSim4OpusTemp() + UrbanSimParcelCSVWriter.FILE_NAME).exists())
        FileCopy.fileCopy(
            new File(uspModule.getMATSim4OpusTemp() + UrbanSimParcelCSVWriter.FILE_NAME),
            new File(savePath + UrbanSimParcelCSVWriter.FILE_NAME));
      // backup person csv file (feedback for UrbanSim)
      if (new File(uspModule.getMATSim4OpusTemp() + UrbanSimPersonCSVWriter.FILE_NAME).exists())
        FileCopy.fileCopy(
            new File(uspModule.getMATSim4OpusTemp() + UrbanSimPersonCSVWriter.FILE_NAME),
            new File(savePath + UrbanSimPersonCSVWriter.FILE_NAME));
      // backup travel_data csv file (feedback for UrbanSim)
      if (new File(uspModule.getMATSim4OpusTemp() + Zone2ZoneImpedancesControlerListener.FILE_NAME)
          .exists())
        FileCopy.fileCopy(
            new File(
                uspModule.getMATSim4OpusTemp() + Zone2ZoneImpedancesControlerListener.FILE_NAME),
            new File(savePath + Zone2ZoneImpedancesControlerListener.FILE_NAME));

      // backup plotting files free speed
      String fileName =
          Labels.FREESPEED_FILENAME
              + (double) acm.getCellSizeCellBasedAccessibility()
              + InternalConstants.FILE_TYPE_TXT;
      if (new File(uspModule.getMATSim4OpusTemp() + fileName).exists())
        FileCopy.fileCopy(
            new File(uspModule.getMATSim4OpusTemp() + fileName), new File(savePath + fileName));
      // backup plotting files for car
      fileName =
          Labels.CAR_FILENAME
              + (double) acm.getCellSizeCellBasedAccessibility()
              + InternalConstants.FILE_TYPE_TXT;
      if (new File(uspModule.getMATSim4OpusTemp() + fileName).exists())
        FileCopy.fileCopy(
            new File(uspModule.getMATSim4OpusTemp() + fileName), new File(savePath + fileName));
      // backup plotting files for bike
      fileName =
          Labels.BIKE_FILENAME
              + (double) acm.getCellSizeCellBasedAccessibility()
              + InternalConstants.FILE_TYPE_TXT;
      if (new File(uspModule.getMATSim4OpusTemp() + fileName).exists())
        FileCopy.fileCopy(
            new File(uspModule.getMATSim4OpusTemp() + fileName), new File(savePath + fileName));
      // backup plotting files for walk
      fileName =
          Labels.WALK_FILENAME
              + (double) acm.getCellSizeCellBasedAccessibility()
              + InternalConstants.FILE_TYPE_TXT;
      if (new File(uspModule.getMATSim4OpusTemp() + fileName).exists())
        FileCopy.fileCopy(
            new File(uspModule.getMATSim4OpusTemp() + fileName), new File(savePath + fileName));
    } catch (Exception e) {
      e.printStackTrace();
    }
    log.info("Saving UrbanSim and MATSim outputs done!");
  }