예제 #1
0
  public double getParkingWalkBeta(Person person, double activityDurationInSeconds) {
    Id personId = person.getId();
    Parser parser = null;
    if (!parkingWalkBetaCache.containsKey(personId)) {
      Parser pTmp = new Parser(parkingWalkBeta);
      PersonImpl persImpl = (PersonImpl) person;

      int isMale = 1;
      if (persImpl.getSex() != null) {
        isMale = !persImpl.getSex().contains("f") ? 1 : 0;
      }

      pTmp.setVariable("isMale", isMale);

      int age = persImpl.getAge();

      pTmp.setVariable("ageInYears", age);
      parkingWalkBetaCache.put(personId, pTmp);
    }
    parser = parkingWalkBetaCache.get(personId);

    parser.setVariable("activityDurationInSeconds", activityDurationInSeconds);

    double result = 0;

    try {
      result = parser.parse();
    } catch (SyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return result;
  }
 @Test
 public void testIgnoreCarAvailability_Always() {
   ChooseRandomSingleLegMode algo =
       new ChooseRandomSingleLegMode(
           new String[] {TransportMode.car, TransportMode.pt, TransportMode.bike}, new Random(1));
   algo.setIgnoreCarAvailability(false);
   Person person = PersonImpl.createPerson(Id.create(1, Person.class));
   PersonUtils.setCarAvail(person, "always");
   PlanImpl plan = new org.matsim.core.population.PlanImpl(person);
   plan.createAndAddActivity("home", new Coord((double) 0, (double) 0));
   plan.createAndAddLeg(TransportMode.pt);
   plan.createAndAddActivity("work", new Coord((double) 0, (double) 0));
   algo.run(plan);
   assertEquals(
       "unexpected leg mode in leg 1.",
       TransportMode.car,
       ((Leg) plan.getPlanElements().get(1)).getMode());
   algo.run(plan);
   assertEquals(
       "unexpected leg mode in leg 1.",
       TransportMode.pt,
       ((Leg) plan.getPlanElements().get(1)).getMode());
   algo.run(plan);
   assertEquals(
       "unexpected leg mode in leg 1.",
       TransportMode.car,
       ((Leg) plan.getPlanElements().get(1)).getMode());
   algo.run(plan);
   assertEquals(
       "unexpected leg mode in leg 1.",
       TransportMode.bike,
       ((Leg) plan.getPlanElements().get(1)).getMode());
 }
 @Test
 public void testRandomChoice() {
   ChooseRandomSingleLegMode algo =
       new ChooseRandomSingleLegMode(
           new String[] {TransportMode.car, TransportMode.pt, TransportMode.walk},
           MatsimRandom.getRandom());
   PlanImpl plan =
       new org.matsim.core.population.PlanImpl(
           PersonImpl.createPerson(Id.create(1, Person.class)));
   plan.createAndAddActivity("home", new Coord((double) 0, (double) 0));
   LegImpl leg = plan.createAndAddLeg(TransportMode.car);
   plan.createAndAddActivity("work", new Coord((double) 0, (double) 0));
   boolean foundCarMode = false;
   boolean foundPtMode = false;
   boolean foundWalkMode = false;
   for (int i = 0; i < 5; i++) {
     algo.run(plan);
     String mode = leg.getMode();
     if (TransportMode.car.equals(mode)) {
       foundCarMode = true;
     } else if (TransportMode.pt.equals(mode)) {
       foundPtMode = true;
     } else if (TransportMode.walk.equals(mode)) {
       foundWalkMode = true;
     } else {
       fail("unexpected mode: " + mode);
     }
   }
   assertTrue("expected to find car-mode", foundCarMode);
   assertTrue("expected to find pt-mode", foundPtMode);
   assertTrue("expected to find walk-mode", foundWalkMode);
 }
 @Test
 public void testHandlePlan_OnlySingleLegChanged() {
   ChooseRandomSingleLegMode algo =
       new ChooseRandomSingleLegMode(
           new String[] {TransportMode.car, TransportMode.pt, TransportMode.walk},
           MatsimRandom.getRandom());
   PlanImpl plan =
       new org.matsim.core.population.PlanImpl(
           PersonImpl.createPerson(Id.create(1, Person.class)));
   plan.createAndAddActivity("home", new Coord(0, 0));
   LegImpl leg1 = plan.createAndAddLeg(TransportMode.car);
   plan.createAndAddActivity("work", new Coord((double) 0, (double) 0));
   LegImpl leg2 = plan.createAndAddLeg(TransportMode.car);
   plan.createAndAddActivity("home", new Coord((double) 0, (double) 0));
   String oldMode1 = leg1.getMode();
   String oldMode2 = leg2.getMode();
   for (int i = 0; i < 5; i++) {
     algo.run(plan);
     int cntChanges = 0;
     String mode1 = leg1.getMode();
     String mode2 = leg2.getMode();
     if (!mode1.equals(oldMode1)) {
       cntChanges++;
       oldMode1 = mode1;
     }
     if (!mode2.equals(oldMode2)) {
       cntChanges++;
       oldMode2 = mode2;
     }
     assertEquals(1, cntChanges);
   }
 }
예제 #5
0
  private SocialPerson createPerson(VertexRecord record, SQLDumpReader sqlData) {
    Person matsimPerson = PersonImpl.createPerson(Id.create(record.id, Person.class));
    SocialPerson person = new SocialPerson(matsimPerson);

    int age;
    if (record.isEgo) age = sqlData.getEgoAge(record.egoSQLId);
    else age = sqlData.getAlterAge(record.alterKeys);

    if (age < 0) errLogger.logNoAge(record.isEgo);
    else PersonUtils.setAge(matsimPerson, age);

    String sex = sqlData.getSex(record);
    if (sex != null) PersonUtils.setSex(matsimPerson, sex);
    else errLogger.logNoSex(record.isEgo);

    if (record.isEgo) PersonUtils.setLicence(matsimPerson, sqlData.getLicense(record));

    if (record.isEgo) PersonUtils.setCarAvail(matsimPerson, sqlData.getCarAvail(record));

    person.setCitizenship(sqlData.getCitizenship(record));
    person.setEducation(sqlData.getEducation(record));
    person.setIncome(sqlData.getIncome(record));
    person.setCivilStatus(sqlData.getCivilStatus(record));
    return person;
  }
예제 #6
0
 /**
  * copy the person and the selected plan of the person
  *
  * @param person
  * @return
  */
 public static Person copyPerson(Person person) {
   Person newPerson = PersonImpl.createPerson(person.getId());
   PlanImpl newPlan = new PlanImpl();
   newPlan.copyFrom(person.getSelectedPlan());
   newPlan.setPerson(newPerson);
   newPerson.addPlan(newPlan);
   newPerson.setSelectedPlan(newPlan);
   PersonUtils.removeUnselectedPlans(newPerson);
   return newPerson;
 }
  /**
   * 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);
  }
예제 #8
0
  private static Person createPerson(
      final int count, final boolean joint, final Map<Id<Person>, Plan> jointPlan) {
    Id<Person> id = Id.createPersonId(count);
    Person person = PersonImpl.createPerson(id);
    PlanImpl plan = new PlanImpl(person);
    person.addPlan(plan);
    if (joint) jointPlan.put(id, plan);
    if (!plan.isSelected()) throw new RuntimeException();

    return person;
  }
 @Test
 public void testHandleEmptyPlan() {
   ChooseRandomSingleLegMode algo =
       new ChooseRandomSingleLegMode(
           new String[] {TransportMode.car, TransportMode.pt, TransportMode.walk},
           MatsimRandom.getRandom());
   PlanImpl plan =
       new org.matsim.core.population.PlanImpl(
           PersonImpl.createPerson(Id.create(1, Person.class)));
   algo.run(plan);
   // no specific assert, but there should also be no NullPointerException or similar stuff that
   // could theoretically happen
 }
 @Test
 public void testHandlePlan_DifferentThanLastMode() {
   ChooseRandomSingleLegMode algo =
       new ChooseRandomSingleLegMode(
           new String[] {TransportMode.car, TransportMode.pt, TransportMode.walk},
           MatsimRandom.getRandom());
   PlanImpl plan =
       new org.matsim.core.population.PlanImpl(
           PersonImpl.createPerson(Id.create(1, Person.class)));
   plan.createAndAddActivity("home", new Coord((double) 0, (double) 0));
   LegImpl leg = plan.createAndAddLeg(TransportMode.car);
   plan.createAndAddActivity("work", new Coord((double) 0, (double) 0));
   String oldMode = leg.getMode();
   for (int i = 0; i < 5; i++) {
     algo.run(plan);
     String mode = leg.getMode();
     assertTrue(!oldMode.equals(mode));
     oldMode = mode;
   }
 }
예제 #11
0
  public void run(ParkControl parkControl) {
    Controler controler = parkControl.controller;
    if (!parkControl.evUsage) {
      System.out.println("Iteration end stats does not work without EV usage");
      return;
    }

    LinkedList<Id> totEVDriving = new LinkedList<Id>();
    LinkedList<Id> totNEVDriving = new LinkedList<Id>();
    LinkedList<Id> totEVNotDriving = new LinkedList<Id>();
    LinkedList<Id> totNEVNotDriving = new LinkedList<Id>();
    LinkedList<Id> secEVDriving = new LinkedList<Id>();
    LinkedList<Id> secNEVDriving = new LinkedList<Id>();
    LinkedList<Id> secEVNotDriving = new LinkedList<Id>();
    LinkedList<Id> secNEVNotDriving = new LinkedList<Id>();
    LinkedList<Id> workEVDriving = new LinkedList<Id>();
    LinkedList<Id> workNEVDriving = new LinkedList<Id>();
    LinkedList<Id> workEVNotDriving = new LinkedList<Id>();
    LinkedList<Id> workNEVNotDriving = new LinkedList<Id>();
    LinkedList<Id> totCharged = new LinkedList<Id>();
    LinkedList<Id> workCharged = new LinkedList<Id>();
    LinkedList<Id> secCharged = new LinkedList<Id>();
    LinkedList<Id> totHadToCharge = new LinkedList<Id>();
    LinkedList<Id> workHadToCharge = new LinkedList<Id>();
    LinkedList<Id> secHadToCharge = new LinkedList<Id>();
    LinkedList<Id> totOutOfBattery = new LinkedList<Id>();
    LinkedList<Id> workOutOfBattery = new LinkedList<Id>();
    LinkedList<Id> secOutOfBattery = new LinkedList<Id>();
    LinkedList<Id> totEvNotParked = new LinkedList<Id>();
    LinkedList<Id> workEvNotParked = new LinkedList<Id>();
    LinkedList<Id> secEvNotParked = new LinkedList<Id>();
    LinkedList<Id> totNEvNotParked = new LinkedList<Id>();
    LinkedList<Id> workNEvNotParked = new LinkedList<Id>();
    LinkedList<Id> secNEvNotParked = new LinkedList<Id>();
    LinkedList<Id> totBrookingsEVsDriving = new LinkedList<Id>();
    LinkedList<Id> totBrookingsEVsNotDriving = new LinkedList<Id>();
    LinkedList<Id> workBrookingsEVsDriving = new LinkedList<Id>();
    LinkedList<Id> workBrookingsEVsNotDriving = new LinkedList<Id>();
    LinkedList<Id> secBrookingsEVsDriving = new LinkedList<Id>();
    LinkedList<Id> secBrookingsEVsNotDriving = new LinkedList<Id>();
    LinkedList<Id> totEVParkedAtHome = new LinkedList<Id>();
    LinkedList<Id> totNEVParkedAtHome = new LinkedList<Id>();
    LinkedList<Id> workEVParkedAtHome = new LinkedList<Id>();
    LinkedList<Id> workNEVParkedAtHome = new LinkedList<Id>();
    LinkedList<Id> secEVParkedAtHome = new LinkedList<Id>();
    LinkedList<Id> secNEVParkedAtHome = new LinkedList<Id>();

    VMCharts chart = new VMCharts();
    chart.addChart("Util vs Traveldistance");
    chart.setAx("Util vs Traveldistance", false);
    chart.setBox("Util vs Traveldistance", true);
    chart.setInterval("Util vs Traveldistance", 10000);
    chart.addSeries("Util vs Traveldistance", "NEV");
    chart.addSeries("Util vs Traveldistance", "EV");

    chart.addChart("Util vs Traveldistance EV");
    chart.setAx("Util vs Traveldistance EV", false);
    chart.setBox("Util vs Traveldistance EV", true);
    chart.setInterval("Util vs Traveldistance EV", 10000);
    chart.addSeries("Util vs Traveldistance EV", "EV");

    EVControl evControl = parkControl.evControl;

    for (Person person : controler.getScenario().getPopulation().getPersons().values()) {
      PersonImpl personImpl = (PersonImpl) person;
      double soc;
      boolean notParked = false;
      boolean parkedAtHome = false;
      PlanImpl planImpl = (PlanImpl) personImpl.getSelectedPlan();
      LegImpl legImpl = (LegImpl) planImpl.getNextLeg(planImpl.getFirstActivity());
      Id id = person.getId();
      LinkedList<ParkingSpot> selectedParkings = parkings.get(id);
      Activity firstAct = planImpl.getFirstActivity();
      String actType = planImpl.getNextActivity(legImpl).getType();
      ParkingSpot firstSelectedSpot;
      ParkingSpot homeSpot;
      String facId = firstAct.getFacilityId().toString();
      if (parkings.containsKey(id)) {
        firstSelectedSpot = selectedParkings.getFirst();
        homeSpot = selectedParkings.getLast();
      } else {
        firstSelectedSpot = new ParkingSpot();
        homeSpot = new ParkingSpot();
        notParked = true;
      }
      if (homeSpot != null
          && homeSpot.parking != null
          && homeSpot.parking.facilityActType != null) {
        if (homeSpot.parking.facilityActType.equals("home")) {
          parkedAtHome = true;
        }
      }

      if (evControl.hasEV(person.getId()) && firstSelectedSpot != null) {
        soc = evControl.stateOfChargePercentage(person.getId());
      } else soc = -150;

      double score = personImpl.getSelectedPlan().getScore();
      double distance = getPlanDistance(planImpl);
      if (score < 0) {
        score = -1;
      }
      if (evControl.hasEV(person.getId())) {
        VMCharts.addValues("Util vs Traveldistance", "EV", distance, score);
        VMCharts.addValues("Util vs Traveldistance EV", "EV", distance, score);
      } else {
        VMCharts.addValues("Util vs Traveldistance", "NEV", distance, score);
      }

      if (evControl.hasEV(person.getId())) {
        if (legImpl.getMode().equals("car")) {
          totEVDriving.add(id);
          if (facId.contains("B")) {
            totBrookingsEVsDriving.add(id);
          }
          if (firstSelectedSpot.charge) {
            totCharged.add(id);
          }
          if (soc < 50) {
            totHadToCharge.add(id);
          }
          if (soc < 0) {
            totOutOfBattery.add(id);
          }
          if (notParked) {
            totEvNotParked.add(id);
          }
          if (parkedAtHome) {
            totEVParkedAtHome.add(id);
          }
          if (actType.equals("work")) {
            workEVDriving.add(id);
            if (facId.contains("B")) {
              workBrookingsEVsDriving.add(id);
            }
            if (firstSelectedSpot.charge) {
              workCharged.add(id);
            }
            if (soc < 50) {
              workHadToCharge.add(id);
            }
            if (soc < 0) {
              workOutOfBattery.add(id);
            }
            if (notParked) {
              workEvNotParked.add(id);
            }
            if (parkedAtHome) {
              workEVParkedAtHome.add(id);
            }
          } else if (actType.equals("secondary")) {
            secEVDriving.add(id);
            if (facId.contains("B")) {
              secBrookingsEVsDriving.add(id);
            }
            if (firstSelectedSpot.charge) {
              secCharged.add(id);
            }
            if (soc < 50) {
              secHadToCharge.add(id);
            }
            if (soc < 0) {
              secOutOfBattery.add(id);
            }
            if (notParked) {
              secEvNotParked.add(id);
            }
            if (parkedAtHome) {
              secEVParkedAtHome.add(id);
            }
          }
        } else {
          totEVNotDriving.add(id);
          if (facId.contains("B")) {
            totBrookingsEVsNotDriving.add(id);
          }
          if (actType.equals("work")) {
            workEVNotDriving.add(id);
            if (facId.contains("B")) {
              workBrookingsEVsNotDriving.add(id);
            }
          } else if (actType.equals("secondary")) {
            secEVNotDriving.add(id);
            if (facId.contains("B")) {
              secBrookingsEVsNotDriving.add(id);
            }
          }
        }
      } else {
        if (legImpl.getMode().equals("car")) {
          totNEVDriving.add(id);
          if (notParked) {
            totNEvNotParked.add(id);
          }
          if (parkedAtHome) {
            totNEVParkedAtHome.add(id);
          }
          if (actType.equals("work")) {
            workNEVDriving.add(id);
            if (notParked) {
              workNEvNotParked.add(id);
            }
            if (parkedAtHome) {
              workNEVParkedAtHome.add(id);
            }
          } else if (actType.equals("secondary")) {
            secNEVDriving.add(id);
            if (notParked) {
              secNEvNotParked.add(id);
            }
            if (parkedAtHome) {
              secNEVParkedAtHome.add(id);
            }
          }
        } else {
          totNEVNotDriving.add(id);
          if (actType.equals("work")) {
            workNEVNotDriving.add(id);
          } else if (actType.equals("secondary")) {
            secNEVNotDriving.add(id);
          }
        }
      }
    }

    chart.addChart("Parkinglot occupancy");
    chart.setAx("Parkinglot occupancy", false);
    chart.setAxis("Parkinglot occupancy", "time", "occupancy [0..1]");
    chart.setLine("Parkinglot occupancy", true);
    for (Parking parking : parkControl.parkingMap.getParkings()) {
      if (parking.ocupancyStats == true) {
        chart.addSeries("Parkinglot occupancy", Integer.toString(parking.id) + "EV");
        chart.addSeries("Parkinglot occupancy", Integer.toString(parking.id) + "NEV");
        for (Double[] values : parking.occupancyList) {
          VMCharts.addValues(
              "Parkinglot occupancy", Integer.toString(parking.id) + "EV", values[0], values[1]);
          VMCharts.addValues(
              "Parkinglot occupancy", Integer.toString(parking.id) + "NEV", values[0], values[2]);
        }
      }
    }

    CSVWriter writer =
        new CSVWriter(
            controler.getConfig().getModule("controler").getValue("outputDirectory")
                + "/parkhistory/parkstats_"
                + controler.getIterationNumber());
    writer.writeLine("Total: ");
    writer.writeLine(
        "EVs in use: "
            + totEVDriving.size()
            + " ("
            + totBrookingsEVsDriving.size()
            + " Brookings)");
    writer.writeLine(
        "EVs not in use: "
            + totEVNotDriving.size()
            + " ("
            + totBrookingsEVsNotDriving.size()
            + " Brookings)");
    writer.writeLine("EVs not parked: " + totEvNotParked.size());
    writer.writeLine("EVs parked at home: " + totEVParkedAtHome.size());
    writer.writeLine("charged: " + totCharged.size());
    writer.writeLine("had to charge: " + totHadToCharge.size());
    writer.writeLine("out of battery: " + totOutOfBattery.size());
    writer.writeLine("NEVs in use: " + totNEVDriving.size());
    writer.writeLine("NEVs not in use: " + totNEVNotDriving.size());
    writer.writeLine("NEVs not parked: " + totNEvNotParked.size());
    writer.writeLine("NEVs parked at home: " + totNEVParkedAtHome.size());
    writer.writeLine("");
    writer.writeLine("Work: ");
    writer.writeLine(
        "EVs in use: "
            + workEVDriving.size()
            + " ("
            + workBrookingsEVsDriving.size()
            + " Brookings)");
    writer.writeLine(
        "EVs not in use: "
            + workEVNotDriving.size()
            + " ("
            + workBrookingsEVsNotDriving.size()
            + " Brookings)");
    writer.writeLine("EVs not parked: " + workEvNotParked.size());
    writer.writeLine("EVs parked at home: " + workEVParkedAtHome.size());
    writer.writeLine("charged: " + workCharged.size());
    writer.writeLine("had to charge: " + workHadToCharge.size());
    writer.writeLine("out of battery: " + workOutOfBattery.size());
    writer.writeLine("NEVs in use: " + workNEVDriving.size());
    writer.writeLine("NEVs not in use: " + workNEVNotDriving.size());
    writer.writeLine("NEVs not parked: " + workNEvNotParked.size());
    writer.writeLine("NEVs parked at home: " + workNEVParkedAtHome.size());
    writer.writeLine("");
    writer.writeLine("Secondary: ");
    writer.writeLine(
        "EVs in use: "
            + secEVDriving.size()
            + " ("
            + secBrookingsEVsDriving.size()
            + " Brookings)");
    writer.writeLine(
        "EVs not in use: "
            + secEVNotDriving.size()
            + " ("
            + secBrookingsEVsNotDriving.size()
            + " Brookings)");
    writer.writeLine("EVs not parked: " + secEvNotParked.size());
    writer.writeLine("EVs parked at home: " + secEVParkedAtHome.size());
    writer.writeLine("charged: " + secCharged.size());
    writer.writeLine("had to charge: " + secHadToCharge.size());
    writer.writeLine("out of battery: " + secOutOfBattery.size());
    writer.writeLine("NEVs in use: " + secNEVDriving.size());
    writer.writeLine("NEVs not in use: " + secNEVNotDriving.size());
    writer.writeLine("NEVs not parked: " + secNEvNotParked.size());
    writer.writeLine("NEVs parked at home: " + secNEVParkedAtHome.size());
    writer.writeLine("");

    writer.close();
  }
예제 #12
0
 @Override
 public void run(Person person) {
   PersonImpl p2 = (PersonImpl) person;
   p2.setSelectedPlan(p2.getPlans().get(0));
   // planScoreNullifier.run(p2);
 }
예제 #13
0
  void readPersonsFromHouseholds(
      Population population, ActivityFacilitiesImpl facilities, double fraction) {
    log.fatal("does not work; see javadoc of class.  Aborting ..." + this);
    System.exit(-1);
    try {
      BufferedReader reader =
          IOUtils.getBufferedReader(Matsim4Urbansim.PATH_TO_OPUS_MATSIM + "tmp/households.tab");

      String header = reader.readLine();
      Map<String, Integer> idxFromKey = Utils.createIdxFromKey(header, null);

      String line = reader.readLine();
      while (line != null) {
        String[] parts = line.split("[\t\n]+");

        if (Math.random() > fraction) {
          line = reader.readLine(); // next line
          continue;
        }

        int idx = idxFromKey.get("persons:i4");
        int nPersons = Integer.parseInt(parts[idx]);

        idx = idxFromKey.get("workers:i4");
        int nWorkers = Integer.parseInt(parts[idx]);

        idx = idxFromKey.get("household_id:i4");
        Id<HH> hhId = Id.create(parts[idx], HH.class);

        idx = idxFromKey.get("grid_id:i4");
        Id<Location> homeGridId = Id.create(parts[idx], Location.class);
        ActivityFacility homeLocation =
            facilities.getFacilities().get(Id.create(homeGridId, ActivityFacility.class));
        if (homeLocation == null) {
          log.warn("no home location; hhId: " + hhId.toString());
          line = reader.readLine(); // next line
          continue;
        }
        Coord homeCoord = homeLocation.getCoord();

        // generate persons only after it's clear that they have a home location:
        for (int ii = 0; ii < nPersons; ii++) {
          Id<Person> personId = Id.create(personCnt, Person.class);
          Person person = PersonImpl.createPerson(personId);
          personCnt++;
          if (personCnt > 10) {
            log.error("hack");
            return;
          }

          population.addPerson(person);

          PlanImpl plan = PersonUtils.createAndAddPlan(person, true);
          Utils.makeHomePlan(plan, homeCoord);

          if (ii < nWorkers) {
            PersonUtils.setEmployed(person, Boolean.TRUE);
          } else {
            PersonUtils.setEmployed(person, Boolean.FALSE);
          }
        }
        line = reader.readLine(); // next line
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.exit(-1);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #14
0
 public int getAge() {
   return person.getAge();
 }
예제 #15
0
  private static void testRestrictedNetwork(final Config config) throws Exception {
    // create a simple scenario, with two parallel links,
    // a long one for cars, a short one for pt.
    final Scenario scenario = ScenarioUtils.createScenario(config);
    Network net = scenario.getNetwork();

    Node n1 =
        net.getFactory().createNode(Id.create(1, Node.class), new Coord((double) 0, (double) 0));
    Node n2 =
        net.getFactory().createNode(Id.create(2, Node.class), new Coord((double) 0, (double) 0));
    Node n3 =
        net.getFactory().createNode(Id.create(3, Node.class), new Coord((double) 0, (double) 0));
    Node n4 =
        net.getFactory().createNode(Id.create(4, Node.class), new Coord((double) 0, (double) 0));

    Link l1 = net.getFactory().createLink(Id.create("l1", Link.class), n1, n2);
    Link l2c = net.getFactory().createLink(Id.create("l2c", Link.class), n2, n3);
    Link l2pt = net.getFactory().createLink(Id.create("l2pt", Link.class), n2, n3);
    Link l3 = net.getFactory().createLink(Id.create("l3", Link.class), n3, n4);

    l2c.setAllowedModes(Collections.singleton(TransportMode.car));
    l2c.setLength(1000);
    l2pt.setAllowedModes(Collections.singleton(TransportMode.pt));
    l2pt.setLength(10);

    net.addNode(n1);
    net.addNode(n2);
    net.addNode(n3);
    net.addNode(n4);

    net.addLink(l1);
    net.addLink(l2c);
    net.addLink(l2pt);
    net.addLink(l3);

    Injector injector =
        Injector.createInjector(
            scenario.getConfig(),
            new AbstractModule() {
              @Override
              public void install() {
                install(
                    AbstractModule.override(
                        Arrays.asList(new TripRouterModule()),
                        new AbstractModule() {
                          @Override
                          public void install() {
                            bind(Scenario.class).toInstance(scenario);
                            addTravelTimeBinding("car")
                                .toInstance(
                                    new FreespeedTravelTimeAndDisutility(config.planCalcScore()));
                            addTravelDisutilityFactoryBinding("car")
                                .toInstance(new OnlyTimeDependentTravelDisutilityFactory());
                          }
                        }));
              }
            });

    // create the factory, get a router, route.
    Provider<TripRouter> factory = injector.getProvider(TripRouter.class);

    TripRouter router = factory.get();

    List<? extends PlanElement> trip =
        router.calcRoute(
            TransportMode.car,
            new LinkFacility(l1),
            new LinkFacility(l3),
            0,
            PersonImpl.createPerson(Id.create("toto", Person.class)));

    Leg l = (Leg) trip.get(0);

    // actual test
    NetworkRoute r = (NetworkRoute) l.getRoute();

    Assert.assertEquals("unexpected route length " + r.getLinkIds(), 1, r.getLinkIds().size());

    Assert.assertEquals("unexpected link", l2c.getId(), r.getLinkIds().get(0));
  }
예제 #16
0
  /** Checks that routes are found when using a monomodal network (ie modes are not restricted) */
  @Test
  public void testMonomodalNetwork() throws Exception {
    final Config config = ConfigUtils.createConfig();
    final Scenario scenario = ScenarioUtils.createScenario(config);
    Network net = scenario.getNetwork();

    Node n1 =
        net.getFactory().createNode(Id.create(1, Node.class), new Coord((double) 0, (double) 0));
    Node n2 =
        net.getFactory().createNode(Id.create(2, Node.class), new Coord((double) 0, (double) 0));
    Node n3 =
        net.getFactory().createNode(Id.create(3, Node.class), new Coord((double) 0, (double) 0));
    Node n4 =
        net.getFactory().createNode(Id.create(4, Node.class), new Coord((double) 0, (double) 0));

    Link l1 = net.getFactory().createLink(Id.create("l1", Link.class), n1, n2);
    Link l2long = net.getFactory().createLink(Id.create("l2long", Link.class), n2, n3);
    Link l2short = net.getFactory().createLink(Id.create("l2short", Link.class), n2, n3);
    Link l3 = net.getFactory().createLink(Id.create("l3", Link.class), n3, n4);

    l2long.setLength(1000);
    l2short.setLength(10);

    net.addNode(n1);
    net.addNode(n2);
    net.addNode(n3);
    net.addNode(n4);

    net.addLink(l1);
    net.addLink(l2long);
    net.addLink(l2short);
    net.addLink(l3);

    // create the factory, get a router, route.
    Injector injector =
        Injector.createInjector(
            scenario.getConfig(),
            new AbstractModule() {
              @Override
              public void install() {
                install(
                    AbstractModule.override(
                        Arrays.asList(new TripRouterModule()),
                        new AbstractModule() {
                          @Override
                          public void install() {
                            bind(Scenario.class).toInstance(scenario);
                            addTravelTimeBinding("car")
                                .toInstance(
                                    new FreespeedTravelTimeAndDisutility(config.planCalcScore()));
                            addTravelDisutilityFactoryBinding("car")
                                .toInstance(new OnlyTimeDependentTravelDisutilityFactory());
                          }
                        }));
              }
            });

    TripRouter router = injector.getInstance(TripRouter.class);

    List<? extends PlanElement> trip =
        router.calcRoute(
            TransportMode.car,
            new LinkFacility(l1),
            new LinkFacility(l3),
            0,
            PersonImpl.createPerson(Id.create("toto", Person.class)));

    Leg l = (Leg) trip.get(0);

    // actual test
    NetworkRoute r = (NetworkRoute) l.getRoute();

    Assert.assertEquals("unexpected route length " + r.getLinkIds(), 1, r.getLinkIds().size());

    Assert.assertEquals("unexpected link", l2short.getId(), r.getLinkIds().get(0));
  }
예제 #17
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());
    }
  }
  private boolean microRouteCurrentLegRoute(
      Leg leg,
      Person person,
      int currentLinkIndex,
      double time,
      Network network,
      TripRouter tripRouter,
      Random random,
      Plan plan) {

    Route route = leg.getRoute();

    // if the route type is not supported (e.g., because it is a walking agent)
    if (!(route instanceof NetworkRoute)) return false;

    if (random.nextFloat() > 0.3) return false; // only 30% replanners

    PersonImpl p = (PersonImpl) person;
    int legnr = plan.getPlanElements().indexOf(leg);

    //	logger.warn(legnr);

    if (p.getAge() == legnr) {
      //		logger.error("agent already replanned");
      //		return false; // agent has been replanned already
    } else {
      //		p.setAge(legnr);
    }

    NetworkRoute oldRoute = (NetworkRoute) route;

    /*
     *  Get the Id of the current Link.
     *  Create a List that contains all links of a route, including the Start- and EndLinks.
     */
    List<Id<Link>> allLinkIds = getRouteLinkIds(oldRoute); //

    int links2go = allLinkIds.size() - (currentLinkIndex + 1); //

    if (links2go >= 3) {
      Id<Link> startLink = allLinkIds.get(0);
      Id<Link> endLink = allLinkIds.get(allLinkIds.size() - 1);

      // The linkIds of the new Route ---------------------------
      List<Id<Link>> linkIds = new ArrayList<Id<Link>>();
      // start of the old route
      linkIds.addAll(allLinkIds.subList(1, currentLinkIndex)); // currentLinkIndex exclusive

      // micro-reroute part of route ---------------------------
      Id<Link> currentLinkId = allLinkIds.get(currentLinkIndex); // link 1, currentLinkIndex = 1
      Link fromLink = network.getLinks().get(currentLinkId);

      int jump = random.nextInt(links2go - 2) + 2; // start with 2
      int toLinkIndex = (currentLinkIndex + jump); // jump over one link //
      Id<Link> toLinkId = allLinkIds.get(toLinkIndex); //
      Link toLink = network.getLinks().get(toLinkId); //

      Facility<ActivityFacility> fromFacility = new LinkWrapperFacility(fromLink);
      Facility<ActivityFacility> toFacility = new LinkWrapperFacility(toLink);

      List<? extends PlanElement> planElements =
          tripRouter.calcRoute(leg.getMode(), fromFacility, toFacility, time, person); //

      if (planElements.size() != 1) {
        throw new RuntimeException(
            "Expected a list of PlanElements containing exactly one element, "
                + "but the returned list contained "
                + planElements.size()
                + " elements.");
      }
      Leg newLeg = (Leg) planElements.get(0);
      Route newRoute = newLeg.getRoute();
      linkIds.addAll(getRouteLinkIds(newRoute)); // currentLinkIndex => startLink

      // remainder of the old route ---------------------------
      if (toLinkIndex + 1 < allLinkIds.size() - 1) { // if route is not yet finished:
        linkIds.addAll(allLinkIds.subList(toLinkIndex + 1, allLinkIds.size() - 1));
      }

      // Overwrite old Route
      if (linkIds.size() > 2 && toLinkId.compareTo(fromLink.getId()) != 0) {
        List<Id<Link>> middleLinks = linkIds.subList(0, linkIds.size()); // to is exclusive

        //				String str = oldRoute.toString();
        //				int lo = oldRoute.getLinkIds().size();

        oldRoute.setLinkIds(startLink, middleLinks, endLink);

        //				if (oldRoute.getLinkIds().size() != lo) {
        //					logger.info(person.getId() + " :" + str + "\n" +
        //							oldRoute.toString());
        //				}
      } // else do not replace route
    }
    return true;
  }
예제 #19
0
 public Id getId() {
   return person.getId();
 }
예제 #20
0
 @Override
 public void run(final Person p) {
   PersonImpl person = (PersonImpl) p;
   String carAvail = person.getCarAvail();
   int age = person.getAge();
   String license = person.getLicense();
   boolean isEmployed = person.isEmployed();
   if (carAvail != null) {
     if (carAvail.equals("always")) {
       if (person.getSex().equals("m")) {
         male_al++;
       } else {
         female_al++;
       }
       if (age < 30) {
         ageA_al++;
       } else if (age >= 30 && age < 50) {
         ageB_al++;
       } else if (age >= 50 && age < 70) {
         ageC_al++;
       } else {
         ageD_al++;
       }
       if (license.equals("yes")) {
         withLicense_al++;
       } else {
         withoutLicense_al++;
       }
       if (isEmployed) {
         isEmployed_al++;
       } else {
         notEmployed_al++;
       }
     } else if (carAvail.equals("sometimes")) {
       if (person.getSex().equals("m")) {
         male_so++;
       } else {
         female_so++;
       }
       if (age < 30) {
         ageA_so++;
       } else if (age >= 30 && age < 50) {
         ageB_so++;
       } else if (age >= 50 && age < 70) {
         ageC_so++;
       } else {
         ageD_so++;
       }
       if (license.equals("yes")) {
         withLicense_so++;
       } else {
         withoutLicense_so++;
       }
       if (isEmployed) {
         isEmployed_so++;
       } else {
         notEmployed_so++;
       }
     } else if (carAvail.equals("never")) {
       if (person.getSex().equals("m")) {
         male_ne++;
       } else {
         female_ne++;
       }
       if (age < 30) {
         ageA_ne++;
       } else if (age >= 30 && age < 50) {
         ageB_ne++;
       } else if (age >= 50 && age < 70) {
         ageC_ne++;
       } else {
         ageD_ne++;
       }
       if (license.equals("yes")) {
         withLicense_ne++;
       } else {
         withoutLicense_ne++;
       }
       if (isEmployed) {
         isEmployed_ne++;
       } else {
         notEmployed_ne++;
       }
     }
   }
 }