public static void main(final String[] args) {

    Config config;
    if (args.length == 0) {
      config = ConfigUtils.loadConfig("examples/equil/config.xml");
    } else {
      config = ConfigUtils.loadConfig(args[0]);
    }

    int lastStrategyIdx = config.strategy().getStrategySettings().size();
    StrategySettings stratSets =
        new StrategySettings(Id.create(lastStrategyIdx + 1, StrategySettings.class));
    stratSets.setStrategyName("doSomethingSpecial");
    stratSets.setWeight(0.1);
    config.strategy().addStrategySettings(stratSets);

    final Controler controler = new Controler(config);
    controler.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            addPlanStrategyBinding("doSomethingSpecial").toProvider(MyPlanStrategyFactory.class);
          }
        });
    controler.run();
  }
  private void createConfig() {

    Config config = sc.getConfig();

    config.controler().setOutputDirectory(outputDir + "/output/" + congestionImpl);
    config.controler().setFirstIteration(0);
    config.controler().setLastIteration(20);
    config.controler().setWriteEventsInterval(10);
    config.controler().setMobsim("qsim");
    config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists);

    config.qsim().setEndTime(9 * 3600.);

    StrategySettings reRoute = new StrategySettings(ConfigUtils.createAvailableStrategyId(config));
    reRoute.setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.ReRoute.name());
    reRoute.setWeight(0.10);
    config.strategy().addStrategySettings(reRoute);
    config.strategy().setFractionOfIterationsToDisableInnovation(0.7);

    StrategySettings changeExpBeta =
        new StrategySettings(ConfigUtils.createAvailableStrategyId(config));
    changeExpBeta.setStrategyName("ChangeExpBeta");
    changeExpBeta.setWeight(0.9);
    config.strategy().addStrategySettings(changeExpBeta);

    ActivityParams o1 = new ActivityParams("o1");
    ActivityParams o2 = new ActivityParams("o2");
    ActivityParams d1 = new ActivityParams("d1");
    ActivityParams d2 = new ActivityParams("d2");

    o1.setTypicalDuration(8 * 3600);
    o2.setTypicalDuration(8 * 3600);
    d1.setTypicalDuration(8 * 3600);
    d2.setTypicalDuration(8 * 3600);

    config.planCalcScore().addActivityParams(o1);
    config.planCalcScore().addActivityParams(o2);
    config.planCalcScore().addActivityParams(d1);
    config.planCalcScore().addActivityParams(d2);

    new ConfigWriter(config).write(outputDir + "/input/input_config.xml.gz");
  }
  public static void main(String[] args) {
    Config config = new Config();
    config.addCoreModules();
    Controler controler = new Controler(config);

    // controler settings
    controler
        .getConfig()
        .controler()
        .setOverwriteFileSetting(
            true
                ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles
                : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists);
    controler.getConfig().controler().setCreateGraphs(false);

    // controlerConfigGroup
    ControlerConfigGroup ccg = controler.getConfig().controler();
    ccg.setOutputDirectory(outputPath);
    ccg.setFirstIteration(0);
    ccg.setLastIteration(0);
    ccg.setMobsim("qsim");
    Set set = new HashSet();
    set.add(EventsFileFormat.xml);
    ccg.setEventsFileFormats(set);
    //		ccg.setRunId("321");

    // qsimConfigGroup
    QSimConfigGroup qcg = controler.getConfig().qsim();
    qcg.setStartTime(0 * 3600.);
    qcg.setEndTime(30 * 3600.);
    qcg.setFlowCapFactor(0.1);
    qcg.setStorageCapFactor(0.3);
    //		qcg.setFlowCapFactor(0.01);
    //		qcg.setStorageCapFactor(0.03);
    qcg.setNumberOfThreads(1);
    qcg.setRemoveStuckVehicles(false);
    qcg.setStuckTime(10.0);

    // planCalcScoreConfigGroup
    PlanCalcScoreConfigGroup pcs = controler.getConfig().planCalcScore();
    Set<String> activities = new HashSet<String>();
    activities.add("unknown");
    activities.add("work");
    activities.add("pickup");
    activities.add("with adult");
    activities.add("other");
    activities.add("pvWork");
    activities.add("pvHome");
    activities.add("gvHome");
    activities.add("education");
    activities.add("business");
    activities.add("shopping");
    activities.add("private");
    activities.add("leisure");
    activities.add("sports");
    activities.add("home");
    activities.add("friends");

    for (String activity : activities) {
      ActivityParams params = new ActivityParams(activity);
      params.setTypicalDuration(30 * 3600);
      pcs.addActivityParams(params);
    }

    // strategy
    StrategyConfigGroup scg = controler.getConfig().strategy();
    StrategySettings strategySettings =
        new StrategySettings(Id.create("1", StrategySettings.class));
    strategySettings.setStrategyName("ChangeExpBeta");
    strategySettings.setWeight(1.0);
    scg.addStrategySettings(strategySettings);

    // network
    NetworkConfigGroup ncg = controler.getConfig().network();
    ncg.setInputFile(networkFile);

    // plans
    PlansConfigGroup pcg = controler.getConfig().plans();
    pcg.setInputFile(plansFile);

    // define emission tool input files

    EmissionsConfigGroup ecg = new EmissionsConfigGroup();
    controler.getConfig().addModule(ecg);
    ecg.setEmissionRoadTypeMappingFile(roadTypeMappingFile);
    ecg.setEmissionVehicleFile(emissionVehicleFile);

    ecg.setAverageWarmEmissionFactorsFile(averageFleetWarmEmissionFactorsFile);
    ecg.setAverageColdEmissionFactorsFile(averageFleetColdEmissionFactorsFile);

    ecg.setUsingDetailedEmissionCalculation(isUsingDetailedEmissionCalculation);
    ecg.setDetailedWarmEmissionFactorsFile(detailedWarmEmissionFactorsFile);
    ecg.setDetailedColdEmissionFactorsFile(detailedColdEmissionFactorsFile);

    // TODO: the following does not work yet. Need to force controler to always write events in the
    // last iteration.
    VspExperimentalConfigGroup vcg = controler.getConfig().vspExperimental();
    vcg.setWritingOutputEvents(false);

    controler.addControlerListener(new EmissionControlerListener());
    controler.run();
  }
Exemple #4
0
  public static void main(String[] args) {

    // loading and modifying the config:
    Config config;
    if (args.length > 0) {
      config = ConfigUtils.loadConfig(args[0]);
    } else {
      throw new RuntimeException("needs argument config.xml");
    }

    // request FEATHERS2 as a PlanStrategy (it is added to the controler further below):
    StrategySettings stratSets =
        new StrategySettings(ConfigUtils.createAvailableStrategyId(config));
    stratSets.setStrategyName(FEATHERS2);
    stratSets.setWeight(0.1);
    config.strategy().addStrategySettings(stratSets);

    // loading the scenario:
    final Scenario scenario = ScenarioUtils.loadScenario(config);

    // loading and modifying the controler:
    final Controler ctrl = new Controler(scenario);

    // generate the FEATHERS adapter class:
    final FeathersModule feathers2 = new FeathersModule();

    // make it an events handler (so it can listen to events; a different solution may be desired
    // here)
    ctrl.getEvents().addHandler(feathers2);

    // add it as a PlanStrategy:
    final javax.inject.Provider<PlanStrategy> planStrategyFactory =
        new javax.inject.Provider<PlanStrategy>() {
          @Override
          public PlanStrategy get() {
            PlanSelector<Plan, Person> planSelector = new RandomPlanSelector<>();
            PlanStrategyImpl.Builder builder = new PlanStrategyImpl.Builder(planSelector);
            PlanStrategyModule module =
                new PlanStrategyModule() {
                  @Override
                  public void prepareReplanning(ReplanningContext replanningContext) {}

                  @Override
                  public void handlePlan(Plan plan) {
                    // the following should (test!!!) only retain the plan we are looking at:
                    Person person = scenario.getPopulation().getPersons().get(plan.getPerson());
                    List<Plan> planToKeep = new ArrayList<>();
                    planToKeep.add(plan);
                    person.getPlans().retainAll(planToKeep);

                    PopulationFactory pf = scenario.getPopulation().getFactory();

                    // modify plan by feathers:
                    plan = feathers2.createPlan(plan.getPerson(), pf);
                  }

                  @Override
                  public void finishReplanning() {}
                };
            builder.addStrategyModule(module);
            return builder.build();
          }
        };
    ctrl.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            addPlanStrategyBinding(FEATHERS2).toProvider(planStrategyFactory);
          }
        });

    // running the controler:
    ctrl.run();
  }
  /**
   * Setting up the MATSim {@link Config} so that it runs 20 iterations for a commercial vehicle
   * population.
   *
   * @param folder the specific folder to which the output will be written. Also, it assumes the
   *     following files are available as input in the folder:
   *     <ul>
   *       <li>{@code population.xml.gz} of commercial vehicles, each person with a plan. Only
   *           activity locations are required. The {@link Leg}s are allowed to take {@code
   *           commercial} as mode.
   *       <li>{@code populationAttributes.xml.gz} indicating which individuals are part of the
   *           <i>commercial vehicle</i> subpopulation. For that the only attribute required, namely
   *           {@code subpopulation}, needs to be set as {@code commercial}.
   *     </ul>
   *
   * @param machine the computer on which the run is executed. This just sets up the number of
   *     threads without having to hard code it in the class. The following values are currently
   *     supported:
   *     <ul>
   *       <li>{@code HOBBES} using 40 threads;
   *       <li>{@code MAC_MINI} the machine in Engineering 2, Room 3-13.1, a dual core i7 using 4
   *           threads;
   *       <li>{@code MACBOOK_PRO} is Johan W. Joubert's laptop, a dual core i5 using 4 threads.
   *     </ul>
   *
   * @return
   */
  public static Config setupConfig(String folder, Machine machine) {
    Config config = ConfigUtils.createConfig();

    /* Set global settings. */
    config.global().setNumberOfThreads(machine.getThreads());
    config.global().setCoordinateSystem("WGS84_SA_Albers");

    /* Set files and folders. */
    config.controler().setOutputDirectory(folder + "output/");
    config.controler().setFirstIteration(0);
    config.controler().setLastIteration(100);
    config.controler().setWriteEventsInterval(20);

    /* Network. */
    config.network().setInputFile(folder + "network.xml.gz");

    /* Population */
    config.plans().setInputFile(folder + "population.xml.gz");
    config.plans().setInputPersonAttributeFile(folder + "populationAttributes.xml.gz");
    config
        .plans()
        .setActivityDurationInterpretation(
            PlansConfigGroup.ActivityDurationInterpretation.tryEndTimeThenDuration);

    /* Facilities */
    config.facilities().setInputFile(folder + "facilities.xml.gz");

    /* QSim */
    config.qsim().setNumberOfThreads(machine.getThreads());
    String[] modes = {"car", "commercial"};
    config.qsim().setMainModes(Arrays.asList(modes));
    config.plansCalcRoute().setNetworkModes(Arrays.asList(modes));

    /* PlanCalcScore */
    ActivityParams major = new ActivityParams("major");
    major.setTypicalDuration(10 * 3600);
    config.planCalcScore().addActivityParams(major);

    ActivityParams minor = new ActivityParams("minor");
    minor.setTypicalDuration(1880);
    config.planCalcScore().addActivityParams(minor);

    /* Generic strategy */
    StrategySettings changeExpBetaStrategySettings =
        new StrategySettings(ConfigUtils.createAvailableStrategyId(config));
    changeExpBetaStrategySettings.setStrategyName(
        DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta.toString());
    changeExpBetaStrategySettings.setWeight(0.8);
    config.strategy().addStrategySettings(changeExpBetaStrategySettings);
    /* Subpopulation strategy. */
    StrategySettings commercialStrategy =
        new StrategySettings(ConfigUtils.createAvailableStrategyId(config));
    commercialStrategy.setStrategyName(
        DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta.toString());
    commercialStrategy.setWeight(0.85);
    commercialStrategy.setSubpopulation("commercial");
    config.strategy().addStrategySettings(commercialStrategy);
    /* Subpopulation ReRoute. Switch off after a time. */
    StrategySettings commercialReRoute =
        new StrategySettings(ConfigUtils.createAvailableStrategyId(config));
    commercialReRoute.setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.ReRoute.name());
    commercialReRoute.setWeight(0.15);
    commercialReRoute.setSubpopulation("commercial");
    commercialReRoute.setDisableAfter(85);
    config.strategy().addStrategySettings(commercialReRoute);

    return config;
  }
Exemple #6
0
  public void configRun() {
    Collection<String> mainModes = Arrays.asList("car", "motorbike", "bike");

    config.plans().setInputFile("../../../repos/runs-svn/patnaIndia/inputs/selectedPlansOnly.xml");
    config.network().setInputFile("../../../repos/runs-svn/patnaIndia/inputs/networkUniModal.xml");
    config
        .counts()
        .setCountsFileName(
            "../../../repos/runs-svn/patnaIndia/inputs/counts/countsCarMotorbikeBike.xml");

    config.counts().setOutputFormat("all");
    config.counts().setWriteCountsInterval(100);
    config.counts().setCountsScaleFactor(94.52);

    // ===
    //		VehiclesConfigGroup vehiclesCnfGrp = new VehiclesConfigGroup();
    //		vehiclesCnfGrp.setInputFile(outputDir+"/vehiclesPatna.xml");
    //		vehiclesCnfGrp.setMainModes(mainModes);
    //		config.addModule(vehiclesCnfGrp);
    // ===

    config.controler().setFirstIteration(0);
    config.controler().setLastIteration(200);
    config.controler().setMobsim("qsim");
    config.controler().setWriteEventsInterval(100);
    config.controler().setWritePlansInterval(100);
    config.controler().setWriteSnapshotsInterval(100);

    config.controler().setSnapshotFormat(Arrays.asList("otfvis"));

    config.qsim().setFlowCapFactor(0.011); // 1.06% sample
    config.qsim().setStorageCapFactor(0.033);
    config.qsim().setSnapshotPeriod(5 * 60);
    config.qsim().setEndTime(36 * 3600);
    config.qsim().setLinkDynamics(LinkDynamics.PassingQ.toString());
    config.qsim().setMainModes(mainModes);

    config.setParam("TimeAllocationMutator", "mutationAffectsDuration", "false");
    config.setParam("TimeAllocationMutator", "mutationRange", "7200.0");

    StrategySettings expChangeBeta = new StrategySettings(Id.create("1", StrategySettings.class));
    expChangeBeta.setStrategyName("ChangeExpBeta");
    expChangeBeta.setWeight(0.9);

    StrategySettings reRoute = new StrategySettings(Id.create("2", StrategySettings.class));
    reRoute.setStrategyName("ReRoute");
    reRoute.setWeight(0.1);

    //		StrategySettings modeChoice = new StrategySettings(Id.create("4",StrategySettings.class));
    //		modeChoice.setModuleName("ChangeLegMode");
    //		modeChoice.setProbability(0.05);

    StrategySettings timeAllocationMutator =
        new StrategySettings(Id.create("3", StrategySettings.class));
    timeAllocationMutator.setStrategyName("TimeAllocationMutator");
    timeAllocationMutator.setWeight(0.05);

    //		config.setParam("changeLegMode", "modes", "car,bike,motorbike,pt,walk");

    config.strategy().setMaxAgentPlanMemorySize(5);
    config.strategy().addStrategySettings(expChangeBeta);
    config.strategy().addStrategySettings(reRoute);
    //		config.strategy().addStrategySettings(modeChoice);
    config.strategy().addStrategySettings(timeAllocationMutator);

    config.strategy().setFractionOfIterationsToDisableInnovation(0.8);

    // vsp default
    config.plans().setRemovingUnneccessaryPlanAttributes(true);
    config.vspExperimental().addParam("vspDefaultsCheckingLevel", "abort");
    // vsp default

    ActivityParams workAct = new ActivityParams("work");
    workAct.setTypicalDuration(8 * 3600);
    config.planCalcScore().addActivityParams(workAct);

    ActivityParams homeAct = new ActivityParams("home");
    homeAct.setTypicalDuration(12 * 3600);
    config.planCalcScore().addActivityParams(homeAct);

    config.planCalcScore().setMarginalUtlOfWaiting_utils_hr(0); // changed to 0 from (-2) earlier

    config.planCalcScore().setPerforming_utils_hr(6.0);
    config
        .planCalcScore()
        .getModes()
        .get(TransportMode.car)
        .setMarginalUtilityOfTraveling((double) 0);
    config
        .planCalcScore()
        .getModes()
        .get(TransportMode.bike)
        .setMarginalUtilityOfTraveling((double) 0);
    config
        .planCalcScore()
        .getModes()
        .get(TransportMode.other)
        .setMarginalUtilityOfTraveling((double) 0);
    config
        .planCalcScore()
        .getModes()
        .get(TransportMode.pt)
        .setMarginalUtilityOfTraveling((double) 0);
    config
        .planCalcScore()
        .getModes()
        .get(TransportMode.walk)
        .setMarginalUtilityOfTraveling((double) 0);

    double constantCar = -3.50;
    config.planCalcScore().getModes().get(TransportMode.car).setConstant(constantCar);
    double constantOther = -2.2;
    config.planCalcScore().getModes().get(TransportMode.other).setConstant(constantOther);
    config.planCalcScore().getModes().get(TransportMode.bike).setConstant((double) 0);
    double constantPt = -3.4;
    config.planCalcScore().getModes().get(TransportMode.pt).setConstant(constantPt);
    double constantWalk = -0.0;
    config.planCalcScore().getModes().get(TransportMode.walk).setConstant(constantWalk);

    // config.planCalcScore().getOrCreateModeParams("bike").setMarginalUtilityOfDistance(-0.01);

    config.plansCalcRoute().setNetworkModes(mainModes);
    config.plansCalcRoute().setBeelineDistanceFactor(1.0);
    /*
     * Beeline distnace factor is set to one so now the travel time will be calculated by given speed,
     * assuming in real scenario how much time it can take
     * For example for walk trips 5 - 6 kph is normal speed but in that case travel time will be
     * total beeline distance/ speed; which will not be realistic, so let's make it to 4 kph
     * similarly for bus also normal speed can be taken as 40 kph so teleported mode speed should be set to 20kph
     * Travel distance is taken care of in event handlers by taking a factor of 1.1 and 1.5 for walk and pt respectively
     */
    config.plansCalcRoute().setTeleportedModeSpeed("walk", 4 / 3.6);
    config.plansCalcRoute().setTeleportedModeSpeed("pt", 20 / 3.6);
    //		config.plansCalcRoute().setTeleportedModeSpeed("motorbike", 20/3.6);
    //		config.plansCalcRoute().setTeleportedModeSpeed("car", 20/3.6);
    //		config.plansCalcRoute().setTeleportedModeSpeed("bike",10/3.6);

    if (MyFirstControler.seepage) {
      config.setParam("seepage", "isSeepageAllowed", "true");
      config.setParam("seepage", "seepMode", "bike");
      config.setParam("seepage", "isSeepModeStorageFree", "false");
      //			config.controler().setOutputDirectory("../../../repos/runs-svn/patnaIndia/run105/");
      config.controler().setOutputDirectory(outputDir + "/seepage/");
      new ConfigWriter(config).write(outputDir + "/seepage/configPatna_seepage.xml");
    } else {
      config.controler().setOutputDirectory(outputDir + "/passing/");
      new ConfigWriter(config).write(outputDir + "/passing/configPatna_passing.xml");
    }
  }
  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());
  }
  public static void main(String[] args) {
    // see an example with detailed explanations -- package
    // opdytsintegration.example.networkparameters.RunNetworkParameters
    Config config = ConfigUtils.loadConfig(EQUIL_DIR + "/config.xml");

    config.controler().setOutputDirectory(OUT_DIR);
    config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists);

    //		config.plans().setInputFile("relaxed_plans.xml.gz");
    config.plans().setInputFile("plans2000.xml.gz");

    // == default config has limited inputs
    StrategyConfigGroup strategies = config.strategy();
    strategies.clearStrategySettings();

    config.changeMode().setModes(new String[] {"car", "pt"});
    StrategySettings modeChoice = new StrategySettings();
    modeChoice.setStrategyName(
        DefaultPlanStrategiesModule.DefaultStrategy.ChangeSingleTripMode.name());
    modeChoice.setWeight(0.1);
    config.strategy().addStrategySettings(modeChoice);

    StrategySettings expChangeBeta = new StrategySettings();
    expChangeBeta.setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta.name());
    expChangeBeta.setWeight(0.9);
    config.strategy().addStrategySettings(expChangeBeta);

    for (PlanCalcScoreConfigGroup.ActivityParams params :
        config.planCalcScore().getActivityParams()) {
      params.setTypicalDurationScoreComputation(
          PlanCalcScoreConfigGroup.TypicalDurationScoreComputation.relative);
    }

    //		config.qsim().setTrafficDynamics( QSimConfigGroup.TrafficDynamics.withHoles );
    //
    //		if ( config.qsim().getTrafficDynamics()== QSimConfigGroup.TrafficDynamics.withHoles ) {
    //			config.qsim().setInflowConstraint(QSimConfigGroup.InflowConstraint.maxflowFromFdiag);
    //		}

    config.qsim().setUsingFastCapacityUpdate(true);

    // ==

    Scenario scenario = KNBerlinControler.prepareScenario(true, false, config);

    double time = 6 * 3600.;
    for (Person person : scenario.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      Activity activity = (Activity) plan.getPlanElements().get(0);
      activity.setEndTime(time);
      time++;
    }

    // ==

    // this is something like time bin generator
    int startTime = 0;
    int binSize = 3600; // can this be scenario simulation end time.
    int binCount = 24; // to me, binCount and binSize must be related
    TimeDiscretization timeDiscretization = new TimeDiscretization(startTime, binSize, binCount);

    Set<String> modes2consider = new HashSet<>();
    modes2consider.add("car");
    modes2consider.add("bike");

    OpdytsModalStatsControlerListener stasControlerListner =
        new OpdytsModalStatsControlerListener(modes2consider, EQUIL);

    // following is the  entry point to start a matsim controler together with opdyts
    MATSimSimulator<ModeChoiceDecisionVariable> simulator =
        new MATSimSimulator<>(new MATSimStateFactoryImpl<>(), scenario, timeDiscretization);
    simulator.addOverridingModule(
        new AbstractModule() {

          @Override
          public void install() {
            // add here whatever should be attached to matsim controler
            // some stats
            addControlerListenerBinding().toInstance(stasControlerListner);

            // from KN
            addControlerListenerBinding().to(KaiAnalysisListener.class);
            bind(CharyparNagelScoringParametersForPerson.class)
                .to(EveryIterationScoringParameters.class);
          }
        });

    // this is the objective Function which returns the value for given SimulatorState
    // in my case, this will be the distance based modal split
    ObjectiveFunction objectiveFunction =
        new ModeChoiceObjectiveFunction(
            EQUIL); // in this, the method argument (SimulatorStat) is not used.

    // search algorithm
    int maxIterations =
        10; // this many times simulator.run(...) and thus controler.run() will be called.
    int maxTransitions = Integer.MAX_VALUE;
    int populationSize =
        10; // the number of samples for decision variables, one of them will be drawn randomly for
    // the simulation.

    boolean interpolate = true;
    boolean includeCurrentBest = false;

    // randomize the decision variables (for e.g.\ utility parameters for modes)
    DecisionVariableRandomizer<ModeChoiceDecisionVariable> decisionVariableRandomizer =
        new ModeChoiceRandomizer(scenario, RandomizedUtilityParametersChoser.ONLY_ASC, EQUIL);

    // what would be the decision variables to optimize the objective function.
    ModeChoiceDecisionVariable initialDecisionVariable =
        new ModeChoiceDecisionVariable(scenario.getConfig().planCalcScore(), scenario, EQUIL);

    // what would decide the convergence of the objective function
    final int iterationsToConvergence = 200; //
    final int averagingIterations = 10;
    ConvergenceCriterion convergenceCriterion =
        new FixedIterationNumberConvergenceCriterion(iterationsToConvergence, averagingIterations);

    RandomSearch<ModeChoiceDecisionVariable> randomSearch =
        new RandomSearch<>(
            simulator,
            decisionVariableRandomizer,
            initialDecisionVariable,
            convergenceCriterion,
            maxIterations, // this many times simulator.run(...) and thus controler.run() will be
            // called.
            maxTransitions,
            populationSize,
            MatsimRandom.getRandom(),
            interpolate,
            objectiveFunction,
            includeCurrentBest);

    // probably, an object which decide about the inertia
    SelfTuner selfTuner = new SelfTuner(0.95);

    randomSearch.setLogPath(OUT_DIR);

    // run it, this will eventually call simulator.run() and thus controler.run
    randomSearch.run(selfTuner);
  }
  @Override
  public void notifyIterationStarts(IterationStartsEvent event) {

    if (event.getIteration()
        == this.congestionInfo.getScenario().getConfig().controler().getFirstIteration()) {

      this.nextDisableInnovativeStrategiesIteration =
          (int)
              (congestionInfo
                      .getScenario()
                      .getConfig()
                      .strategy()
                      .getFractionOfIterationsToDisableInnovation()
                  * congestionInfo.getDecongestionConfigGroup().getUPDATE_PRICE_INTERVAL());
      log.info(
          "next disable innovative strategies iteration: "
              + this.nextDisableInnovativeStrategiesIteration);

      if (this.nextDisableInnovativeStrategiesIteration != 0) {
        this.nextEnableInnovativeStrategiesIteration =
            (int) (congestionInfo.getDecongestionConfigGroup().getUPDATE_PRICE_INTERVAL() + 1);
      }
      log.info(
          "next enable innovative strategies iteration: "
              + this.nextEnableInnovativeStrategiesIteration);

    } else {

      if (event.getIteration() == this.nextDisableInnovativeStrategiesIteration) {
        // set weight to zero
        log.warn("Strategy weight adjustment (set to zero) in iteration " + event.getIteration());

        for (GenericPlanStrategy<Plan, Person> strategy :
            event.getServices().getStrategyManager().getStrategies(null)) {

          String strategyName = strategy.toString();
          if (isInnovativeStrategy(strategyName)) {
            log.info("Setting weight for " + strategyName + " to zero.");
            event.getServices().getStrategyManager().changeWeightOfStrategy(strategy, null, 0.0);
          }
        }

        this.nextDisableInnovativeStrategiesIteration +=
            congestionInfo.getDecongestionConfigGroup().getUPDATE_PRICE_INTERVAL();
        log.info(
            "next disable innovative strategies iteration: "
                + this.nextDisableInnovativeStrategiesIteration);

      } else if (event.getIteration() == this.nextEnableInnovativeStrategiesIteration) {
        // set weight back to original value

        if (event.getIteration()
            >= congestionInfo
                    .getScenario()
                    .getConfig()
                    .strategy()
                    .getFractionOfIterationsToDisableInnovation()
                * (congestionInfo.getScenario().getConfig().controler().getLastIteration()
                    - congestionInfo.getScenario().getConfig().controler().getFirstIteration())) {

          log.info(
              "Strategies are switched off by global settings. Do not set back the strategy parameters to original values...");

        } else {

          log.info(
              "Strategy weight adjustment (set back to original value) in iteration "
                  + event.getIteration());

          for (GenericPlanStrategy<Plan, Person> strategy :
              event.getServices().getStrategyManager().getStrategies(null)) {

            String strategyName = strategy.toString();
            if (isInnovativeStrategy(strategyName)) {

              double originalValue = -1.0;
              for (StrategySettings setting :
                  event.getServices().getConfig().strategy().getStrategySettings()) {
                log.info("setting: " + setting.getStrategyName());
                log.info("strategyName: " + strategyName);

                if (strategyName.contains(setting.getStrategyName())) {
                  originalValue = setting.getWeight();
                }
              }

              if (originalValue == -1.0) {
                throw new RuntimeException("Aborting...");
              }

              log.warn(
                  "Setting weight for "
                      + strategyName
                      + " back to original value: "
                      + originalValue);
              event
                  .getServices()
                  .getStrategyManager()
                  .changeWeightOfStrategy(strategy, null, originalValue);
            }
          }
          this.nextEnableInnovativeStrategiesIteration +=
              congestionInfo.getDecongestionConfigGroup().getUPDATE_PRICE_INTERVAL();
        }
      }
    }
  }