private void createDemand() {

    Population pop = sc.getPopulation();
    PopulationFactory fact = pop.getFactory();

    for (int i = 1; i <= 400; i++) {

      Person p = fact.createPerson(Id.createPersonId(i));
      Plan plan = fact.createPlan();
      p.addPlan(plan);
      Leg leg = fact.createLeg(TransportMode.car);
      Activity home;
      Activity work;

      if (i % 2 == 0) { // o --d1
        home = fact.createActivityFromCoord("o1", lo.getCoord());
        home.setEndTime(7 * 3600 + i);
        work = fact.createActivityFromCoord("d1", ld1.getCoord());
      } else /*if(i%2==0)*/ { // o --d2
        home = fact.createActivityFromCoord("o1", lo.getCoord());
        home.setEndTime(7 * 3600 + i);
        work = fact.createActivityFromCoord("d2", ld2.getCoord());
      }
      plan.addActivity(home);
      plan.addLeg(leg);
      plan.addActivity(work);
      pop.addPerson(p);
    }
    new PopulationWriter(pop).write(outputDir + "/input/input_plans.xml.gz");
  }
  private static void fillPlan(
      final Plan plan,
      final String mode,
      final Random r,
      final PopulationFactory pf,
      Coord homeCoord) {
    Activity h1 = pf.createActivityFromCoord("h", homeCoord);
    h1.setEndTime(7.0 * 3600 + r.nextDouble() * 3600.0);
    plan.addActivity(h1);

    Leg leg1 = pf.createLeg(mode);
    plan.addLeg(leg1);

    Coord workCoord;
    if (r.nextDouble() < 0.5) {
      workCoord =
          new Coord(
              (double) (int) (loc1X - 450 + 900.0 * r.nextDouble()),
              (double) (int) (loc1Y - 450 + 900.0 * r.nextDouble()));
    } else {
      workCoord =
          new Coord(
              (double) (int) (loc2X - 450 + 900.0 * r.nextDouble()),
              (double) (int) (loc2Y - 450 + 900.0 * r.nextDouble()));
    }
    Activity w = pf.createActivityFromCoord("w", workCoord);
    w.setEndTime(17.0 * 3600 + r.nextDouble() * 3600.0);
    plan.addActivity(w);

    Leg leg2 = pf.createLeg(mode);
    plan.addLeg(leg2);

    if (r.nextDouble() < 0.5) {
      // add shop activity
      Coord shopCoord;
      if (r.nextDouble() < 0.5) {
        shopCoord =
            new Coord(
                (double) (int) (loc1X - 450 + 900.0 * r.nextDouble()),
                (double) (int) (loc1Y - 450 + 900.0 * r.nextDouble()));
      } else {
        shopCoord =
            new Coord(
                (double) (int) (loc2X - 450 + 900.0 * r.nextDouble()),
                (double) (int) (loc2Y - 450 + 900.0 * r.nextDouble()));
      }
      Activity s = pf.createActivityFromCoord("s", shopCoord);
      s.setEndTime(w.getEndTime() + r.nextDouble() * 3600.0);
      plan.addActivity(s);

      Leg leg3 = pf.createLeg(mode);
      plan.addLeg(leg3);
    }

    Activity h2 = pf.createActivityFromCoord("h", homeCoord);
    plan.addActivity(h2);
  }
Exemple #3
0
  private void createOneVWTrucker(
      int i, Coord origin, Coord destination, String mode, String fromToPrefix) {
    Id<Person> personId = Id.createPersonId(fromToPrefix + i);
    Person person = scenario.getPopulation().getFactory().createPerson(personId);

    Plan plan = scenario.getPopulation().getFactory().createPlan();

    Activity source =
        scenario.getPopulation().getFactory().createActivityFromCoord("source", origin);
    double rand = random.nextDouble() * 18 * 60 * 60;
    source.setEndTime(rand);
    plan.addActivity(source);

    Leg outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(outboundTrip);

    Activity delivery =
        scenario.getPopulation().getFactory().createActivityFromCoord("delivery", destination);
    delivery.setMaximumDuration(3600);
    plan.addActivity(delivery);

    Leg inboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(inboundTrip);
    Activity source2 =
        scenario.getPopulation().getFactory().createActivityFromCoord("source", origin);
    plan.addActivity(source2);

    person.addPlan(plan);
    scenario
        .getPopulation()
        .getPersonAttributes()
        .putAttribute(person.getId().toString(), "subpopulation", "noRep");

    scenario.getPopulation().addPerson(person);
  }
Exemple #4
0
  private void createOneTransitTrucker(
      int i, Coord origin, Coord destination, String mode, String fromToPrefix) {
    Id<Person> personId = Id.createPersonId(fromToPrefix + i);
    Person person = scenario.getPopulation().getFactory().createPerson(personId);

    Plan plan = scenario.getPopulation().getFactory().createPlan();

    Activity cargo = scenario.getPopulation().getFactory().createActivityFromCoord("cargo", origin);
    int rand = random.nextInt(18 * 60 * 60) + 1;
    cargo.setEndTime(rand);
    plan.addActivity(cargo);

    Leg outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(outboundTrip);

    Activity cargod =
        scenario.getPopulation().getFactory().createActivityFromCoord("cargoD", destination);
    cargod.setMaximumDuration(3600);
    plan.addActivity(cargod);
    Leg inBundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(inBundTrip);

    Activity cargo2 =
        scenario.getPopulation().getFactory().createActivityFromCoord("cargo", origin);
    plan.addActivity(cargo2);

    person.addPlan(plan);
    scenario
        .getPopulation()
        .getPersonAttributes()
        .putAttribute(person.getId().toString(), "subpopulation", "noRep");
    scenario.getPopulation().addPerson(person);
  }
  private static Person createPerson(Scenario scenario, Coord home, Coord work, int i) {
    Random r = MatsimRandom.getRandom();
    PopulationFactory f = scenario.getPopulation().getFactory();
    Person p = f.createPerson(Id.createPersonId(i));
    Plan plan = f.createPlan();
    p.addPlan(plan);
    Activity h1 = f.createActivityFromCoord("home", home);
    h1.setEndTime(6 * 3600 + r.nextInt(4 * 3600));
    Leg leg = f.createLeg("taxibus");
    Activity w = f.createActivityFromCoord("work", work);
    w.setEndTime(12 * 3600 + r.nextInt(6 * 3600));
    Leg leg2 = f.createLeg("taxibus");
    Activity h2 = f.createActivityFromCoord("home", home);
    plan.addActivity(h1);
    plan.addLeg(leg);
    plan.addActivity(w);
    plan.addLeg(leg2);
    plan.addActivity(h2);

    return p;
  }
Exemple #6
0
  private void createOneStudent(
      int i, Coord coord, Coord coordUniversity, String mode, String fromToPrefix) {
    int additionalTrips = random.nextInt(4);
    Id<Person> personId = Id.createPersonId(fromToPrefix + i);
    Person person = scenario.getPopulation().getFactory().createPerson(personId);

    Plan plan = scenario.getPopulation().getFactory().createPlan();

    Activity home = scenario.getPopulation().getFactory().createActivityFromCoord("home", coord);
    home.setEndTime(8 * 60 * 60 + 2 * 3600 * random.nextDouble());
    plan.addActivity(home);

    Leg outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(outboundTrip);

    Activity university =
        scenario
            .getPopulation()
            .getFactory()
            .createActivityFromCoord("university", coordUniversity);
    university.setEndTime(16 * 60 * 60 + 2 * 3600 * random.nextDouble());
    plan.addActivity(university);

    if (additionalTrips == 1 || additionalTrips == 3) {
      enrichPlanBySingleLegAndActivity(coordUniversity, plan, mode, 5400, false);
    }

    Leg returnTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(returnTrip);

    Activity home2 = scenario.getPopulation().getFactory().createActivityFromCoord("home", coord);
    plan.addActivity(home2);
    if (additionalTrips > 1) {
      home2.setMaximumDuration(random.nextInt(5400));
      enrichPlanByReturnLegAndActivity(home2, plan, mode, 5400);
    }
    person.addPlan(plan);
    scenario.getPopulation().addPerson(person);
  }
Exemple #7
0
  private void enrichPlanByReturnLegAndActivity(Activity last, Plan plan, String mode, int maxDur) {

    double lastEnd = 0.0;
    if (last.getEndTime() != Time.UNDEFINED_TIME) {
      lastEnd = last.getEndTime();
    }
    String newMode = enrichPlanBySingleLegAndActivity(last.getCoord(), plan, mode, maxDur, true);
    Leg returnTrip = scenario.getPopulation().getFactory().createLeg(newMode);
    plan.addLeg(returnTrip);
    Activity home =
        scenario
            .getPopulation()
            .getFactory()
            .createActivityFromCoord(last.getType(), last.getCoord());
    if (lastEnd != 0.0) {
      home.setEndTime(lastEnd);
    }
    plan.addActivity(home);
  }
  /**
   * Tests if the scoring function correctly handles {@link PersonMoneyEvent}. It generates one
   * person with one plan having two activities (home, work) and a car-leg in between. It then tests
   * the scoring function by calling several methods on an instance of the scoring function with the
   * aforementioned plan.
   */
  @Test
  public void testAddMoney() {
    Fixture f = new Fixture();

    // score the same plan twice
    PersonImpl person1 = new PersonImpl(Id.create(1, Person.class));
    PlanImpl plan1 = person1.createAndAddPlan(true);
    Activity act1a =
        plan1.createAndAddActivity("home", (Id<Link>) null); // , 0, 7.0*3600, 7*3600, false);
    act1a.setEndTime(f.secondLegStartTime);
    Leg leg1 = plan1.createAndAddLeg(TransportMode.car); // , 7*3600, 100, 7*3600+100);
    leg1.setDepartureTime(f.secondLegStartTime);
    leg1.setTravelTime(f.secondLegTravelTime);
    Route route2 = new GenericRouteImpl(null, null);
    leg1.setRoute(route2);
    route2.setDistance(20000.0);
    Activity act1b =
        plan1.createAndAddActivity(
            "work",
            (Id<Link>) null); // , 7.0*3600+100, Time.UNDEFINED_TIME, Time.UNDEFINED_TIME, false);
    act1b.setStartTime(f.secondLegStartTime + f.secondLegTravelTime);
    ScoringFunction sf1 = getScoringFunctionInstance(f, person1);
    sf1.handleActivity(act1a);
    sf1.handleLeg(leg1);
    sf1.handleActivity(act1b);

    sf1.finish();
    double score1 = sf1.getScore();

    ScoringFunction sf2 = getScoringFunctionInstance(f, person1);
    sf2.handleActivity(act1a);
    sf2.addMoney(1.23);
    sf2.handleLeg(leg1);
    sf2.addMoney(-2.46);
    sf2.handleActivity(act1b);
    sf2.addMoney(4.86);
    sf2.addMoney(-0.28);
    sf2.finish();
    double score2 = sf2.getScore();

    assertEquals(1.23 - 2.46 + 4.86 - 0.28, score2 - score1, EPSILON);
  }
Exemple #9
0
  private void createOneVWFlexitimeWorker(
      int i, Coord homeC, String mode, String fromToPrefix, double minHrs, double maxHrs) {
    int additionalTrips = random.nextInt(4);

    Id<Person> personId = Id.createPersonId(fromToPrefix + i + "vw");
    Person person = scenario.getPopulation().getFactory().createPerson(personId);

    Plan plan = scenario.getPopulation().getFactory().createPlan();

    Activity home = scenario.getPopulation().getFactory().createActivityFromCoord("home", homeC);

    home.setEndTime(5 * 60 * 60 + 3 * 3600 * random.nextDouble());
    plan.addActivity(home);

    Leg outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(outboundTrip);

    Coord coord = scenario.getNetwork().getLinks().get(calcVWWorkLinkId()).getCoord();
    Activity work =
        scenario.getPopulation().getFactory().createActivityFromCoord("work_vw_flexitime", coord);
    double spread = (maxHrs - minHrs) * 3600;
    work.setMaximumDuration(minHrs * 3600 + random.nextDouble() * spread);
    plan.addActivity(work);
    if (additionalTrips == 1 || additionalTrips == 3) {
      enrichPlanBySingleLegAndActivity(coord, plan, mode, 5400, false);
    }

    Leg returnTrip = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(returnTrip);

    Activity home2 = scenario.getPopulation().getFactory().createActivityFromCoord("home", homeC);
    plan.addActivity(home2);

    person.addPlan(plan);
    if (additionalTrips > 1) {
      home2.setMaximumDuration(random.nextInt(5400));

      enrichPlanByReturnLegAndActivity(home2, plan, mode, 5400);
    }
    scenario.getPopulation().addPerson(person);
  }
Exemple #10
0
 private static void createPopulation(Scenario sc, int destination) {
   Population pop = sc.getPopulation();
   pop.getPersons().clear();
   PopulationFactory fac = pop.getFactory();
   double t = 0;
   for (int i = 0; i < NR_AGENTS / 2; i++) {
     Person pers = fac.createPerson(Id.create("b" + i, Person.class));
     Plan plan = fac.createPlan();
     pers.addPlan(plan);
     Activity act0;
     act0 = fac.createActivityFromLinkId("origin", Id.create("0", Link.class));
     act0.setEndTime(t);
     plan.addActivity(act0);
     Leg leg = fac.createLeg("walkct");
     plan.addLeg(leg);
     Activity act1 =
         fac.createActivityFromLinkId("destination", Id.create(destination, Link.class));
     plan.addActivity(act1);
     pop.addPerson(pers);
   }
   //		for (int i = NR_AGENTS / 2; i < NR_AGENTS; i++) {
   //			Person pers = fac.createPerson(Id.create("b" + i, Person.class));
   //			Plan plan = fac.createPlan();
   //			pers.addPlan(plan);
   //			Activity act0;
   //			act0 = fac.createActivityFromLinkId("origin",
   //					Id.create(destination + 1, Link.class));
   //			act0.setEndTime(t);
   //			plan.addActivity(act0);
   //			Leg leg = fac.createLeg("walkct");
   //			plan.addLeg(leg);
   //			Activity act1 = fac.createActivityFromLinkId("destination",
   //					Id.create(1, Link.class));
   //			plan.addActivity(act1);
   //			pop.addPerson(pers);
   //		}
 }
  public static void main(String[] args) {

    /*
     * We enter coordinates in the WGS84 reference system, but we want them to appear in the population file
     * projected to UTM33N, because we also generated the network in UTM33N.
     */
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, TransformationFactory.WGS84_UTM33N);

    /*
     * First, create a new Config and a new Scenario.
     */
    Config config = ConfigUtils.createConfig();
    Scenario sc = ScenarioUtils.createScenario(config);

    /*
     * Pick the Network and the Population out of the Scenario for convenience.
     */
    Network network = sc.getNetwork();
    Population population = sc.getPopulation();

    /*
     * Pick the PopulationFactory out of the Population for convenience.
     * It contains methods to create new Population items.
     */
    PopulationFactory populationFactory = population.getFactory();

    /*
     * Create a Person designated "1" and add it to the Population.
     */

    long key = 1;
    for (long i = 1; i <= 5000; i++) {
      key = i;
      Person person = populationFactory.createPerson(Id.createPersonId(key));
      population.addPerson(person);

      /*
       * Create a Plan for the Person
       */
      Plan plan = populationFactory.createPlan();

      /*
       * Create a "home" Activity for the Person. In order to have the Person end its day at the same location,
       * we keep the home coordinates for later use (see below).
       * Note that we use the CoordinateTransformation created above.
       */
      Coord homeCoordinates = new Coord(686661.13571, 4827510.51845);
      Activity activity1 = populationFactory.createActivityFromCoord("home", homeCoordinates);
      activity1.setEndTime(
          21600
              + i * 0.72); // leave at 6 o'clock, one vehicle entering after other in a short while
      // so that there is no peak at one second
      // activity1.setEndTime(21600);
      plan.addActivity(activity1); // add the Activity to the Plan

      /*
       * Create a Leg. A Leg initially hasn't got many attributes. It just says that a car will be used.
       */
      plan.addLeg(populationFactory.createLeg("car"));

      /*
       * Create a "work" Activity, at a different location.
       */
      Activity activity2 =
          populationFactory.createActivityFromCoord("work", new Coord(689426.65361, 4826700.65288));
      activity2.setEndTime(57600); // leave at 4 p.m.
      plan.addActivity(activity2);
      System.out.println("Last Departure Time: " + claculateTime(activity1.getEndTime()));

      /*
       * Create another car Leg.
       */
      person.addPlan(plan);
    }

    for (long i = 1; i <= 5000; i++) {
      key = i + 5000;
      Person person = populationFactory.createPerson(Id.createPersonId(key));
      population.addPerson(person);
      Plan plan = populationFactory.createPlan();
      Coord homeCoordinates = new Coord(686661.13571, 4826063.88649);
      Activity activity1 = populationFactory.createActivityFromCoord("home", homeCoordinates);
      activity1.setEndTime(21600 + i * 1); // leave at 6 o'clock
      // activity1.setEndTime(21600);
      plan.addActivity(activity1); // add the Activity to the Plan
      plan.addLeg(populationFactory.createLeg("car"));
      Activity activity2 =
          populationFactory.createActivityFromCoord("work", new Coord(689426.65361, 4826700.65288));
      activity2.setEndTime(57600); // leave at 4 p.m.
      plan.addActivity(activity2);
      System.out.println("Last Departure Time: " + claculateTime(activity1.getEndTime()));
      person.addPlan(plan);
    }

    /*
     * Write the population (of 1 Person) to a file.
     */
    MatsimWriter popWriter =
        new org.matsim.api.core.v01.population.PopulationWriter(population, network);
    popWriter.write("H:\\Mike Work\\input\\population.xml");
  }
Exemple #12
0
  /**
   * Tests that plans with missing act locations are completed (=xy2links and routed) before the
   * mobsim starts.
   *
   * @author mrieser
   */
  @Test
  public void testCalcMissingActLinks() {
    Config config = this.utils.loadConfig(null);
    Fixture f = new Fixture(config);

    /* Create a person with two plans, driving from link 1 to link 3, starting at 7am.  */
    Population population = f.scenario.getPopulation();
    PopulationFactory factory = population.getFactory();
    Person person1 = null;
    Activity act1a = null;
    Activity act1b = null;
    Activity act2a = null;
    Activity act2b = null;
    Leg leg1 = null;
    Leg leg2 = null;

    person1 = PersonImpl.createPerson(Id.create(1, Person.class));
    // --- plan 1 ---
    Plan plan1 = factory.createPlan();
    person1.addPlan(plan1);
    double x1 = -50.0;
    act1a = factory.createActivityFromCoord("h", new Coord(x1, 10.0));
    act1a.setEndTime(7.0 * 3600);
    plan1.addActivity(act1a);
    leg1 = factory.createLeg(TransportMode.car);
    plan1.addLeg(leg1);
    // DO NOT CREATE A ROUTE FOR THE LEG!!!
    double y1 = -10.0;
    act1b = factory.createActivityFromCoord("h", new Coord(1075.0, y1));
    plan1.addActivity(act1b);
    // --- plan 2 ---
    Plan plan2 = factory.createPlan();
    person1.addPlan(plan2);
    double x = -50.0;
    double y = -10.0;
    act2a = factory.createActivityFromCoord("h", new Coord(x, y));
    act2a.setEndTime(7.9 * 3600);
    plan2.addActivity(act2a);
    leg2 = factory.createLeg(TransportMode.car);
    plan2.addLeg(leg2);
    // DO NOT CREATE A ROUTE FOR THE LEG!!!
    act2b = factory.createActivityFromCoord("h", new Coord(1111.1, 10.0));
    plan2.addActivity(act2b);
    population.addPerson(person1);

    // Complete the configuration for our test case
    // - set scoring parameters
    ActivityParams actParams = new ActivityParams("h");
    actParams.setTypicalDuration(8 * 3600);
    actParams.setPriority(1.0);
    config.planCalcScore().addActivityParams(actParams);
    // - define iterations
    config.controler().setLastIteration(0);
    // - make sure we don't use threads, as they are not deterministic
    config.global().setNumberOfThreads(1);

    // Now run the simulation
    Controler controler = new Controler(f.scenario);
    controler.getConfig().controler().setCreateGraphs(false);
    controler.getConfig().controler().setWriteEventsInterval(0);
    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();
    /* if something goes wrong, there will be an exception we don't catch and the test fails,
     * otherwise, everything is fine. */

    // check that BOTH plans have their act-locations calculated
    assertEquals(f.link1.getId(), act1a.getLinkId());
    assertEquals(f.link3.getId(), act1b.getLinkId());
    assertEquals(f.link1.getId(), act2a.getLinkId());
    assertEquals(f.link3.getId(), act2b.getLinkId());

    // check that BOTH plans have a route set, even when we only run 1 iteration where only one of
    // them is used.
    // assertNotNull(leg1.getRoute());
    // assertNotNull(leg2.getRoute());
    // but do not assume that the leg will be the same instance...
    for (Plan plan : new Plan[] {plan1, plan2}) {
      assertEquals(
          "unexpected plan length in " + plan.getPlanElements(), 3, plan.getPlanElements().size());
      assertNotNull(
          "null route in plan " + plan.getPlanElements(),
          ((Leg) plan.getPlanElements().get(1)).getRoute());
    }
  }
Exemple #13
0
  /**
   * Tests that the travel times are correctly calculated during the simulation.
   *
   * @author mrieser
   */
  @Test
  public void testTravelTimeCalculation() {
    Config config = this.utils.loadConfig(null);
    Fixture f = new Fixture(config);

    /* Create 2 persons driving from link 1 to link 3, both starting at the
     * same time at 7am.  */
    Population population = f.scenario.getPopulation();
    PopulationFactory factory = population.getFactory();
    Person person1 = null;

    person1 = factory.createPerson(Id.create("1", Person.class));
    Plan plan1 = factory.createPlan();
    person1.addPlan(plan1);
    Activity a1 = factory.createActivityFromLinkId("h", f.link1.getId());
    a1.setEndTime(7.0 * 3600);
    plan1.addActivity(a1);
    Leg leg1 = factory.createLeg(TransportMode.car);
    plan1.addLeg(leg1);
    NetworkRoute route1 =
        ((PopulationFactoryImpl) f.scenario.getPopulation().getFactory())
            .createRoute(NetworkRoute.class, f.link1.getId(), f.link3.getId());
    leg1.setRoute(route1);
    ArrayList<Id<Link>> linkIds = new ArrayList<Id<Link>>();
    linkIds.add(f.link2.getId());
    route1.setLinkIds(f.link1.getId(), linkIds, f.link3.getId());
    plan1.addActivity(factory.createActivityFromLinkId("h", f.link3.getId()));
    population.addPerson(person1);

    Person person2 = factory.createPerson(Id.create("2", Person.class));
    Plan plan2 = factory.createPlan();
    person2.addPlan(plan2);
    Activity a2 = factory.createActivityFromLinkId("h", f.link1.getId());
    a2.setEndTime(7.0 * 3600);
    plan2.addActivity(a2);
    Leg leg2 = factory.createLeg(TransportMode.car);
    plan2.addLeg(leg2);
    NetworkRoute route2 =
        ((PopulationFactoryImpl) f.scenario.getPopulation().getFactory())
            .createRoute(NetworkRoute.class, f.link1.getId(), f.link3.getId());
    leg2.setRoute(route2);
    route2.setLinkIds(f.link1.getId(), linkIds, f.link3.getId());
    plan2.addActivity(factory.createActivityFromLinkId("h", f.link3.getId()));
    population.addPerson(person2);

    // Complete the configuration for our test case
    // - set scoring parameters
    ActivityParams actParams = new ActivityParams("h");
    actParams.setTypicalDuration(8 * 3600);
    actParams.setPriority(1.0);
    config.planCalcScore().addActivityParams(actParams);
    // - define iterations
    config.controler().setLastIteration(0);
    // - make sure we don't use threads, as they are not deterministic
    config.global().setNumberOfThreads(0);

    // Now run the simulation
    Controler controler = new Controler(f.scenario);
    controler.getConfig().controler().setCreateGraphs(false);
    controler.getConfig().controler().setWriteEventsInterval(0);
    controler.setDumpDataAtEnd(false);
    controler.run();

    // test if we got the right result
    // the actual result is 151sec, not 150, as each vehicle "loses" 1sec in the buffer
    assertEquals(
        "TravelTimeCalculator has wrong result",
        151.0,
        controler.getLinkTravelTimes().getLinkTravelTime(f.link2, 7 * 3600, null, null),
        0.0);

    // now test that the ReRoute-Strategy also knows about these travel times...
    config.controler().setLastIteration(1);
    ConfigGroup strategyParams = config.getModule("strategy");
    strategyParams.addParam("maxAgentPlanMemorySize", "4");
    strategyParams.addParam("ModuleProbability_1", "1.0");
    strategyParams.addParam("Module_1", "ReRoute");
    // Run the simulation again
    controler = new Controler(f.scenario);
    controler.getConfig().controler().setCreateGraphs(false);
    controler
        .getConfig()
        .controler()
        .setOverwriteFileSetting(
            OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles);
    controler.getConfig().controler().setWriteEventsInterval(0);
    controler.run();

    // test that the plans have the correct times
    assertEquals(
        "ReRoute seems to have wrong travel times.",
        151.0,
        ((Leg) (person1.getPlans().get(1).getPlanElements().get(1))).getTravelTime(),
        0.0);
  }
Exemple #14
0
  public void cleanUpScenario(Scenario sc) {
    LOG.info("Cleaning up scenario...");
    /* TODO Still need to figure out what cleaning up must happen. */

    /* Search for location-less activities, and sample its locations from
     * the kernel density estimates. */
    LOG.info("Sampling locations for those without known zones...");
    int locationsFixed = 0;
    int knownLocations = 0;
    for (Person person : sc.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      if (plan != null) {
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            Coord coord = act.getCoord();
            if (coord.getX() == 0.0 || coord.getY() == 0.0) {
              ((ActivityImpl) act).setCoord(sampleActivityLocation(act.getType()));
              locationsFixed++;
            } else {
              knownLocations++;
            }
          }
        }
      }
    }
    LOG.info("Number of known locations: " + knownLocations);
    LOG.info("Number of locations fixed: " + locationsFixed);
    LOG.info("Done sampling locations.");

    /* Ensure each activity, except the last, has both a start and end time. */
    LOG.info("Ensure each activity has an end time...");
    for (Person person : sc.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      if (plan != null) {
        List<PlanElement> list = plan.getPlanElements();
        for (int i = 0; i < list.size() - 2; i += 2) {
          PlanElement pe = list.get(i);
          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            double endTime = act.getEndTime();
            if (endTime < 0.0) {
              double legStart = ((Leg) list.get(i + 1)).getDepartureTime();
              act.setEndTime(legStart);
            }
          } else {
            LOG.warn("Every second PlanElement should be of type 'Activity'.");
          }
        }
      }
    }
    LOG.info("Done fixing activity end times.");

    /* Ensure that the home location/coordinate for all members in the
     * household are the same for all their "h" activities. */
    LOG.info("Fix home locations for each household member. ");
    int homeLocationsFixed = 0;
    int nonTravellers = 0;
    for (Household hh : sc.getHouseholds().getHouseholds().values()) {
      Object o =
          sc.getHouseholds()
              .getHouseholdAttributes()
              .getAttribute(hh.getId().toString(), "transportZone");
      if (o instanceof String) {
        String zoneId = (String) o;
        Coord homeCoord = null;
        if (zoneId != null && !zoneId.equalsIgnoreCase("")) {
          /* There is known home zone. */
          Point p = this.zoneMap.get(zoneId).sampleRandomInteriorPoint();
          homeCoord = CoordUtils.createCoord(p.getX(), p.getY());
        } else {
          /* There is no transport zone. */
          homeCoord = sampleActivityLocation("h");
        }

        /* Now assign the home coordinate to ALL home activities for
         * all members of the household. */
        for (Id<Person> id : hh.getMemberIds()) {
          Person person = sc.getPopulation().getPersons().get(id);
          Plan plan = person.getSelectedPlan();
          if (plan != null) {
            for (PlanElement pe : person.getSelectedPlan().getPlanElements()) {
              if (pe instanceof ActivityImpl) {
                ActivityImpl act = (ActivityImpl) pe;
                if (act.getType().equalsIgnoreCase("h")) {
                  act.setCoord(homeCoord);
                  homeLocationsFixed++;
                }
              }
            }
          } else {
            /* The member does not have ANY plan. We 'fix' this by
             * adding aPlan with a single home-based activity for
             * which not times are specified. */
            Plan stayHomePlan = sc.getPopulation().getFactory().createPlan();
            Activity act = sc.getPopulation().getFactory().createActivityFromCoord("h", homeCoord);
            stayHomePlan.addActivity(act);
            person.addPlan(stayHomePlan);
            nonTravellers++;
          }
        }
      }
    }
    LOG.info("Total number of home locations fixed: " + homeLocationsFixed);
    LOG.info("      Total number of non-travellers: " + nonTravellers);
    LOG.info("Done fixing home locations.");

    /* TODO Check what to do with those household members that are not
     * travelling. Are they just given a single 'h' activities, and
     * left at that? */

    /* Look for erroneous activity times that can/should be fixed in
     * the raw travel diary input data. This will typically include very
     * long activity times or leg durations. */
    LOG.info("Checking leg durations:");
    int remainingLegOddities = 0;
    double legDurationThreshold = Time.parseTime("03:00:00");
    for (Person p : sc.getPopulation().getPersons().values()) {
      Plan plan = p.getSelectedPlan();
      if (plan != null) {
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Leg) {
            double duration = ((Leg) pe).getTravelTime();
            if (duration < 0 || duration > legDurationThreshold) {
              LOG.warn(
                  " -> Odd leg duration: "
                      + p.getId().toString()
                      + " ("
                      + Time.writeTime(duration)
                      + ")");
              remainingLegOddities++;
            }
          }
        }
      }
    }
    LOG.info("Done checking leg durations. (" + remainingLegOddities + " remain)");

    /* Parse the activity duration times in an effort to pick up
     * erroneous travel time data that results in negative activity
     * durations. Then fix in input data. */
    LOG.info("Checking activity durations (from leg times):");
    int remainingActivityOddities = 0;
    double activityDurationThreshold = Time.parseTime("16:00:00");
    for (Person p : sc.getPopulation().getPersons().values()) {
      Plan plan = p.getSelectedPlan();
      if (plan != null) {
        for (int i = 1; i < plan.getPlanElements().size() - 2; i += 2) {
          PlanElement pe1 = plan.getPlanElements().get(i);
          PlanElement pe2 = plan.getPlanElements().get(i + 2);
          if (pe1 instanceof Leg && pe2 instanceof Leg) {
            Leg l1 = (Leg) pe1;
            Leg l2 = (Leg) pe2;
            double act = l2.getDepartureTime() - (l1.getDepartureTime() + l1.getTravelTime());
            if (act < 0 || act > activityDurationThreshold) {
              LOG.warn(
                  " -> Odd activity duration: "
                      + p.getId().toString()
                      + " ("
                      + Time.writeTime(act)
                      + ")");
              remainingActivityOddities++;
            }
          } else {
            LOG.error("PlanElements not of type Leg!!");
            LOG.error("   pe1: " + pe1.getClass().toString());
            LOG.error("   pe2: " + pe2.getClass().toString());
          }
        }
      }
    }
    LOG.info("Done checking activity durations. (" + remainingActivityOddities + " remain)");

    /* TODO Fix plans for night workers. They typically start with 'h',
     * but should actually start with 'w'. */

    /* TODO Consider what to do with repeating activities, especially
     * consecutive home activities. */

    /* Convert all activity locations to a projected coordinate system. */
    LOG.info("Converting all activity locations to EPSG:3857...");
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation("WGS84", "EPSG:3857");
    for (Person person : sc.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      if (plan != null) {
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            ((ActivityImpl) act).setCoord(ct.transform(act.getCoord()));
          }
        }
      }
    }
    LOG.info("Done converting activity locations.");

    LOG.info("Done cleaning up scenario.");
  }
Exemple #15
0
  private void processDiary() {
    LOG.info("Processing diary...");
    PopulationFactory pf = this.sc.getPopulation().getFactory();

    Map<String, Integer> chainCount = new TreeMap<>();

    int noTrips = 0;
    int noFirstTrip = 0;
    int noZoneInfo = 0;
    int zoneInfo = 0;

    Counter counter = new Counter("  person # ");
    for (Id<Person> pId : this.tripMap.keySet()) {
      List<String[]> list = tripMap.get(pId);
      Map<String, String[]> map = new TreeMap<>();
      for (String[] sa : list) {
        String tripNumber = sa[23];
        if (!tripNumber.equals("")) {
          String tripId = String.format("%02d", Integer.parseInt(tripNumber));
          map.put(tripId, sa);
        }
      }

      if (map.size() == 0) {
        noTrips++;
      } else {
        /* Try and do some magic with the diary. */
        Plan plan = pf.createPlan();

        /* Check the first activity. */
        String chain = "";
        String[] sa = map.get("01");
        if (sa == null) {
          /* There is no first trip numbered '01'. */
          LOG.warn(pId.toString() + ": " + map.keySet().toString());
          noFirstTrip++;
        } else {
          chain += "h";
          String homeZone = sa[7];
          Coord homeCoord = sampleCoord(homeZone, "h");

          Activity firstHome = pf.createActivityFromCoord("h", homeCoord);
          double homeEnd = 0.0;
          try {
            homeEnd = Time.parseTime(sa[25]);
          } catch (NumberFormatException e) {
            LOG.error(" TIME: ===> " + pId.toString() + ": " + sa[25]);
          }
          firstHome.setEndTime(homeEnd);
          plan.addActivity(firstHome);
        }

        /* Parse the chain. */
        Iterator<String> it = map.keySet().iterator();

        while (it.hasNext()) {
          String trip = it.next();
          String[] tripSa = map.get(trip);
          String tripPurpose = tripSa[33];
          String matsimTrip =
              DiaryEnums.TripPurpose.parseFromCode(
                      tripPurpose.equals("") || tripPurpose.equals(" ")
                          ? 0
                          : Integer.parseInt(tripPurpose))
                  .getMatsimActivityCode();
          chain += "-" + matsimTrip;

          /* Add the trip to plan. */
          String recordedMode = tripSa[34];
          if (recordedMode.contains(";")) {
            LOG.error("Multiple modes for " + pId.toString() + ": " + recordedMode);
            throw new RuntimeException();
          }
          String matsimMode =
              DiaryEnums.ModeOfTravel.parseFromCode(
                      tripSa[34].equals("") || tripSa[34].equalsIgnoreCase(" ")
                          ? 0
                          : Integer.parseInt(tripSa[34]))
                  .getMatsimMode();
          Leg leg = pf.createLeg(matsimMode);
          double tripStartTime = 0.0;
          double tripEndTime = 0.0;
          try {
            tripStartTime = Time.parseTime(tripSa[25]);
          } catch (NumberFormatException e) {
            LOG.error(" TIME: ===> " + pId.toString() + ": " + tripSa[25]);
          }
          try {
            tripEndTime = Time.parseTime(tripSa[27]);
          } catch (NumberFormatException e) {
            LOG.error(" TIME: ===> " + pId.toString() + ": " + tripSa[27]);
          }
          leg.setDepartureTime(tripStartTime);
          leg.setTravelTime(tripEndTime - tripStartTime);
          plan.addLeg(leg);

          /* Add the destination activity. */
          if (tripSa[32].equals("") || tripSa[32].equals(" ")) {
            if (!matsimTrip.equalsIgnoreCase("h")) {
              zoneInfo++;
            } else {
              noZoneInfo++;
            }
          } else {
            zoneInfo++;
          }
          Coord actCoord = sampleCoord(tripSa[32], matsimTrip);
          Activity act = pf.createActivityFromCoord(matsimTrip, actCoord);
          act.setStartTime(tripEndTime);
          plan.addActivity(act);
        }

        /* Check and add chain. */
        if (!chainCount.containsKey(chain)) {
          chainCount.put(chain, 1);
        } else {
          int oldCount = chainCount.get(chain);
          chainCount.put(chain, oldCount + 1);
        }

        /* Finally, associate the plan with the person. */
        sc.getPopulation().getPersons().get(pId).addPlan(plan);
      }
      counter.incCounter();
    }
    counter.printCounter();

    LOG.info("          Number of persons with no trips: " + noTrips);
    LOG.info("    Number of persons with no first trips: " + noFirstTrip);
    LOG.info(" Number of destinations without zone info: " + noZoneInfo);
    LOG.info("    Number of destinations with zone info: " + zoneInfo);

    /* Report the activity chain types. */
    SortedSet<Entry<String, Integer>> set = entriesSortedByValues(chainCount);
    Iterator<Entry<String, Integer>> iter = set.iterator();
    while (iter.hasNext()) {
      Entry<String, Integer> entry = iter.next();
      LOG.info("  " + entry.getKey() + " (" + entry.getValue() + ")");
    }

    LOG.info("Done processing diary.");
  }
  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);
  }
Exemple #17
0
  /**
   * @param args
   * @throws FactoryException
   */
  public static void main(String[] args) throws FactoryException {
    String popFile = args[0];
    String facFile = args[1];
    String netFile = args[2];
    int n = Integer.parseInt(args[3]);
    String outDir = args[4];

    Logger logger = Logger.getLogger(DemoScenario.class);

    MathTransform transform = CRS.findMathTransform(CRSUtils.getCRS(31467), CRSUtils.getCRS(3857));

    Config config = ConfigUtils.createConfig();
    Scenario scenario = ScenarioUtils.createScenario(config);
    /*
     * remove foreign persons and extract subsample
     */
    logger.info("Loading persons...");
    MatsimPopulationReader pReader = new MatsimPopulationReader(scenario);
    pReader.readFile(popFile);
    logger.info("Done.");

    logger.info("Removing foreign persons...");
    Set<Id<Person>> remove = new HashSet<>();
    for (Id<Person> id : scenario.getPopulation().getPersons().keySet()) {
      if (id.toString().startsWith("foreign")) {
        remove.add(id);
      }
    }

    int cnt = 0;
    for (Id<Person> id : remove) {
      if (scenario.getPopulation().getPersons().remove(id) != null) {
        cnt++;
      }
    }
    logger.info(String.format("Done. Removed %s foreign persons.", cnt));

    logger.info("Drawing population subsample...");
    List<Person> persons = new ArrayList<>(scenario.getPopulation().getPersons().values());
    Collections.shuffle(persons);
    Population population = PopulationUtils.createPopulation(config);
    cnt = 0;
    for (int i = 0; i < n; i++) {
      population.addPerson(persons.get(i));
    }
    logger.info("Done.");

    logger.info("Bluring activity end times...");
    Random random = new XORShiftRandom();
    for (Person person : population.getPersons().values()) {
      for (Plan plan : person.getPlans()) {
        for (int i = 0; i < plan.getPlanElements().size(); i += 2) {
          Activity act = (Activity) plan.getPlanElements().get(i);
          double endTim = act.getEndTime() - 15 * 60 + (random.nextDouble() * 30 * 60);
          act.setEndTime(endTim);
          double startTim = act.getStartTime() - 15 * 60 + (random.nextDouble() * 30 * 60);
          act.setStartTime(startTim);
        }
      }
    }
    logger.info("Done.");

    logger.info("Writing population...");
    PopulationWriter pWriter = new PopulationWriter(population);
    pWriter.write(String.format("%s/plans.xml.gz", outDir));
    logger.info("Done.");
    /*
     * filter only used facilities
     */
    logger.info("Loading facilities...");
    MatsimFacilitiesReader fReader = new MatsimFacilitiesReader(scenario);
    fReader.readFile(facFile);
    logger.info("Done.");

    logger.info("Removing unsused facilities...");
    Set<Id<ActivityFacility>> unused =
        new HashSet<>(scenario.getActivityFacilities().getFacilities().keySet());
    for (Person person : population.getPersons().values()) {
      for (Plan plan : person.getPlans()) {
        for (int i = 0; i < plan.getPlanElements().size(); i += 2) {
          Activity act = (Activity) plan.getPlanElements().get(i);
          unused.remove(act.getFacilityId());
        }
      }
    }
    logger.info("Done.");

    logger.info("Transforming facility coordinates...");
    for (ActivityFacility fac : scenario.getActivityFacilities().getFacilities().values()) {
      double[] points = new double[] {fac.getCoord().getX(), fac.getCoord().getY()};
      try {
        transform.transform(points, 0, points, 0, 1);
      } catch (TransformException e) {
        e.printStackTrace();
      }

      ((ActivityFacilityImpl) fac).setCoord(new Coord(points[0], points[1]));
    }
    logger.info("Done.");

    logger.info("Writing facilities...");
    FacilitiesWriter fWrtier = new FacilitiesWriter(scenario.getActivityFacilities());
    fWrtier.write(String.format("%s/facilities.xml.gz", outDir));
    logger.info("Done.");
    /*
     * clean network from foreign links
     */
    logger.info("Loading network...");
    MatsimNetworkReader nReader = new MatsimNetworkReader(scenario);
    nReader.readFile(netFile);
    logger.info("Done.");

    logger.info("Removing foreign links...");
    Set<Id<Link>> linksRemove = new HashSet<>();
    for (Id<Link> id : scenario.getNetwork().getLinks().keySet()) {
      if (id.toString().contains(".l")) {
        linksRemove.add(id);
      }
    }

    for (Id<Link> id : linksRemove) {
      scenario.getNetwork().removeLink(id);
    }
    logger.info("Done.");

    logger.info("Removing foreign nodes...");
    Set<Id<Node>> nodesRemove = new HashSet<>();
    for (Id<Node> id : scenario.getNetwork().getNodes().keySet()) {
      if (id.toString().contains(".n")) {
        nodesRemove.add(id);
      }
    }

    for (Id<Node> id : nodesRemove) {
      scenario.getNetwork().removeNode(id);
    }
    logger.info("Done.");

    logger.info("Transforming node coordinates...");
    for (Node node : scenario.getNetwork().getNodes().values()) {
      double[] points = new double[] {node.getCoord().getX(), node.getCoord().getY()};
      try {
        transform.transform(points, 0, points, 0, 1);
      } catch (TransformException e) {
        e.printStackTrace();
      }

      ((NodeImpl) node).setCoord(new Coord(points[0], points[1]));
    }
    logger.info("Done.");

    logger.info("Writing network...");
    NetworkWriter nWriter = new NetworkWriter(scenario.getNetwork());
    nWriter.write(String.format("%s/network.xml.gz", outDir));
    logger.info("Done.");
  }
  public void CreateChoiceSets() {

    PopulationFactory populationFactory = population.getFactory();
    ArrayList<Person> newPersons = new ArrayList<>();

    /*Clean routes*/
    PlanRouteStripper planRouteStripper = new PlanRouteStripper();
    planRouteStripper.run(population);

    for (Id<Person> personId : population.getPersons().keySet()) {

      Plan plan = population.getPersons().get(personId).getSelectedPlan();
      plan.getCustomAttributes()
          .put(
              "toll",
              population
                  .getPersonAttributes()
                  .getAttribute(personId.toString(), "selectedPlanToll"));
      initialPlans.put(personId, plan);

      population.getPersons().get(personId).createCopyOfSelectedPlanAndMakeSelected();

      Plan planTmp = population.getPersons().get(personId).getSelectedPlan();
      population.getPersons().get(personId).getPlans().clear();
      population.getPersons().get(personId).addPlan(planTmp);
    }

    /*Create optimal walk plan and substitute it in the planMap*/
    OptimalWalkPlanFinder optimalWalkPlanFinder = new OptimalWalkPlanFinder(controler.getConfig());

    for (Id<Person> personId : population.getPersons().keySet()) {

      /* Plan cloning for each mode*/
      HashMap<String, Plan> planMap = new HashMap<>();

      Leg firstLeg =
          (Leg) population.getPersons().get(personId).getSelectedPlan().getPlanElements().get(1);
      String initialMode = firstLeg.getMode();

      // If "No PT"
      if (initialMode == "pt" && simType.equals("noPT")) initialMode = "walk";

      planMap.put(initialMode, population.getPersons().get(personId).getSelectedPlan());

      // String[] modes =
      // controler.getScenario().getConfig().getModule("subtourModeChoice").getValue("modes").split(",");
      // String[] modes = {"car","walk"};

      ArrayList<String> relevantModes = new ArrayList<String>();
      relevantModes.add("car");
      if (!simType.equals("carOnly") && !simType.equals("noPT")) relevantModes.add("pt");

      for (String mode : relevantModes) {
        if (!initialMode.equals(mode) && !mode.equals("walk")) {
          population.getPersons().get(personId).createCopyOfSelectedPlanAndMakeSelected();
          Plan planForModeChange = population.getPersons().get(personId).getSelectedPlan();

          for (int j = 1; j < planForModeChange.getPlanElements().size(); j += 2) {
            Leg leg = (Leg) planForModeChange.getPlanElements().get(j);
            leg.setMode(mode);
          }

          planMap.put(mode, planForModeChange);
        }
      }

      /*Check if walk is a viable alternative and if so, add it to the choice set*/
      if (!initialMode.equals("walk")
          && optimalWalkPlanFinder.getWalkTravelTime(planMap.get(initialMode)) <= 3600.0
          && !simType.equals("carOnly")) {
        population.getPersons().get(personId).createCopyOfSelectedPlanAndMakeSelected();
        Plan planForModeChange = population.getPersons().get(personId).getSelectedPlan();
        planForModeChange = optimalWalkPlanFinder.findOptimalWalkPlan(planForModeChange);
        for (int j = 1; j < planForModeChange.getPlanElements().size(); j += 2) {
          Leg leg = (Leg) planForModeChange.getPlanElements().get(j);
          leg.setMode("walk");
        }

        planMap.put("walk", planForModeChange);
      }
      ;

      // String[] relevantModes = {"car","pt"};

      /* Departure time modification for each mode*/
      for (String mode : relevantModes) {
        Plan basePlan = planMap.get(mode);
        population.getPersons().get(personId).setSelectedPlan(basePlan);

        for (int i = 0; i < 6; i++) {
          population.getPersons().get(personId).createCopyOfSelectedPlanAndMakeSelected();
        }

        population.getPersons().get(personId).setSelectedPlan(basePlan);

        int planModCounter = 0;
        /* Departure time modification */
        for (Plan planToModify : population.getPersons().get(personId).getPlans()) {

          if (((Leg) planToModify.getPlanElements().get(1)).getMode().equals(mode)
              && !PersonUtils.isSelected(planToModify)) {

            // Home departure time + 1h
            if (planModCounter == 0) {
              Activity act = (Activity) planToModify.getPlanElements().get(0);
              act.setEndTime(act.getEndTime() + 3600.0);
            }

            // Home departure time - 1h
            if (planModCounter == 1) {
              Activity act = (Activity) planToModify.getPlanElements().get(0);
              act.setEndTime(act.getEndTime() - 3600.0);
            }

            // Work departure time + 1h
            if (planModCounter == 2) {
              Activity act = (Activity) planToModify.getPlanElements().get(2);
              act.setEndTime(act.getEndTime() + 3600.0);
            }

            // Work departure time - 1h
            if (planModCounter == 3) {
              Activity act = (Activity) planToModify.getPlanElements().get(2);
              act.setEndTime(act.getEndTime() - 3600.0);
            }

            // Home departure time + 1h, Work departure time +1h
            if (planModCounter == 4) {
              Activity act = (Activity) planToModify.getPlanElements().get(0);
              act.setEndTime(act.getEndTime() + 3600.0);

              Activity act2 = (Activity) planToModify.getPlanElements().get(2);
              act2.setEndTime(act2.getEndTime() + 3600.0);
            }

            // Home departure time - 1h, Work departure time -1h
            if (planModCounter == 5) {
              Activity act = (Activity) planToModify.getPlanElements().get(0);
              act.setEndTime(act.getEndTime() - 3600.0);

              Activity act2 = (Activity) planToModify.getPlanElements().get(2);
              act2.setEndTime(act2.getEndTime() - 3600.0);
            }

            //                      NOT REALISTIC
            //						//Home departure time +1h, Work departure time -1h
            //						if (planModCounter == 6) {
            //							Activity act = (Activity) planToModify.getPlanElements().get(0);
            //							act.setEndTime(act.getEndTime() + 3600.0);
            //
            //							Activity act2 = (Activity) planToModify.getPlanElements().get(2);
            //							act2.setEndTime(act2.getEndTime() - 3600.0);
            //						}
            //
            //						//Home departure time - 1h, Work departure time +1h
            //						if (planModCounter == 7) {
            //							Activity act = (Activity) planToModify.getPlanElements().get(0);
            //							act.setEndTime(act.getEndTime() - 3600.0);
            //
            //							Activity act2 = (Activity) planToModify.getPlanElements().get(2);
            //							act2.setEndTime(act2.getEndTime() + 3600.0);
            //						}

            planModCounter++;
          }
        }
      }

      /*Plan split to different persons*/
      int count = 0;
      population.getPersons().get(personId).setSelectedPlan(planMap.get(initialMode));
      for (Plan newPlan : population.getPersons().get(personId).getPlans()) {
        if (personId.toString().equals("1000")) System.out.println();
        if (!PersonUtils.isSelected(newPlan)) {
          count++;
          Person newPerson =
              populationFactory.createPerson(Id.createPersonId(personId.toString() + "_" + count));
          newPerson.addPlan(newPlan);
          newPerson.setSelectedPlan(newPlan);
          newPersons.add(newPerson);
          population
              .getPersonAttributes()
              .putAttribute(
                  newPerson.getId().toString(),
                  "income",
                  population.getPersonAttributes().getAttribute(personId.toString(), "income"));
          population
              .getPersonAttributes()
              .putAttribute(
                  newPerson.getId().toString(),
                  "betaFactor",
                  population.getPersonAttributes().getAttribute(personId.toString(), "betaFactor"));
        }
      }

      /*Clear all plans from initial person*/
      //			population.getPersons().get(personId).getPlans().clear();
      //			population.getPersons().get(personId).addPlan(initialPlans.get(personId));
      //			population.getPersons().get(personId).setSelectedPlan(initialPlans.get(personId));

      /*Clear all plans from initial person*/
      population.getPersons().get(personId).getPlans().clear();

      Person tempPerson = population.getFactory().createPerson(Id.create(20000, Person.class));
      tempPerson.addPlan(initialPlans.get(personId));
      tempPerson.setSelectedPlan(initialPlans.get(personId));
      tempPerson.createCopyOfSelectedPlanAndMakeSelected();
      Plan tempPlan = tempPerson.getSelectedPlan();
      population.getPersons().get(personId).addPlan(tempPlan);
      population.getPersons().get(personId).setSelectedPlan(tempPlan);
    }

    /*Add new agents to the simulation*/
    for (Person newPerson : newPersons) {
      population.addPerson(newPerson);
    }

    /*Write out new population file*/
    //		System.out.println("New number of persons: " + population.getPersons().size());
    //		new org.matsim.core.population.PopulationWriter(population,
    // controler.getScenario().getNetwork()).write("/Volumes/DATA 1 (WD 2
    // TB)/output_SelectExp1_5p_"+simType+"_1000it_Dwell/popText.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());
  }
Exemple #20
0
  private void createOnePerson(
      int i,
      Coord coord,
      Coord coordWork,
      String mode,
      String toFromPrefix,
      double personalRandom) {
    Id<Person> personId = Id.createPersonId(toFromPrefix + i);
    Person person = scenario.getPopulation().getFactory().createPerson(personId);

    Plan plan = scenario.getPopulation().getFactory().createPlan();

    // Planerzeugung inkl. Zufallslogik für Start- bzw. Endezeiten
    // 60% Plan: home-work-home

    // CARSHARING MODE
    if (personalRandom < 0.6) {
      double csRandom = rnd.nextDouble();
      if (csRandom > 0.33 && csRandom < 0.67) mode = "freefloating";
      if (csRandom >= 0.67) mode = "twowaycarsharing";
    }

    Activity home = scenario.getPopulation().getFactory().createActivityFromCoord("home", coord);
    double startTime =
        7.5 * 60 * 60 + (2 * 60 * 60 * rnd.nextDouble()); // ZufallsStartZeit 7.30-9.30Uhr
    home.setEndTime(startTime);
    plan.addActivity(home);

    Leg hinweg1 = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(hinweg1);

    // 10% Plan: home-KINDERGARTEN1-work-KINDERGARTEN2-home
    // kindergarten AM
    if ((personalRandom > 0.6) && (personalRandom <= 0.7)) {

      Activity kindergarten1 =
          scenario
              .getPopulation()
              .getFactory()
              .createActivityFromCoord(
                  "kindergarten1", this.findClosestCoordFromMap(coord, kindergartens));
      kindergarten1.setEndTime(
          startTime + (0.4 * 60 * 60) + (0.1 * 60 * 60 * rnd.nextDouble())); // DropOff-Zeit 5-10min
      plan.addActivity(kindergarten1);

      Leg hinweg2 = scenario.getPopulation().getFactory().createLeg(mode);
      plan.addLeg(hinweg2);
    }

    Activity work =
        scenario.getPopulation().getFactory().createActivityFromCoord("work", coordWork);
    double workEndTime =
        startTime
            + (7.5 * 60 * 60)
            + (1 * 60 * 60 * rnd.nextDouble()); // Arbeitszeit 7,5-8,5 Stunden
    work.setEndTime(workEndTime);
    plan.addActivity(work);

    Leg rueckweg1 = scenario.getPopulation().getFactory().createLeg(mode);
    plan.addLeg(rueckweg1);

    // kindergarten PM
    if ((personalRandom > 0.6) && (personalRandom <= 0.7)) {

      Activity kindergarten2 =
          scenario
              .getPopulation()
              .getFactory()
              .createActivityFromCoord(
                  "kindergarten2", this.findClosestCoordFromMap(coord, kindergartens));
      kindergarten2.setEndTime(
          workEndTime
              + (0.4 * 60 * 60)
              + (0.1 * 60 * 60 * rnd.nextDouble())); // PickUp-Zeit 5-10min
      plan.addActivity(kindergarten2);

      Leg rückweg2 = scenario.getPopulation().getFactory().createLeg(mode);
      plan.addLeg(rückweg2);
    }

    // 30% Plan: home-work-home-SHOPPEN-home
    if (personalRandom > 0.7) {

      Activity home2 = scenario.getPopulation().getFactory().createActivityFromCoord("home", coord);
      double startShoppingTime = workEndTime + (1 * 60 * 60) + (0.5 * 60 * 60 * rnd.nextDouble());
      home2.setEndTime(startShoppingTime);
      plan.addActivity(home2);

      Leg zumShoppen = scenario.getPopulation().getFactory().createLeg(mode);
      plan.addLeg(zumShoppen);

      Activity shopping =
          scenario
              .getPopulation()
              .getFactory()
              .createActivityFromCoord("shopping", this.findClosestCoordFromMap(coord, shops));
      shopping.setEndTime(
          startShoppingTime
              + (1 * 60 * 60)
              + (1 * 60 * 60 * rnd.nextDouble())); // Shoppen 1-2 Stunden
      plan.addActivity(shopping);

      Leg vomShoppen = scenario.getPopulation().getFactory().createLeg(mode);
      plan.addLeg(vomShoppen);
    }

    Activity home3 = scenario.getPopulation().getFactory().createActivityFromCoord("home", coord);
    plan.addActivity(home3);

    person.addPlan(plan);
    scenario.getPopulation().addPerson(person);
  }
    @Override
    public void notifyMobsimBeforeSimStep(final MobsimBeforeSimStepEvent e) {
      if (e.getSimulationTime() == t1) {
        assertEquals(
            100,
            this.arp
                .getActivityPerformingAgents()
                .size()); // all agents perform an activity before the time step
        assertEquals(
            1,
            this.arp
                .getActivityEndingAgents(e.getSimulationTime())
                .size()); // one agent ends an activity
      }

      if (e.getSimulationTime() == t2) {
        assertEquals(
            99,
            this.arp
                .getActivityPerformingAgents()
                .size()); // 99 agents perform an activity before the time step
        assertEquals(
            1,
            this.arp
                .getActivityEndingAgents(e.getSimulationTime())
                .size()); // one agent ends an activity
      }

      if (e.getSimulationTime() == t3) {
        assertEquals(
            98,
            this.arp
                .getActivityPerformingAgents()
                .size()); // 98 agents perform an activity before the time step
        assertEquals(
            1,
            this.arp
                .getActivityEndingAgents(e.getSimulationTime())
                .size()); // one agent ends an activity
      }

      if (e.getSimulationTime() == t4) {
        assertEquals(
            97,
            this.arp
                .getActivityPerformingAgents()
                .size()); // 97 agents perform an activity before the time step
        assertEquals(
            97,
            this.arp
                .getActivityEndingAgents(e.getSimulationTime())
                .size()); // 97 agents end an activity

        // now reschedule the activity end time of an agent
        MobsimAgent agent = this.agents.get(Id.create("40", Person.class));
        Activity currentActivity = (Activity) WithinDayAgentUtils.getCurrentPlanElement(agent);
        currentActivity.setEndTime(e.getSimulationTime() + 60);
        WithinDayAgentUtils.resetCaches(agent);
        this.withinDayEngine.getActivityRescheduler().rescheduleActivityEnd(agent);
        ((QSim) e.getQueueSimulation())
            .getEventsManager()
            .processEvent(
                new ReplanningEvent(e.getSimulationTime(), agent.getId(), "ActivityRescheduler"));

        // reschedule a second time to check what happens if the agent is replanned multiple times
        // in one time step
        currentActivity.setEndTime(e.getSimulationTime() + 120);
        WithinDayAgentUtils.resetCaches(agent);
        this.withinDayEngine.getActivityRescheduler().rescheduleActivityEnd(agent);
        ((QSim) e.getQueueSimulation())
            .getEventsManager()
            .processEvent(
                new ReplanningEvent(e.getSimulationTime(), agent.getId(), "ActivityRescheduler"));
      }

      if (e.getSimulationTime() == t5) {
        assertEquals(
            1,
            this.arp
                .getActivityPerformingAgents()
                .size()); // one agent performs an activity before the time step
        assertEquals(
            0,
            this.arp
                .getActivityEndingAgents(e.getSimulationTime())
                .size()); // no agent ends an activity
      }

      if (e.getSimulationTime() == t6) {
        assertEquals(
            1,
            this.arp
                .getActivityPerformingAgents()
                .size()); // one agent performs an activity before the time step
        assertEquals(
            1,
            this.arp
                .getActivityEndingAgents(e.getSimulationTime())
                .size()); // one agent ends an activity
      }
    }
Exemple #22
0
  private void createOneVWShiftWorker(int i, Coord homeC, String mode, String fromToPrefix) {
    int additionalTrips = random.nextInt(4);

    Id<Person> personId = Id.createPersonId(fromToPrefix + i + "vw");
    Person person = scenario.getPopulation().getFactory().createPerson(personId);

    Plan plan = scenario.getPopulation().getFactory().createPlan();

    int rand = random.nextInt(3) + 1;
    switch (rand) {
      case 1:
        Activity home =
            scenario.getPopulation().getFactory().createActivityFromCoord("home", homeC);
        home.setEndTime(5 * 60 * 60);
        plan.addActivity(home);

        Leg outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
        plan.addLeg(outboundTrip);

        Coord coord3 = scenario.getNetwork().getLinks().get(calcVWWorkLinkId()).getCoord();
        Activity shift1 =
            scenario.getPopulation().getFactory().createActivityFromCoord("work_vw_shift1", coord3);
        shift1.setEndTime(13 * 60 * 60 + 40 * 60);
        plan.addActivity(shift1);
        if (additionalTrips == 1 || additionalTrips == 3) {
          enrichPlanBySingleLegAndActivity(coord3, plan, mode, 5400, false);
        }

        Leg returnTrip = scenario.getPopulation().getFactory().createLeg(mode);
        plan.addLeg(returnTrip);

        Activity home2 =
            scenario.getPopulation().getFactory().createActivityFromCoord("home", homeC);
        plan.addActivity(home2);
        if (additionalTrips > 1) {
          home2.setMaximumDuration(random.nextInt(5400));

          enrichPlanByReturnLegAndActivity(home2, plan, mode, 5400);
        }
        break;
      case 2:
        home = scenario.getPopulation().getFactory().createActivityFromCoord("home", homeC);
        home.setEndTime(13 * 60 * 60);

        plan.addActivity(home);

        if (additionalTrips > 1) {

          enrichPlanByReturnLegAndActivity(home, plan, mode, 5400);
          home.setEndTime(8 * 3600 + random.nextInt(7200));
          ;
        }

        if (additionalTrips == 1 || additionalTrips == 3) {
          enrichPlanBySingleLegAndActivity(homeC, plan, mode, 5400, false);
        }
        outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
        plan.addLeg(outboundTrip);

        Coord coord = scenario.getNetwork().getLinks().get(calcVWWorkLinkId()).getCoord();
        Activity shift2 =
            scenario.getPopulation().getFactory().createActivityFromCoord("work_vw_shift2", coord);
        shift2.setEndTime(21 * 60 * 60 + 40 * 60);
        plan.addActivity(shift2);

        returnTrip = scenario.getPopulation().getFactory().createLeg(mode);
        plan.addLeg(returnTrip);

        home2 = scenario.getPopulation().getFactory().createActivityFromCoord("home", homeC);
        plan.addActivity(home2);

        break;
      case 3:
        Id<Link> workLink = calcVWWorkLinkId();
        Coord coord2 = scenario.getNetwork().getLinks().get(workLink).getCoord();
        Activity shift3 =
            scenario.getPopulation().getFactory().createActivityFromCoord("work_vw_shift3", coord2);
        shift3.setEndTime(5 * 60 * 60 + 40 * 60);
        plan.addActivity(shift3);

        if (additionalTrips == 1 || additionalTrips == 3) {
          enrichPlanBySingleLegAndActivity(coord2, plan, mode, 5400, false);
        }
        outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
        plan.addLeg(outboundTrip);

        home = scenario.getPopulation().getFactory().createActivityFromCoord("homeD", homeC);
        home.setEndTime(21 * 60 * 60);
        plan.addActivity(home);

        if (additionalTrips > 1) {

          enrichPlanByReturnLegAndActivity(home, plan, mode, 5400);
          home.setEndTime(8 * 3600 + random.nextInt(7200));
          ;
        }

        outboundTrip = scenario.getPopulation().getFactory().createLeg(mode);
        plan.addLeg(outboundTrip);

        Activity shift32 =
            scenario
                .getPopulation()
                .getFactory()
                .createActivityFromCoord(
                    "work_vw_shift3", scenario.getNetwork().getLinks().get(workLink).getCoord());

        plan.addActivity(shift32);
        break;
    }

    person.addPlan(plan);
    scenario.getPopulation().addPerson(person);
  }