// test overnight activities with first and last activity of different types
  @Test
  public final void test0c() {

    PlanCalcScoreConfigGroup plansCalcScoreConfigGroup = new PlanCalcScoreConfigGroup();

    ActivityParams activityParams1 = new ActivityParams("firstActivityType");
    activityParams1.setTypicalDuration(12 * 3600.);

    ActivityParams activityParams2 = new ActivityParams("lastActivityType");
    activityParams2.setTypicalDuration(12 * 3600.);

    plansCalcScoreConfigGroup.addActivityParams(activityParams1);
    plansCalcScoreConfigGroup.addActivityParams(activityParams2);

    plansCalcScoreConfigGroup.setEarlyDeparture_utils_hr(0.);
    plansCalcScoreConfigGroup.setLateArrival_utils_hr(0.);
    plansCalcScoreConfigGroup.setMarginalUtlOfWaiting_utils_hr(0.);
    plansCalcScoreConfigGroup.setPerforming_utils_hr(6.);

    ScenarioConfigGroup scenarioConfig = new ScenarioConfigGroup();
    CharyparNagelScoringParameters params =
        new CharyparNagelScoringParameters.Builder(
                plansCalcScoreConfigGroup,
                plansCalcScoreConfigGroup.getScoringParameters(null),
                scenarioConfig)
            .build();

    MarginalSumScoringFunction marginaSumScoringFunction = new MarginalSumScoringFunction(params);

    Id<Link> linkId = null;

    ActivityImpl activity1 = new ActivityImpl("firstActivityType", linkId);
    activity1.setEndTime(7 * 3600.);
    ActivityImpl activity2 = new ActivityImpl("lastActivityType", linkId);
    activity2.setStartTime(18 * 3600.);

    // test if zero delay results in zero activity delay disutility
    double delay1 = 0 * 3600.;
    double activityDelayDisutility1 =
        marginaSumScoringFunction.getOvernightActivityDelayDisutility(activity1, activity2, delay1);
    // 6 --> 10.0934029996839 utils + 7 --> 21.1922519472465 utils = 31.285654946930 utils
    // 6 --> 10.0934029996839 utils + 7 --> 21.1922519472465 utils = 31.285654946930 utils
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        0.,
        activityDelayDisutility1,
        MatsimTestUtils.EPSILON);

    // test if a delay results in the right activity delay disutility
    double delay2 = 1 * 3600.;
    double activityDelayDisutility2 =
        marginaSumScoringFunction.getOvernightActivityDelayDisutility(activity1, activity2, delay2);
    // 6 --> 10.0934029996839 utils + 7 --> 21.1922519472465 utils = 31.285654946930 utils
    // 7 --> 21.1922519472465 utils + 7 --> 21.1922519472465 utils = 42.3845038944931 utils
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        11.0988489475631,
        activityDelayDisutility2,
        MatsimTestUtils.EPSILON);
  }
예제 #2
0
 public Population geographicallyFilterPopulation(
     final Population origPopulation, final ObjectAttributes personAttributes) {
   Population filteredPopulation = PopulationUtils.createPopulation(ConfigUtils.createConfig());
   Counter counter = new Counter(" person # ");
   boolean actInArea;
   for (Person p : origPopulation.getPersons().values()) {
     counter.incCounter();
     if (p.getSelectedPlan() != null) {
       actInArea = false;
       for (PlanElement pe : p.getSelectedPlan().getPlanElements()) {
         if (!actInArea && pe instanceof ActivityImpl) {
           ActivityImpl act = (ActivityImpl) pe;
           if (inArea(act.getCoord())) {
             actInArea = true;
           }
         }
       }
       if (actInArea) {
         filteredPopulation.addPerson(p);
         filteredAgents.put(p.getId(), p);
       } else {
         personAttributes.removeAllAttributes(p.toString());
       }
     }
   }
   return filteredPopulation;
 }
예제 #3
0
  public static int getDepartureParkingActIndex(Plan plan, ActivityImpl activity) {
    List<PlanElement> pe = plan.getPlanElements();
    int activityIndex = pe.indexOf(activity);
    int indexOfDepartingParkingAct = -1;

    for (int i = activityIndex; i < pe.size(); i++) {
      if (pe.get(i) instanceof ActivityImpl) {
        ActivityImpl parkingAct = (ActivityImpl) plan.getPlanElements().get(i);
        if (parkingAct.getType().equalsIgnoreCase("parking")) {
          indexOfDepartingParkingAct = i;
          break;
        }
      }
    }

    // if home parking
    if (indexOfDepartingParkingAct == -1) {
      for (int i = 0; i < pe.size(); i++) {
        if (pe.get(i) instanceof ActivityImpl) {
          ActivityImpl parkingAct = (ActivityImpl) plan.getPlanElements().get(i);
          if (parkingAct.getType().equalsIgnoreCase("parking")) {
            indexOfDepartingParkingAct = i;
            break;
          }
        }
      }
    }

    if (indexOfDepartingParkingAct == -1) {
      throw new Error("plan wrong: no parking in the whole plan");
    }

    return indexOfDepartingParkingAct;
  }
예제 #4
0
  /**
   * reurns null, if no parking activity found else id of first parking facility
   *
   * @param plan
   * @return
   */
  public static Id<ActivityFacility> getFirstParkingFacilityId(Plan plan) {

    for (int i = 0; i < plan.getPlanElements().size(); i++) {
      if (plan.getPlanElements().get(i) instanceof ActivityImpl) {
        ActivityImpl activity = (ActivityImpl) plan.getPlanElements().get(i);

        if (activity.getType().equalsIgnoreCase("parking")) {
          return activity.getFacilityId();
        }
      }
    }

    return null;
  }
예제 #5
0
 @Override
 public void run(Person person) {
   Integer p_id = Integer.valueOf(person.getId().toString());
   Coord coord = persons.getPerson(p_id).getHousehold().getCoord();
   ActivityFacility f = this.homeFacQuadTree.get(coord.getX(), coord.getY());
   Plan plan = person.getSelectedPlan();
   for (PlanElement pe : plan.getPlanElements()) {
     if (pe instanceof ActivityImpl) {
       ActivityImpl act = (ActivityImpl) pe;
       if (H.equals(act.getType())) {
         act.setCoord(f.getCoord());
       }
     }
   }
 }
  /**
   * Helper method to complete a plan with *wh in a consistent way. Assuming that the first activity
   * is the home activity.
   *
   * @param plan
   * @param workCoord
   * @param jobLocation
   * @author nagel
   */
  public static void completePlanToHwh(
      PlanImpl plan, Coord workCoord, ActivityFacility jobLocation) {

    // complete the first activity (home) by setting end time.
    ActivityImpl act = (ActivityImpl) plan.getFirstActivity();
    act.setEndTime(7. * 3600.); // tnicolai: make configurable: see actType1.setOpeningTime(7*3600)
    // gather coordinate and facility id needed for last activity
    Coord homeCoord = act.getCoord();
    Id homeId = act.getFacilityId();

    // set Leg
    plan.createAndAddLeg(TransportMode.car);

    // set second activity (work)
    act = plan.createAndAddActivity(Constants.ACT_WORK, workCoord);
    act.setFacilityId(jobLocation.getId());
    act.setMaximumDuration(
        8. * 3600.); // tnicolai: make configurable: actType1.setTypicalDuration(8*60*60);

    // set Leg
    plan.createAndAddLeg(TransportMode.car);

    // set last activity (=first activity) and complete home-work-home plan.
    plan.createAndAddActivity(Constants.ACT_HOME, homeCoord);
    act = (ActivityImpl) plan.getLastActivity();
    act.setFacilityId(homeId);
  }
예제 #7
0
  /**
   * Get the ParkingTimeInfo of the parking related to the given activity
   *
   * @param activity
   * @return
   */
  public static ParkingTimeInfo getParkingTimeInfo(
      Plan plan, ActivityImpl activity, ParkingArrivalDepartureLog parkingArrivalDepartureLog) {
    ActivityImpl arrivalParkingAct = getArrivalParkingAct(plan, activity);
    ActivityImpl departureParkingAct = getDepartureParkingAct(plan, activity);

    int parkingArrivalIndex = getParkingArrivalIndex(plan, arrivalParkingAct);

    ParkingTimeInfo parkingTimeInfo =
        parkingArrivalDepartureLog.getParkingArrivalDepartureList().get(parkingArrivalIndex);

    if (arrivalParkingAct.getFacilityId() != parkingTimeInfo.getParkingFacilityId()) {
      throw new Error(
          "facility Ids inconsistent:"
              + arrivalParkingAct.getFacilityId()
              + "!="
              + parkingTimeInfo.getParkingFacilityId());
    }

    return parkingTimeInfo;
  }
예제 #8
0
  public ActivityFacilities filterFacilitiesWithPopulation(
      final ActivityFacilities origFacilities) {
    ActivityFacilities filteredFacilities = FacilitiesUtils.createActivityFacilities();

    for (Person person : filteredAgents.values()) {
      if (person.getSelectedPlan() != null) {
        for (PlanElement pe : person.getSelectedPlan().getPlanElements()) {
          if (pe instanceof ActivityImpl) {
            ActivityImpl act = (ActivityImpl) pe;
            if (act.getFacilityId() != null
                && !filteredFacilities.getFacilities().containsKey(act.getFacilityId())) {
              filteredFacilities.addActivityFacility(
                  origFacilities.getFacilities().get(act.getFacilityId()));
            }
          }
        }
      }
    }

    return filteredFacilities;
  }
예제 #9
0
  /**
   * TODO: add test. If the specified arrival is the i-th arrival of the day, return i (with i
   * starting at 0).
   *
   * @param plan
   * @param parkingArrivalAct
   * @return
   */
  public static int getParkingArrivalIndex(Plan plan, ActivityImpl parkingArrivalAct) {
    List<PlanElement> pe = plan.getPlanElements();
    int parkingPlanElementIndex = pe.indexOf(parkingArrivalAct);
    int index = -1;

    for (int i = 0; i <= parkingPlanElementIndex; i++) {
      if (pe.get(i) instanceof ActivityImpl) {
        ActivityImpl activity = (ActivityImpl) plan.getPlanElements().get(i);

        if (activity.getType().equalsIgnoreCase("parking")) {
          Leg leg = (Leg) plan.getPlanElements().get(i - 1);

          if (leg.getMode().equalsIgnoreCase("car")) {
            index++;
          }
        }
      }
    }

    return index;
  }
예제 #10
0
  public static int getArrivalParkingActIndex(Plan plan, ActivityImpl activity) {
    List<PlanElement> pe = plan.getPlanElements();
    int activityIndex = pe.indexOf(activity);
    int indexOfArrivalParkingAct = -1;

    for (int i = activityIndex; 0 < i; i--) {
      if (pe.get(i) instanceof ActivityImpl) {
        ActivityImpl parkingAct = (ActivityImpl) plan.getPlanElements().get(i);
        if (parkingAct.getType().equalsIgnoreCase("parking")) {
          indexOfArrivalParkingAct = i;
          break;
        }
      }
    }

    if (indexOfArrivalParkingAct == -1) {
      throw new Error("no parking arrival activity found - something is wrong with the plan");
    }

    return indexOfArrivalParkingAct;
  }
예제 #11
0
  /**
   * The home/first parking comes last (because it is the last parking arrival of the day).
   *
   * @param plan
   * @return
   */
  public static LinkedList<Id<ActivityFacility>> getAllParkingFacilityIds(Plan plan) {
    LinkedList<Id<ActivityFacility>> parkingFacilityIds = new LinkedList<>();

    // recognize parking arrival patterns (this means, there is car leg
    // after which there is
    // a parking activity).
    for (int i = 0; i < plan.getPlanElements().size(); i++) {
      if (plan.getPlanElements().get(i) instanceof ActivityImpl) {
        ActivityImpl activity = (ActivityImpl) plan.getPlanElements().get(i);

        if (activity.getType().equalsIgnoreCase("parking")) {
          Leg leg = (Leg) plan.getPlanElements().get(i - 1);

          if (leg.getMode().equalsIgnoreCase("car")) {
            parkingFacilityIds.add(activity.getFacilityId());
          }
        }
      }
    }

    return parkingFacilityIds;
  }
예제 #12
0
  /**
   * get the first activity after each arrival at a parking.
   *
   * @param plan
   * @return
   */
  public static LinkedList<ActivityImpl> getParkingTargetActivities(Plan plan) {
    LinkedList<ActivityImpl> list = new LinkedList<ActivityImpl>();

    for (int i = 0; i < plan.getPlanElements().size(); i++) {
      if (plan.getPlanElements().get(i) instanceof ActivityImpl) {
        ActivityImpl activity = (ActivityImpl) plan.getPlanElements().get(i);

        if (activity.getType().equalsIgnoreCase("parking")) {
          Leg leg = (Leg) plan.getPlanElements().get(i - 1);

          if (leg.getMode().equalsIgnoreCase("car")) {
            // parking arrival pattern recognized.

            ActivityImpl targetActivity = (ActivityImpl) plan.getPlanElements().get(i + 2);
            list.add(targetActivity);
          }
        }
      }
    }

    return list;
  }
예제 #13
0
  private static boolean checkActivityInArea(Geometry area, ActivityImpl activity) {

    boolean inArea = false;
    Coord coord = activity.getCoord();
    double x = coord.getX();
    double y = coord.getY();
    Coordinate coordinate = new Coordinate(x, y);
    GeometryFactory gf = new GeometryFactory();
    Point activityPoint = gf.createPoint(coordinate);
    Geometry envelope = area.getEnvelope();

    if (envelope.covers(activityPoint)) {
      if (area.covers(activityPoint)) {
        inArea = true;
      }
    }

    return inArea;
  }
예제 #14
0
  private Population getTestPopulation() {
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network network = scenario.getNetwork();
    new MatsimNetworkReader(scenario.getNetwork()).readFile("test/scenarios/equil/network.xml");

    Link link1 = network.getLinks().get(Id.create(1, Link.class));
    Link link20 = network.getLinks().get(Id.create(20, Link.class));

    Population population = scenario.getPopulation();

    Person person;
    PlanImpl plan;
    LegImpl leg;
    NetworkRoute route;

    person = PopulationUtils.createPerson(Id.create("1", Person.class));
    plan = PersonUtils.createAndAddPlan(person, true);
    ActivityImpl a = plan.createAndAddActivity("h", link1.getId());
    a.setEndTime(7.0 * 3600);
    leg = plan.createAndAddLeg(TransportMode.car);
    route = new LinkNetworkRouteImpl(link1.getId(), link20.getId());
    route.setLinkIds(link1.getId(), NetworkUtils.getLinkIds("6 15"), link20.getId());
    leg.setRoute(route);
    plan.createAndAddActivity("w", link20.getId());
    population.addPerson(person);

    person = PopulationUtils.createPerson(Id.create("2", Person.class));
    plan = PersonUtils.createAndAddPlan(person, true);
    ActivityImpl a2 = plan.createAndAddActivity("h", link1.getId());
    a2.setEndTime(7.0 * 3600 + 5.0 * 60);
    leg = plan.createAndAddLeg(TransportMode.car);
    route = new LinkNetworkRouteImpl(link1.getId(), link20.getId());
    route.setLinkIds(link1.getId(), NetworkUtils.getLinkIds("6 15"), link20.getId());
    leg.setRoute(route);
    plan.createAndAddActivity("w", link20.getId());
    population.addPerson(person);

    person = PopulationUtils.createPerson(Id.create("3", Person.class));
    plan = PersonUtils.createAndAddPlan(person, true);
    ActivityImpl a3 = plan.createAndAddActivity("h", link1.getId());
    a3.setEndTime(7.0 * 3600 + 10.0 * 60);
    leg = plan.createAndAddLeg(TransportMode.car);
    route = new LinkNetworkRouteImpl(link1.getId(), link20.getId());
    route.setLinkIds(link1.getId(), NetworkUtils.getLinkIds("5 14"), link20.getId());
    leg.setRoute(route);
    plan.createAndAddActivity("w", link20.getId());
    population.addPerson(person);

    return population;
  }
예제 #15
0
    @Override
    public List<int[]> call() throws Exception {

      /* Set up arrays to hold data for this plan */
      int[] hourArray = new int[24];
      int[] activityArray = new int[72];
      int[] areaArray = new int[9];
      int[] hourArray1 = new int[24];
      int[] activityArray1 = new int[72];
      int[] hourArray2 = new int[24];
      int[] activityArray2 = new int[72];
      int[] hourArray3 = new int[24];
      int[] activityArray3 = new int[72];
      int[] hourArray4 = new int[24];
      int[] activityArray4 = new int[72];
      int[] hourArray5 = new int[24];
      int[] activityArray5 = new int[72];
      int[] hourArray6 = new int[24];
      int[] activityArray6 = new int[72];
      int[] hourArray7 = new int[24];
      int[] activityArray7 = new int[72];
      int[] hourArray8 = new int[24];
      int[] activityArray8 = new int[72];
      int[] hourArray9 = new int[24];
      int[] activityArray9 = new int[72];
      Arrays.fill(areaArray, 0);
      Arrays.fill(hourArray, 0);
      Arrays.fill(activityArray, 0);
      Arrays.fill(activityArray1, 0);
      Arrays.fill(hourArray1, 0);
      Arrays.fill(hourArray2, 0);
      Arrays.fill(activityArray2, 0);
      Arrays.fill(hourArray3, 0);
      Arrays.fill(activityArray3, 0);
      Arrays.fill(hourArray4, 0);
      Arrays.fill(activityArray4, 0);
      Arrays.fill(hourArray5, 0);
      Arrays.fill(activityArray5, 0);
      Arrays.fill(hourArray6, 0);
      Arrays.fill(activityArray6, 0);
      Arrays.fill(hourArray7, 0);
      Arrays.fill(activityArray7, 0);
      Arrays.fill(hourArray8, 0);
      Arrays.fill(activityArray8, 0);
      Arrays.fill(hourArray9, 0);
      Arrays.fill(activityArray9, 0);

      /* Get the hour in which the chain starts */
      int startHour = 24;
      List<PlanElement> planElements = plan.getPlanElements();
      PlanElement firstMajor = planElements.get(0);
      if (firstMajor instanceof Activity) {
        ActivityImpl activity = (ActivityImpl) firstMajor;
        double endTime = activity.getEndTime();
        if (endTime >= 0) {
          startHour = convertSecondsToHourOfDay(endTime);
          incrementArray(startHour, hourArray);
        } else {
          LOG.info("Chain start time is negative: " + endTime);
        }
      } else {
        LOG.info(
            "First plan element in plan is not an activity therefore"
                + " the chain start time cannot be captured!");
      }

      /* Get the number of minor activities */
      int numberPlanElements = plan.getPlanElements().size();
      int numberMinorActivities = (int) ((numberPlanElements - 1) / 2.0 - 1);
      if (numberMinorActivities >= 0) {
        incrementArray(numberMinorActivities, activityArray);
      } else {
        LOG.info("numberMinorActivities less than 0: " + numberMinorActivities);
      }

      /* Get the areas in which this chain's activities are performed */
      boolean inSouthAfrica = false;
      boolean inGauteng = false;
      boolean inCapeTown = false;
      boolean inEthekwini = false;

      boolean[] a1 = new boolean[] {false, false, false, false};
      boolean[] a2 = new boolean[] {false, false, false, true};
      boolean[] a3 = new boolean[] {false, false, true, true};
      boolean[] a4 = new boolean[] {false, true, false, true};
      boolean[] a5 = new boolean[] {true, false, false, true};
      boolean[] a6 = new boolean[] {true, true, false, true};
      boolean[] a7 = new boolean[] {false, true, true, true};
      boolean[] a8 = new boolean[] {true, true, true, true};
      boolean[] a9 = new boolean[] {true, false, true, true};

      inSouthAfrica = checkPlanInArea(saGeometry, plan);
      if (inSouthAfrica) {
        inGauteng = checkPlanInArea(gautengGeometry, plan);
        inEthekwini = checkPlanInArea(eThekwiniGeometry, plan);
        inCapeTown = checkPlanInArea(ctGeometry, plan);
      }

      boolean[] booleanArray = new boolean[] {inGauteng, inCapeTown, inEthekwini, inSouthAfrica};
      if (Arrays.equals(booleanArray, a1)) {
        incrementArray(0, areaArray);
        incrementArray(startHour, hourArray1);
        incrementArray(numberMinorActivities, activityArray1);
      } else if (Arrays.equals(booleanArray, a2)) {
        incrementArray(1, areaArray);
        incrementArray(startHour, hourArray2);
        incrementArray(numberMinorActivities, activityArray2);
      } else if (Arrays.equals(booleanArray, a3)) {
        incrementArray(2, areaArray);
        incrementArray(startHour, hourArray3);
        incrementArray(numberMinorActivities, activityArray3);
      } else if (Arrays.equals(booleanArray, a4)) {
        incrementArray(3, areaArray);
        incrementArray(startHour, hourArray4);
        incrementArray(numberMinorActivities, activityArray4);
      } else if (Arrays.equals(booleanArray, a5)) {
        incrementArray(4, areaArray);
        incrementArray(startHour, hourArray5);
        incrementArray(numberMinorActivities, activityArray5);
      } else if (Arrays.equals(booleanArray, a6)) {
        incrementArray(5, areaArray);
        incrementArray(startHour, hourArray6);
        incrementArray(numberMinorActivities, activityArray6);
      } else if (Arrays.equals(booleanArray, a7)) {
        incrementArray(6, areaArray);
        incrementArray(startHour, hourArray7);
        incrementArray(numberMinorActivities, activityArray7);
      } else if (Arrays.equals(booleanArray, a8)) {
        incrementArray(7, areaArray);
        incrementArray(startHour, hourArray8);
        incrementArray(numberMinorActivities, activityArray8);
      } else if (Arrays.equals(booleanArray, a9)) {
        incrementArray(8, areaArray);
        incrementArray(startHour, hourArray9);
        incrementArray(numberMinorActivities, activityArray9);
      } else {
        LOG.info("booleanArray does not match any a1 to a9.");
      }

      List<int[]> infoList = new ArrayList<int[]>();
      infoList.add(areaArray);
      infoList.add(hourArray);
      infoList.add(activityArray);
      infoList.add(hourArray1);
      infoList.add(activityArray1);
      infoList.add(hourArray2);
      infoList.add(activityArray2);
      infoList.add(hourArray3);
      infoList.add(activityArray3);
      infoList.add(hourArray4);
      infoList.add(activityArray4);
      infoList.add(hourArray5);
      infoList.add(activityArray5);
      infoList.add(hourArray6);
      infoList.add(activityArray6);
      infoList.add(hourArray7);
      infoList.add(activityArray7);
      infoList.add(hourArray8);
      infoList.add(activityArray8);
      infoList.add(hourArray9);
      infoList.add(activityArray9);

      counter.incCounter();
      return infoList;
    }
 /**
  * Helper method to start a plan by inserting the home location. This is really only useful
  * together with "completePlanToHwh", which completes the plan, and benefits from the fact that
  * the Strings for the "home" and the "work" act are now concentrated here.
  *
  * @param plan
  * @param homeCoord
  * @param homeLocation
  * @author nagel
  */
 public static void makeHomePlan(PlanImpl plan, Coord homeCoord, ActivityFacility homeLocation) {
   ActivityImpl act = plan.createAndAddActivity(Constants.ACT_HOME, homeCoord);
   act.setFacilityId(
       homeLocation.getId()); // tnicolai: added facility id to compute zone2zone trips
 }
예제 #17
0
  /**
   * get parking related walking distance of whole day - average per leg
   *
   * @param plan
   * @param facilities
   * @return
   */
  public static double getParkingRelatedWalkingDistanceOfWholeDayAveragePerLeg(
      Plan plan, ActivityFacilities facilities) {
    double travelDistance = 0;
    int numberOfLegs = 0;

    List<PlanElement> pe = plan.getPlanElements();

    for (int i = 0; i < pe.size(); i++) {
      if (pe.get(i) instanceof ActivityImpl) {
        ActivityImpl parkingActivity = (ActivityImpl) pe.get(i);
        if (parkingActivity.getType().equalsIgnoreCase("parking")) {
          Coord coordParking =
              facilities.getFacilities().get(parkingActivity.getFacilityId()).getCoord();
          Leg nextLeg = (Leg) pe.get(i + 1);
          Leg prevLeg = (Leg) pe.get(i - 1);
          if (nextLeg.getMode().equalsIgnoreCase("walk")) {
            ActivityImpl nextAct = (ActivityImpl) pe.get(i + 2);

            if (nextAct.getFacilityId() != null) {
              Coord nextActFacilityCoord =
                  facilities.getFacilities().get(nextAct.getFacilityId()).getCoord();
              travelDistance += GeneralLib.getDistance(coordParking, nextActFacilityCoord);
            } else {
              Coord nextActLinkCoord = nextAct.getCoord();
              travelDistance += GeneralLib.getDistance(coordParking, nextActLinkCoord);
            }
            numberOfLegs++;
          }
          if (prevLeg.getMode().equalsIgnoreCase("walk")) {
            ActivityImpl prevAct = (ActivityImpl) pe.get(i - 2);

            if (prevAct.getFacilityId() != null) {
              Coord prevActFacilityCoord =
                  facilities.getFacilities().get(prevAct.getFacilityId()).getCoord();
              travelDistance += GeneralLib.getDistance(coordParking, prevActFacilityCoord);
            } else {
              Coord prevActLinkCoord = prevAct.getCoord();
              travelDistance += GeneralLib.getDistance(coordParking, prevActLinkCoord);
            }
            numberOfLegs++;
          }
        }
      }
    }

    return travelDistance / numberOfLegs;
  }
예제 #18
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.");
  }
  // test overnight activities with first and last activity of the same type
  @Test
  public final void test0b() {

    PlanCalcScoreConfigGroup plansCalcScoreConfigGroup = new PlanCalcScoreConfigGroup();
    ActivityParams activityParams = new ActivityParams("overnightActivity");
    activityParams.setTypicalDuration(12 * 3600.);

    plansCalcScoreConfigGroup.addActivityParams(activityParams);
    plansCalcScoreConfigGroup.setEarlyDeparture_utils_hr(0.);
    plansCalcScoreConfigGroup.setLateArrival_utils_hr(0.);
    plansCalcScoreConfigGroup.setMarginalUtlOfWaiting_utils_hr(0.);
    plansCalcScoreConfigGroup.setPerforming_utils_hr(6.);

    ScenarioConfigGroup scenarioConfig = new ScenarioConfigGroup();

    CharyparNagelScoringParameters params =
        new CharyparNagelScoringParameters.Builder(
                plansCalcScoreConfigGroup,
                plansCalcScoreConfigGroup.getScoringParameters(null),
                scenarioConfig)
            .build();

    MarginalSumScoringFunction marginaSumScoringFunction = new MarginalSumScoringFunction(params);

    Id<Link> linkId = null;

    ActivityImpl activity1 = new ActivityImpl("overnightActivity", linkId);
    activity1.setEndTime(7 * 3600.);
    ActivityImpl activity2 = new ActivityImpl("overnightActivity", linkId);
    activity2.setStartTime(18 * 3600.);

    // test if zero delay results in zero activity delay disutility
    double delay1 = 0 * 3600.;
    double activityDelayDisutility1 =
        marginaSumScoringFunction.getOvernightActivityDelayDisutility(activity1, activity2, delay1);
    // 6 + 7 hours --> 65.763074952494600 utils
    // 6 + 7 hours --> 65.763074952494600 utils
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        0.,
        activityDelayDisutility1,
        MatsimTestUtils.EPSILON);

    // test if a delay results in the right activity delay disutility
    double delay2 = 1 * 3600.;
    double activityDelayDisutility2 =
        marginaSumScoringFunction.getOvernightActivityDelayDisutility(activity1, activity2, delay2);
    // 6 + 7 hours --> 65.763074952494600 utils
    // 7 + 7 hours --> 71.098848947562600 utils
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        5.335773995067980,
        activityDelayDisutility2,
        MatsimTestUtils.EPSILON);

    // repeat the previous test: test if a delay results in the right activity delay disutility
    double activityDelayDisutility2b =
        marginaSumScoringFunction.getOvernightActivityDelayDisutility(activity1, activity2, delay2);
    // 6 + 7 hours --> 65.763074952494600 utils
    // 7 + 7 hours --> 71.098848947562600 utils
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        5.335773995067980,
        activityDelayDisutility2b,
        MatsimTestUtils.EPSILON);
  }
    public Fixture() {
      firstLegStartTime = 7 * 3600;
      firstLegTravelTime = 30 * 60;
      thirdLegTravelTime = 30 * 60;
      secondLegStartTime = 10 * 3600;
      secondLegTravelTime = 15 * 60;
      thirdLegStartTime = 13 * 3600;
      fourthLegStartTime = 16 * 3600;
      fourthLegTravelTime = 15 * 60;
      // home act end 7am
      // work 7:30 to 10:00
      // work 10:15 to 13:00
      // work 13:30 to 16:00
      // home 15:15 to ...

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      ActivityImpl fifthActivity = this.plan.createAndAddActivity("h", link9.getId());
      fifthActivity.setStartTime(fourthLegStartTime + fourthLegTravelTime);
      this.scenario.getPopulation().addPerson(this.person);
    }
  // test normal activities
  @Test
  public final void test0a() {

    PlanCalcScoreConfigGroup plansCalcScoreConfigGroup = new PlanCalcScoreConfigGroup();
    ActivityParams activityParams = new ActivityParams("work");
    activityParams.setTypicalDuration(6 * 3600.);
    activityParams.setOpeningTime(7 * 3600.);
    activityParams.setClosingTime(18 * 3600.);

    plansCalcScoreConfigGroup.addActivityParams(activityParams);
    plansCalcScoreConfigGroup.setEarlyDeparture_utils_hr(0.);
    plansCalcScoreConfigGroup.setLateArrival_utils_hr(0.);
    plansCalcScoreConfigGroup.setMarginalUtlOfWaiting_utils_hr(0.);
    plansCalcScoreConfigGroup.setPerforming_utils_hr(6.);

    ScenarioConfigGroup scenarioConfig = new ScenarioConfigGroup();

    CharyparNagelScoringParameters params =
        new CharyparNagelScoringParameters.Builder(
                plansCalcScoreConfigGroup,
                plansCalcScoreConfigGroup.getScoringParameters(null),
                scenarioConfig)
            .build();

    MarginalSumScoringFunction marginaSumScoringFunction = new MarginalSumScoringFunction(params);

    Id<Link> linkId = null;

    // test if zero delay results in zero activity delay disutility
    ActivityImpl activity1 = new ActivityImpl("work", linkId);
    activity1.setStartTime(10 * 3600.);
    activity1.setEndTime(16 * 3600.);
    double delay1 = 0 * 3600.;
    double activityDelayDisutility1 =
        marginaSumScoringFunction.getNormalActivityDelayDisutility(activity1, delay1);
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        0.,
        activityDelayDisutility1,
        MatsimTestUtils.EPSILON);

    // test if a delay results in zero activity delay disutility if the agent would have arrived to
    // late at the activity location anyway
    ActivityImpl activity2 = new ActivityImpl("work", linkId);
    activity2.setStartTime(19 * 3600.);
    activity2.setEndTime(20 * 3600.);
    double delay2 = 0.5 * 3600.;
    double activityDelayDisutility2 =
        marginaSumScoringFunction.getNormalActivityDelayDisutility(activity2, delay2);
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        0.,
        activityDelayDisutility2,
        MatsimTestUtils.EPSILON);

    // test if a delay results in zero activity delay disutility if the agent would have arrived to
    // early at the activity location anyway
    ActivityImpl activity3 = new ActivityImpl("work", linkId);
    activity3.setStartTime(4 * 3600.);
    activity3.setEndTime(5 * 3600.);
    double delay3 = 0.5 * 3600.;
    double activityDelayDisutility3 =
        marginaSumScoringFunction.getNormalActivityDelayDisutility(activity3, delay3);
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        0.,
        activityDelayDisutility3,
        MatsimTestUtils.EPSILON);

    // test if a delay results in the right activity delay disutility if the agent would have had
    // more time to perform the activity
    ActivityImpl activity4 = new ActivityImpl("work", linkId);
    activity4.setStartTime(10 * 3600.);
    activity4.setEndTime(16 * 3600.);
    double delay4 = 1 * 3600.;
    double activityDelayDisutility4 =
        marginaSumScoringFunction.getNormalActivityDelayDisutility(activity4, delay4);
    // 6 hours --> 65.549424473781 utils
    // 5 hours --> 60 utils
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        5.549424473781310,
        activityDelayDisutility4,
        MatsimTestUtils.EPSILON);

    // repeat the previous test: test if a delay results in the right activity delay disutility if
    // the agent would have had more time to perform the activity
    double activityDelayDisutility4b =
        marginaSumScoringFunction.getNormalActivityDelayDisutility(activity4, delay4);
    // 6 hours --> 65.549424473781 utils
    // 5 hours --> 60 utils
    Assert.assertEquals(
        "Wrong disutility from starting an activity with a delay (arriving later at the activity location).",
        5.549424473781310,
        activityDelayDisutility4b,
        MatsimTestUtils.EPSILON);
  }