示例#1
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);
  }
  public FreeFloatingParkingPersonDriverAgentImpl(
      final Person person,
      final Plan plan,
      final Netsim simulation,
      final Scenario scenario,
      final MatsimServices controler,
      ParkingModuleWithFreeFloatingCarSharing parkingModule) {
    this.person = person;
    this.simulation = simulation;
    this.controler = controler;
    this.plan = plan;
    this.scenario = scenario;
    this.parkingModule = parkingModule;

    beelineFactor =
        ((PlansCalcRouteConfigGroup) scenario.getConfig().getModule("planscalcroute"))
            .getBeelineDistanceFactors()
            .get("walk");
    walkSpeed =
        (((PlansCalcRouteConfigGroup) controler.getConfig().getModule("planscalcroute"))
            .getTeleportedModeSpeeds()
            .get("walk"));

    List<? extends PlanElement> planElements = this.plan.getPlanElements();
    if (planElements.size() > 0) {
      this.currentPlanElementIndex = 0;
      Activity firstAct = (Activity) planElements.get(0);
      this.currentLinkId = firstAct.getLinkId();
      this.state = MobsimAgent.State.ACTIVITY;
      calculateAndSetDepartureTime(firstAct);
    }
    throw new RuntimeException(
        "Should this class still be in use?  I think there is a delegated version of this, isn't there?  "
            + "This one here causes additional refactoring work. kai, feb'16");
  }
  @Override
  public void handleAgentLeg(AgentWithParking aem) {
    Id personId = aem.getPerson().getId();

    boolean endOfLegReached = aem.endOfLegReached();

    if (endOfLegReached) {
      if (!parkingFound.contains(personId)) {
        parkingFound.add(personId);

        DebugLib.traceAgent(personId);

        Activity nextAct =
            (Activity)
                aem.getPerson()
                    .getSelectedPlan()
                    .getPlanElements()
                    .get(aem.getPlanElementIndex() + 3);

        Id parkingId =
            AgentWithParking.parkingManager.getFreePrivateParking(
                nextAct.getFacilityId(), nextAct.getType());

        if (isInvalidParking(aem, parkingId)) {
          parkingId =
              AgentWithParking.parkingManager.getClosestParkingFacilityNotOnLink(
                  nextAct.getCoord(), aem.getInvalidLinkForParking());
        }

        parkVehicleAndLogSearchTime(aem, personId, parkingId);
      }
    } else {
      super.handleAgentLeg(aem);
    }
  }
  private void assignDistanceBinsPerPerson(DesiredDurationPerson desiredDurationPerson) {

    Id personId = desiredDurationPerson.getPersonId();
    PlanImpl plan = (PlanImpl) this.plans.getPersons().get(personId).getSelectedPlan();

    List<? extends PlanElement> actslegs = plan.getPlanElements();
    for (int j = 0; j < actslegs.size(); j = j + 2) {
      final Activity act = (Activity) actslegs.get(j);

      if (act.getType().startsWith("leisure")) {
        final LegImpl leg = (LegImpl) actslegs.get(j + 1);

        if (leg.getMode().equals(this.mode)) {
          int randomDistance =
              (int)
                  Math.round(
                      this.distanceBins.getRandomDistance(
                          desiredDurationPerson.planContainsLeisurePriorToWork()));
          String newActType = act.getType() + "_" + randomDistance;
          act.setType(newActType);

          // minimum duration is 30 min! -> else division by zero while scoring
          plan.getPerson()
              .getDesires()
              .putActivityDuration(
                  newActType, Math.max(30 * 60, desiredDurationPerson.getDuration()));

          // for plot
          this.durationDistanceBins.addVal(desiredDurationPerson.getDuration(), randomDistance);
        }
      }
    }
  }
示例#5
0
  public void plans2Shape(Population population, String outputFile) {

    SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
    typeBuilder.setName("shape");
    typeBuilder.add("geometry", Point.class);
    typeBuilder.add("id", String.class);
    typeBuilder.add("actType", String.class);
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(typeBuilder.buildFeatureType());

    List<SimpleFeature> features = new ArrayList<SimpleFeature>();

    for (Person person : population.getPersons().values()) {

      for (PlanElement pe : person.getSelectedPlan().getPlanElements()) {

        if (pe instanceof Activity) {

          Activity act = (Activity) pe;
          Coord coord = act.getCoord();

          SimpleFeature feature =
              builder.buildFeature(
                  null,
                  new Object[] {
                    new GeometryFactory().createPoint(new Coordinate(coord.getX(), coord.getY())),
                    person.getId().toString(),
                    act.getType()
                  });
          features.add(feature);
        }
      }
    }

    ShapeFileWriter.writeGeometries(features, outputFile);
  }
  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");
  }
示例#7
0
 protected void handleAct(final double time) {
   Activity act = (Activity) this.plan.getPlanElements().get(this.index);
   if (this.index == 0) {
     this.firstActTime = time;
   } else if (this.index == this.lastActIndex) {
     String lastActType = act.getType();
     if (lastActType.equals(((Activity) this.plan.getPlanElements().get(0)).getType())) {
       // the first Act and the last Act have the same type
       this.score +=
           calcActScore(this.lastTime, this.firstActTime + 24 * 3600, act); // SCENARIO_DURATION
     } else {
       if (scoreActs) {
         log.warn(
             "The first and the last activity do not have the same type. The correctness of the scoring function can thus not be guaranteed.");
         // score first activity
         Activity firstAct = (Activity) this.plan.getPlanElements().get(0);
         this.score += calcActScore(0.0, this.firstActTime, firstAct);
         // score last activity
         this.score += calcActScore(this.lastTime, 24 * 3600, act); // SCENARIO_DURATION
       }
     }
   } else {
     this.score += calcActScore(this.lastTime, time, act);
   }
   this.index++;
 }
示例#8
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 void updateWalkTimeTmpVariables(
      String legMod,
      Id personId,
      Plan executedPlan,
      int planElementIndex,
      double valueA,
      double valueB) {

    if (isPlanElementDuringDay(personId, planElementIndex)) {
      if (legMod.equals(TransportMode.walk)) {

        Activity previousAct = (Activity) executedPlan.getPlanElements().get(planElementIndex - 1);
        Leg previousLeg = (Leg) executedPlan.getPlanElements().get(planElementIndex - 2);

        if (previousAct.getType().equalsIgnoreCase("parking")
            && previousLeg.getMode().equals(TransportMode.car)) {
          firstParkingWalkTmp.put(personId, valueA);
        }

        Activity nextAct = (Activity) executedPlan.getPlanElements().get(planElementIndex + 1);
        Leg nextLeg = (Leg) executedPlan.getPlanElements().get(planElementIndex + 2);

        if (nextAct.getType().equalsIgnoreCase("parking")
            && nextLeg.getMode().equals(TransportMode.car)) {
          secondParkingWalkTmp.put(personId, valueB);
        }
      }
    }
  }
 private void handleLastActivity(EventsToScore eventsToScore, Fixture f, Activity activity) {
   eventsToScore.handleEvent(
       new ActivityStartEvent(
           activity.getStartTime(),
           f.person.getId(),
           activity.getLinkId(),
           activity.getFacilityId(),
           activity.getType()));
 }
示例#11
0
  @Test
  public void testActivityAttributesIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final Plan plan = population.getFactory().createPlan();
    person.addPlan(plan);
    final Activity act = population.getFactory().createActivityFromCoord("speech", new Coord(0, 0));
    plan.addActivity(act);

    act.getAttributes().putAttribute("makes sense", false);
    act.getAttributes().putAttribute("length", 1895L);

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));
    final Activity readAct = (Activity) readPerson.getSelectedPlan().getPlanElements().get(0);

    Assert.assertEquals(
        "Unexpected boolean attribute in " + readAct.getAttributes(),
        act.getAttributes().getAttribute("makes sense"),
        readAct.getAttributes().getAttribute("makes sense"));

    Assert.assertEquals(
        "Unexpected Long attribute in " + readAct.getAttributes(),
        act.getAttributes().getAttribute("length"),
        readAct.getAttributes().getAttribute("length"));
  }
示例#12
0
  public static Set<Coord> getCoords(Population population) {
    Set<Coord> coords = new HashSet<Coord>();

    for (Person person : population.getPersons().values()) {
      Plan plan = person.getPlans().get(0);
      Activity act = (Activity) plan.getPlanElements().get(0);
      Coord c = act.getCoord();
      coords.add(c);
    }

    return coords;
  }
  @Override
  public void handleAgentLeg(AgentWithParking aem) {
    Activity nextAct =
        (Activity)
            aem.getPerson().getSelectedPlan().getPlanElements().get(aem.getPlanElementIndex() + 3);

    if (GeneralLib.getDistance(
            getCurrentLink(aem).getCoord(), network.getLinks().get(nextAct.getLinkId()).getCoord())
        < distanceToDestinationForStartingRandomSearch) {
      throughAwayRestOfRoute(aem);
    }
    super.handleAgentLeg(aem);
  }
 @Override
 public final void endActivityAndComputeNextState(final double now) {
   Activity act = (Activity) this.getPlanElements().get(this.currentPlanElementIndex);
   this.simulation
       .getEventsManager()
       .processEvent(
           new ActivityEndEvent(
               now,
               this.getPerson().getId(),
               act.getLinkId(),
               act.getFacilityId(),
               act.getType()));
   advancePlan(now);
 }
  private void initializeActivity(Activity act) {
    this.state = MobsimAgent.State.ACTIVITY;

    double now = this.getMobsim().getSimTimer().getTimeOfDay();
    this.simulation
        .getEventsManager()
        .processEvent(
            new ActivityStartEvent(
                now, this.getId(), this.currentLinkId, act.getFacilityId(), act.getType()));
    /* schedule a departure if either duration or endtime is set of the activity.
     * Otherwise, the agent will just stay at this activity for ever...
     */
    calculateAndSetDepartureTime(act);
  }
示例#16
0
  @Test
  public void testCoord3dIO() {
    final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig());

    final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump"));
    population.addPerson(person);

    final Plan plan = population.getFactory().createPlan();
    person.addPlan(plan);
    plan.addActivity(population.getFactory().createActivityFromCoord("speech", new Coord(0, 0)));
    plan.addActivity(
        population.getFactory().createActivityFromCoord("tweet", new Coord(0, 0, -100)));

    final String file = utils.getOutputDirectory() + "/population.xml";
    new PopulationWriter(population).writeV6(file);

    final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReader(readScenario).readFile(file);

    final Person readPerson =
        readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump"));
    final Activity readSpeach = (Activity) readPerson.getSelectedPlan().getPlanElements().get(0);
    final Activity readTweet = (Activity) readPerson.getSelectedPlan().getPlanElements().get(1);

    Assert.assertFalse(
        "did not expect Z value in " + readSpeach.getCoord(), readSpeach.getCoord().hasZ());

    Assert.assertTrue("did expect T value in " + readTweet.getCoord(), readTweet.getCoord().hasZ());

    Assert.assertEquals(
        "unexpected Z value in " + readTweet.getCoord(),
        -100,
        readTweet.getCoord().getZ(),
        MatsimTestUtils.EPSILON);
  }
示例#17
0
 private Activity firstActivity(final Person person, final String type) {
   final Plan plan = person.getSelectedPlan();
   if (plan == null) {
     return null;
   }
   for (PlanElement element : plan.getPlanElements()) {
     if (element instanceof Activity) {
       final Activity act = (Activity) element;
       if (act.getType() != null && act.getType().startsWith(type)) {
         return act;
       }
     }
   }
   return null;
 }
示例#18
0
  private void replaceDoubtfulLegsByOtherMode() {
    for (Person p : scenario.getPopulation().getPersons().values()) {
      for (Plan plan : p.getPlans()) {

        Leg lastleg = null;
        Activity lastActivity = null;
        boolean personb = random.nextBoolean();
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Activity) {
            if (lastActivity == null) {
              lastActivity = (Activity) pe;
            } else {
              Coord lastCoord;
              if (lastActivity.getCoord() != null) {
                lastCoord = lastActivity.getCoord();
              } else {
                Link lastLink = scenario.getNetwork().getLinks().get(lastActivity.getLinkId());
                lastCoord = lastLink.getCoord();
              }
              Coord currentCoord;
              if (((Activity) pe).getCoord() != null) {
                currentCoord = ((Activity) pe).getCoord();
              } else {
                currentCoord =
                    scenario.getNetwork().getLinks().get(((Activity) pe).getLinkId()).getCoord();
              }

              double distance = CoordUtils.calcDistance(lastCoord, currentCoord);

              if (distance > 3000 && lastleg.getMode().equals("walk")) {
                lastleg.setMode("pt");
              } else if (distance > 20000 && lastleg.getMode().equals("bike")) {
                lastleg.setMode("pt");
              } else if (distance < 2000 && (lastleg.getMode().equals("pt"))) {
                if (personb == true) lastleg.setMode("walk");
                else lastleg.setMode("bike");
              }

              lastActivity = (Activity) pe;
            }

          } else if (pe instanceof Leg) {
            lastleg = (Leg) pe;
          }
        }
      }
    }
  }
示例#19
0
  private List<Link> createActivityLinks() {

    List<Link> links = new LinkedList<Link>();

    for (Activity act : this.activityList) {
      if (act.getLinkId() != null && this.network != null) {
        links.add(this.network.getLinks().get(act.getLinkId()));
      }
    }

    if (links.size() == 0) {
      return null;
    } else {
      return links;
    }
  }
  @Override
  protected double[] getOpeningInterval(Activity act) {

    //  openInterval has two values
    // openInterval[0] will be the opening time
    // openInterval[1] will be the closing time
    double[] openInterval = new double[] {Time.UNDEFINED_TIME, Time.UNDEFINED_TIME};

    boolean foundAct = false;

    ActivityFacility facility = this.facilities.getFacilities().get(act.getFacilityId());
    Iterator<String> facilityActTypeIterator = facility.getActivityOptions().keySet().iterator();
    String facilityActType = null;
    Set<OpeningTime> opentimes = null;

    while (facilityActTypeIterator.hasNext() && !foundAct) {

      facilityActType = facilityActTypeIterator.next();
      if (act.getType().equals(facilityActType)) {
        foundAct = true;

        // choose appropriate opentime:
        // either wed or wkday
        // if none is given, use undefined opentimes
        opentimes = facility.getActivityOptions().get(facilityActType).getOpeningTimes();
        if (opentimes != null && opentimes.size() > 0) {
          // ignoring lunch breaks with the following procedure:
          // if there is only one wed/wkday open time interval, use it
          // if there are two or more, use the earliest start time and the latest end time
          openInterval[0] = Double.MAX_VALUE;
          openInterval[1] = Double.MIN_VALUE;

          for (OpeningTime opentime : opentimes) {

            openInterval[0] = Math.min(openInterval[0], opentime.getStartTime());
            openInterval[1] = Math.max(openInterval[1], opentime.getEndTime());
          }
        }
      }
    }

    if (!foundAct) {
      return new double[] {0, Double.MAX_VALUE};
    }

    return openInterval;
  }
示例#21
0
    @Override
    public void run(Person person) {

      Plan selectedPlan = person.getSelectedPlan();

      ArrayList<String> modeChain = new ArrayList<String>();
      for (PlanElement pe : selectedPlan.getPlanElements()) {
        if (pe instanceof Leg) {
          Leg leg = (Leg) pe;
          modeChain.add(leg.getMode());
        }
      }
      String[] candidate = new String[modeChain.size()];
      candidate = modeChain.toArray(candidate);

      MeisterkConfigGroup meisterkConfigGroup = new MeisterkConfigGroup();

      boolean isFeasible =
          PlanAnalyzeTourModeChoiceSet.isModeChainFeasible(
              selectedPlan,
              candidate,
              meisterkConfigGroup.getChainBasedModes(),
              PlanomatConfigGroup.TripStructureAnalysisLayerOption.facility,
              this.facilities,
              this.network);

      if (!isFeasible) {

        logger.info("Agent id: " + person.getId());

        for (PlanElement pe : selectedPlan.getPlanElements()) {

          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            logger.info("\t" + act.getFacilityId());
          }

          if (pe instanceof Leg) {
            Leg leg = (Leg) pe;
            modeChain.add(leg.getMode());
            logger.info("\t" + leg.getMode());
          }
        }
        this.numInfeasiblePlans++;
      }
    }
示例#22
0
  private String enrichPlanBySingleLegAndActivity(
      Coord lastActivityCoord, Plan plan, String oldmode, int maxDur, boolean canChangeMode) {
    String mode = oldmode;
    Coord nextDestination;
    String nextActivity;
    double duration;
    double r = random.nextDouble();
    if (r < 0.25) {
      nextActivity = "private";
      nextDestination = findClosestCoordFromMapRandomized(lastActivityCoord, residential, 20);
      duration = 600 + random.nextInt(maxDur);
    } else if (r < 0.5) {
      nextActivity = "leisure";
      nextDestination = findClosestCoordFromMapRandomized(lastActivityCoord, schools, 5);
      duration = 600 + random.nextInt(maxDur);

    } else {
      nextActivity = "shopping";
      nextDestination = findClosestCoordFromMapRandomized(lastActivityCoord, retail, 10);
      duration = 600 + random.nextInt(maxDur);
    }
    Activity next =
        scenario
            .getPopulation()
            .getFactory()
            .createActivityFromCoord(nextActivity, nextDestination);
    next.setMaximumDuration(duration);
    double distance = CoordUtils.calcDistance(nextDestination, lastActivityCoord);
    if (canChangeMode) {
      if (distance < 500) {
        mode = "walk";

      } else if (distance < 3000) {
        if (random.nextBoolean()) mode = "car";
        else if (random.nextBoolean()) mode = "bike";
        else mode = "pt";
      } else {
        if (random.nextBoolean()) mode = "car";
        else mode = "pt";
      }
    }
    plan.addLeg(scenario.getPopulation().getFactory().createLeg(mode));
    plan.addActivity(next);
    return mode;
  }
示例#23
0
  protected double[] getOpeningInterval(final Activity act) {

    ActivityUtilityParameters params = utilParams.get(act.getType());
    if (params == null) {
      throw new IllegalArgumentException(
          "acttype \"" + act.getType() + "\" is not known in utility parameters.");
    }

    double openingTime = params.getOpeningTime();
    double closingTime = params.getClosingTime();

    //  openInterval has two values
    // openInterval[0] will be the opening time
    // openInterval[1] will be the closing time
    double[] openInterval = new double[] {openingTime, closingTime};

    return openInterval;
  }
  private boolean judgeByBeeline(final Activity fromAct, final Activity toAct) {
    if (this.aoiCenter == null) {
      // we cannot use the bee-line decision if we don't know the alternative aoi-center
      return false;
    }
    Coord fromCoord = fromAct.getCoord();
    Coord toCoord = toAct.getCoord();

    if (fromCoord == null) {
      fromCoord = this.network.getLinks().get(fromAct.getLinkId()).getCoord();
    }
    if (toCoord == null) {
      toCoord = this.network.getLinks().get(toAct.getLinkId()).getCoord();
    }

    return (CoordUtils.distancePointLinesegment(fromCoord, toCoord, this.aoiCenter)
        <= this.aoiRadius);
  }
  /**
   * 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);
  }
示例#26
0
  /** @param args */
  public static void main(String[] args) {
    Header.printHeader(checkShoppingTypes.class.toString(), args);

    Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    MatsimReader pr = new PopulationReader(sc);
    pr.readFile(args[0]);

    int s1 = 0;
    int s2 = 0;
    int s3 = 0;
    int s4 = 0;
    int s5 = 0;

    for (Id id : sc.getPopulation().getPersons().keySet()) {
      Plan plan = sc.getPopulation().getPersons().get(id).getSelectedPlan();
      for (PlanElement pe : plan.getPlanElements()) {
        if (pe instanceof Activity) {
          Activity act = (Activity) pe;
          String s = act.getType();
          if (s.equalsIgnoreCase("s1")) {
            s1++;
          } else if (s.equalsIgnoreCase("s2")) {
            s2++;
          } else if (s.equalsIgnoreCase("s3")) {
            s3++;
          } else if (s.equalsIgnoreCase("s4")) {
            s4++;
          } else if (s.equalsIgnoreCase("s5")) {
            s5++;
          }
        }
      }
    }

    LOG.info("  s1: " + s1);
    LOG.info("  s2: " + s2);
    LOG.info("  s3: " + s3);
    LOG.info("  s4: " + s4);
    LOG.info("  s5: " + s5);

    Header.printFooter();
  }
示例#27
0
  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);
  }
  public double getDestinationScore(
      Activity act, double fVar, int activityIndex, Id<Person> personId) {
    double score = 0.0;
    if (this.scaleEpsilon.isFlexibleType(act.getType())) {
      /*
       * The following will not work if activities are inserted or removed during replanning (e.g. ptInteractionActivities).  kai/mz, oct'14
       */
      int actIndex =
          2
              * activityIndex; // "2": retrofitting; this used to be the PlanElementIndex.  One
                               // could probably remove the "2",
      // but then the test fail because this is equivalent to a different random seed.  So more
      // diligent checking would be needed.

      if (fVar < 0.0) fVar = this.scaleEpsilon.getEpsilonFactor(act.getType());
      score += (fVar * this.getEpsilonAlternative(act.getFacilityId(), personId, actIndex));
      score += this.getAttributesScore(act.getFacilityId(), personId);
    }
    return score;
  }
  private ActivityFacility getOrigin(Person p) {
    final Activity act = (Activity) p.getSelectedPlan().getPlanElements().get(0);
    final Id<ActivityFacility> facilityId = act.getFacilityId();
    return facilityId != null
        ? allFacilities.getFacilities().get(act.getFacilityId())
        : new ActivityFacility() {
          @Override
          public Map<String, ActivityOption> getActivityOptions() {
            throw new UnsupportedOperationException(
                "This is a dummy facility, only link and coord are available.");
          }

          @Override
          public void addActivityOption(ActivityOption option) {
            throw new UnsupportedOperationException(
                "This is a dummy facility, only link and coord are available.");
          }

          @Override
          public Id<Link> getLinkId() {
            return act.getLinkId();
          }

          @Override
          public Coord getCoord() {
            return act.getCoord();
          }

          @Override
          public Map<String, Object> getCustomAttributes() {
            throw new UnsupportedOperationException(
                "This is a dummy facility, only link and coord are available.");
          }

          @Override
          public Id<ActivityFacility> getId() {
            throw new UnsupportedOperationException(
                "This is a dummy facility, only link and coord are available.");
          }
        };
  }
  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;
  }