/**
   * Test how the scoring function reacts when the first and the last activity do not have the same
   * act-type.
   */
  @Test
  public void testDifferentFirstLastAct() {
    Fixture f = new Fixture();
    // change the last act to something different than the first act
    ((Activity) f.plan.getPlanElements().get(8)).setType("h2");

    PlanCalcScoreConfigGroup.ActivityParams params =
        new PlanCalcScoreConfigGroup.ActivityParams("h2");
    params.setTypicalDuration(8 * 3600);
    f.config.planCalcScore().addActivityParams(params);
    f.config.planCalcScore().getActivityParams("h").setTypicalDuration(6.0 * 3600);

    double perf = +6.0;
    f.config.planCalcScore().setPerforming_utils_hr(perf);
    double zeroUtilDurW = getZeroUtilDuration_hrs(3.0, 1.0);
    double zeroUtilDurH = getZeroUtilDuration_hrs(6.0, 1.0);
    double zeroUtilDurH2 = getZeroUtilDuration_hrs(8.0, 1.0);

    assertEquals(
        perf * 3.0 * Math.log(2.5 / zeroUtilDurW)
            + perf * 3.0 * Math.log(2.75 / zeroUtilDurW)
            + perf * 3.0 * Math.log(2.5 / zeroUtilDurW)
            + perf * 6.0 * Math.log(7.0 / zeroUtilDurH)
            + perf * 8.0 * Math.log(7.75 / zeroUtilDurH2),
        calcScore(f),
        EPSILON);
  }
    public Fixture() {
      firstLegStartTime = 7 * 3600;
      firstLegTravelTime = 30 * 60;
      thirdLegTravelTime = 30 * 60;
      secondLegStartTime = 10 * 3600;
      secondLegTravelTime = 15 * 60;
      thirdLegStartTime = 13 * 3600;
      fourthLegStartTime = 16 * 3600;
      fourthLegTravelTime = 15 * 60;
      // home act end 7am
      // work 7:30 to 10:00
      // work 10:15 to 13:00
      // work 13:30 to 16:00
      // home 15:15 to ...

      this.config = ConfigUtils.createConfig();
      PlanCalcScoreConfigGroup scoring = this.config.planCalcScore();
      scoring.setBrainExpBeta(2.0);

      scoring.setConstantCar(0.0);
      scoring.setConstantPt(0.0);
      scoring.setConstantWalk(0.0);
      scoring.setConstantBike(0.0);

      scoring.setEarlyDeparture_utils_hr(0.0);
      scoring.setLateArrival_utils_hr(0.0);
      scoring.setMarginalUtlOfWaiting_utils_hr(0.0);
      scoring.setPerforming_utils_hr(0.0);
      scoring.setTraveling_utils_hr(0.0);
      scoring.setTravelingPt_utils_hr(0.0);
      scoring.setTravelingWalk_utils_hr(0.0);
      scoring.setTravelingBike_utils_hr(0.0);

      scoring.setMarginalUtilityOfMoney(1.);
      scoring.setMonetaryDistanceCostRateCar(0.0);
      scoring.setMonetaryDistanceCostRatePt(0.0);

      // setup activity types h and w for scoring
      PlanCalcScoreConfigGroup.ActivityParams params =
          new PlanCalcScoreConfigGroup.ActivityParams("h");
      params.setTypicalDuration(15 * 3600);
      scoring.addActivityParams(params);

      params = new PlanCalcScoreConfigGroup.ActivityParams("w");
      params.setTypicalDuration(3 * 3600);
      scoring.addActivityParams(params);

      this.scenario = ScenarioUtils.createScenario(config);
      this.network = (NetworkImpl) this.scenario.getNetwork();
      Node node1 =
          this.network.createAndAddNode(Id.create("1", Node.class), new CoordImpl(0.0, 0.0));
      Node node2 =
          this.network.createAndAddNode(Id.create("2", Node.class), new CoordImpl(500.0, 0.0));
      Node node3 =
          this.network.createAndAddNode(Id.create("3", Node.class), new CoordImpl(5500.0, 0.0));
      Node node4 =
          this.network.createAndAddNode(Id.create("4", Node.class), new CoordImpl(6000.0, 0.0));
      Node node5 =
          this.network.createAndAddNode(Id.create("5", Node.class), new CoordImpl(11000.0, 0.0));
      Node node6 =
          this.network.createAndAddNode(Id.create("6", Node.class), new CoordImpl(11500.0, 0.0));
      Node node7 =
          this.network.createAndAddNode(Id.create("7", Node.class), new CoordImpl(16500.0, 0.0));
      Node node8 =
          this.network.createAndAddNode(Id.create("8", Node.class), new CoordImpl(17000.0, 0.0));
      Node node9 =
          this.network.createAndAddNode(Id.create("9", Node.class), new CoordImpl(22000.0, 0.0));
      Node node10 =
          this.network.createAndAddNode(Id.create("10", Node.class), new CoordImpl(22500.0, 0.0));

      Link link1 =
          this.network.createAndAddLink(Id.create("1", Link.class), node1, node2, 500, 25, 3600, 1);
      Link link2 =
          this.network.createAndAddLink(
              Id.create("2", Link.class), node2, node3, 25000, 50, 3600, 1);
      Link link3 =
          this.network.createAndAddLink(Id.create("3", Link.class), node3, node4, 500, 25, 3600, 1);
      this.network.createAndAddLink(Id.create("4", Link.class), node4, node5, 5000, 50, 3600, 1);
      Link link5 =
          this.network.createAndAddLink(Id.create("5", Link.class), node5, node6, 500, 25, 3600, 1);
      this.network.createAndAddLink(Id.create("6", Link.class), node6, node7, 5000, 50, 3600, 1);
      Link link7 =
          this.network.createAndAddLink(Id.create("7", Link.class), node7, node8, 500, 25, 3600, 1);
      this.network.createAndAddLink(Id.create("8", Link.class), node8, node9, 5000, 50, 3600, 1);
      Link link9 =
          this.network.createAndAddLink(
              Id.create("9", Link.class), node9, node10, 500, 25, 3600, 1);

      this.person = new PersonImpl(Id.create("1", Person.class));
      this.plan = this.person.createAndAddPlan(true);

      ActivityImpl firstActivity = this.plan.createAndAddActivity("h", link1.getId());
      firstActivity.setEndTime(firstLegStartTime);

      Leg leg = this.plan.createAndAddLeg(TransportMode.car);
      leg.setDepartureTime(firstLegStartTime);
      leg.setTravelTime(firstLegTravelTime);
      NetworkRoute route1 = new LinkNetworkRouteImpl(link1.getId(), link3.getId());
      route1.setLinkIds(link1.getId(), Arrays.asList(link2.getId()), link3.getId());
      route1.setTravelTime(firstLegTravelTime);
      route1.setDistance(RouteUtils.calcDistance(route1, this.network));
      leg.setRoute(route1);

      ActivityImpl secondActivity = this.plan.createAndAddActivity("w", link3.getId());
      secondActivity.setStartTime(firstLegStartTime + firstLegTravelTime);
      secondActivity.setEndTime(secondLegStartTime);
      leg = this.plan.createAndAddLeg(TransportMode.pt);
      leg.setDepartureTime(secondLegStartTime);
      leg.setTravelTime(secondLegTravelTime);
      Route route2 = new GenericRouteImpl(link3.getId(), link5.getId());
      route2.setTravelTime(secondLegTravelTime);
      route2.setDistance(20000.0);
      leg.setRoute(route2);

      ActivityImpl thirdActivity = this.plan.createAndAddActivity("w", link5.getId());
      thirdActivity.setStartTime(secondLegStartTime + secondLegTravelTime);
      thirdActivity.setEndTime(thirdLegStartTime);
      leg = this.plan.createAndAddLeg(TransportMode.walk);
      leg.setDepartureTime(thirdLegStartTime);
      leg.setTravelTime(thirdLegTravelTime);
      Route route3 = new GenericRouteImpl(link5.getId(), link7.getId());
      route3.setTravelTime(thirdLegTravelTime);
      route3.setDistance(CoordUtils.calcDistance(link5.getCoord(), link7.getCoord()));
      leg.setRoute(route3);

      ActivityImpl fourthActivity = this.plan.createAndAddActivity("w", link7.getId());
      fourthActivity.setStartTime(thirdLegStartTime + thirdLegTravelTime);
      fourthActivity.setEndTime(fourthLegStartTime);
      leg = this.plan.createAndAddLeg(TransportMode.bike);
      leg.setDepartureTime(fourthLegStartTime);
      leg.setTravelTime(fourthLegTravelTime);
      Route route4 = new GenericRouteImpl(link7.getId(), link9.getId());
      route4.setTravelTime(fourthLegTravelTime);
      route4.setDistance(CoordUtils.calcDistance(link7.getCoord(), link9.getCoord()));
      leg.setRoute(route4);

      ActivityImpl fifthActivity = this.plan.createAndAddActivity("h", link9.getId());
      fifthActivity.setStartTime(fourthLegStartTime + fourthLegTravelTime);
      this.scenario.getPopulation().addPerson(this.person);
    }
  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);
  }
Esempio n. 4
0
  public static void main(String[] args) throws IOException {
    FileUtils.deleteDirectory(new File(OUT_DIR));
    String inputDir = OUT_DIR + "/input";
    String outputDir = OUT_DIR + "/output";
    new File(inputDir).mkdirs();

    Config c = ConfigUtils.createConfig();

    c.global().setCoordinateSystem("EPSG:3395");
    Scenario sc = ScenarioUtils.createScenario(c);

    int destination = createNetwork(sc);
    ((NetworkImpl) sc.getNetwork()).setEffectiveCellSize(.26);
    ((NetworkImpl) sc.getNetwork()).setEffectiveLaneWidth(.71);
    ((NetworkImpl) sc.getNetwork()).setCapacityPeriod(1);

    c.network().setInputFile(inputDir + "/network.xml.gz");

    // c.strategy().addParam("Module_1",
    // "playground.gregor.sim2d_v4.replanning.Sim2DReRoutePlanStrategy");
    c.strategy().addParam("Module_1", "ReRoute");
    c.strategy().addParam("ModuleProbability_1", ".5");
    c.strategy().addParam("ModuleDisableAfterIteration_1", "10");
    c.strategy().addParam("Module_2", "ChangeExpBeta");
    c.strategy().addParam("ModuleProbability_2", ".5");

    c.controler().setOutputDirectory(outputDir);
    c.controler().setLastIteration(20);

    c.plans().setInputFile(inputDir + "/population.xml.gz");

    PlanCalcScoreConfigGroup.ActivityParams pre =
        new PlanCalcScoreConfigGroup.ActivityParams("origin");
    pre.setTypicalDuration(49); // needs to be geq 49, otherwise when
    // running a simulation one gets
    // "java.lang.RuntimeException: zeroUtilityDuration of type pre-evac must be greater than 0.0.
    // Did you forget to specify the typicalDuration?"
    // the reason is the double precision. see also comment in
    // ActivityUtilityParameters.java (gl)
    pre.setMinimalDuration(49);
    pre.setClosingTime(49);
    pre.setEarliestEndTime(49);
    pre.setLatestStartTime(49);
    pre.setOpeningTime(49);

    PlanCalcScoreConfigGroup.ActivityParams post =
        new PlanCalcScoreConfigGroup.ActivityParams("destination");
    post.setTypicalDuration(49); // dito
    post.setMinimalDuration(49);
    post.setClosingTime(49);
    post.setEarliestEndTime(49);
    post.setLatestStartTime(49);
    post.setOpeningTime(49);
    sc.getConfig().planCalcScore().addActivityParams(pre);
    sc.getConfig().planCalcScore().addActivityParams(post);

    sc.getConfig().planCalcScore().setLateArrival_utils_hr(0.);
    sc.getConfig().planCalcScore().setPerforming_utils_hr(0.);

    QSimConfigGroup qsim = sc.getConfig().qsim();
    // qsim.setEndTime(20 * 60);
    c.controler().setMobsim("ctsim");
    c.global().setCoordinateSystem("EPSG:3395");

    c.qsim().setEndTime(30 * 60);

    new ConfigWriter(c).write(inputDir + "/config.xml");

    new NetworkWriter(sc.getNetwork()).write(c.network().getInputFile());

    createPopulation(sc, destination);

    Population pop = sc.getPopulation();
    new PopulationWriter(pop, sc.getNetwork()).write(c.plans().getInputFile());

    CTRunner.main(new String[] {inputDir + "/config.xml", "true"});
  }