private static void startLeg(final Leg leg, final BufferedWriter out) throws IOException {
    out.write("\t\t\t<leg mode=\"");
    out.write(leg.getMode());
    out.write("\"");
    if (leg.getDepartureTime() != Time.UNDEFINED_TIME) {
      out.write(" dep_time=\"");
      out.write(Time.writeTime(leg.getDepartureTime()));
      out.write("\"");
    }
    if (leg.getTravelTime() != Time.UNDEFINED_TIME) {
      out.write(" trav_time=\"");
      out.write(Time.writeTime(leg.getTravelTime()));
      out.write("\"");
    }
    //		if (leg instanceof LegImpl) {
    //			LegImpl l = (LegImpl)leg;
    //			if (l.getDepartureTime() + l.getTravelTime() != Time.UNDEFINED_TIME) {
    //				out.write(" arr_time=\"");
    //				out.write(Time.writeTime(l.getDepartureTime() + l.getTravelTime()));
    //				out.write("\"");
    //			}
    //		}
    // arrival time is in dtd, but no longer evaluated in code (according to not being in API).
    // kai, jun'16

    out.write(">\n");
  }
  private void initializeOneWayCarsharingCarLeg(Link l, double now) {
    this.state = MobsimAgent.State.LEG;

    PlanElement pe = this.getCurrentPlanElement();

    Leg leg = (Leg) pe;
    Network network = scenario.getNetwork();
    endStationOW =
        findClosestAvailableParkingSpace(network.getLinks().get(leg.getRoute().getEndLinkId()));

    if (endStationOW == null) {

      this.state = MobsimAgent.State.ABORT;
      this.simulation
          .getEventsManager()
          .processEvent(new NoParkingSpaceEvent(now, leg.getRoute().getEndLinkId(), "ow"));

      return;
    } else {
      startStationOW.freeParkingSpot();
      endStationOW.reserveParkingSpot();

      Link destinationLink = endStationOW.getLink();
      // create route for the car part of the onewaycarsharing trip
      initializeCSVehicleLeg("onewaycarsharing", now, l, destinationLink);
    }
  }
 @Override
 public void writePerson(final Person person, final BufferedWriter out) throws IOException {
   PopulationWriterHandlerImplV5.startPerson(person, out);
   for (Plan plan : person.getPlans()) {
     PopulationWriterHandlerImplV5.startPlan(plan, out);
     // act/leg
     for (PlanElement pe : plan.getPlanElements()) {
       if (pe instanceof Activity) {
         Activity act = (Activity) pe;
         this.writeAct(act, out);
       } else if (pe instanceof Leg) {
         Leg leg = (Leg) pe;
         PopulationWriterHandlerImplV5.startLeg(leg, out);
         // route
         Route route = leg.getRoute();
         if (route != null) {
           PopulationWriterHandlerImplV5.startRoute(route, out);
           PopulationWriterHandlerImplV5.endRoute(out);
         }
         PopulationWriterHandlerImplV5.endLeg(out);
       }
     }
     PopulationWriterHandlerImplV5.endPlan(out);
   }
   PopulationWriterHandlerImplV5.endPerson(out);
   this.writeSeparator(out);
   out.flush();
 }
  private void writeFile(List<Leg> legs, String outFile) {
    FileOutputStream fos = null;
    OutputStreamWriter osw = null;
    BufferedWriter bw = null;

    try {
      fos = new FileOutputStream(outFile);
      osw = new OutputStreamWriter(fos, charset);
      bw = new BufferedWriter(osw);

      // write Header
      bw.write("depaturetime" + delimiter + "arrivaltime" + "\n");

      // write Values
      for (Leg leg : legs) {
        bw.write(String.valueOf(leg.getDepartureTime()));
        bw.write(delimiter);
        bw.write(String.valueOf(leg.getDepartureTime() + leg.getTravelTime()));
        bw.write("\n");
      }

      bw.close();
      osw.close();
      fos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  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);
        }
      }
    }
  }
예제 #6
0
  public void startLeg(Leg leg) {
    this.leg = leg;
    routeIndex = 0;

    if (leg.getRoute() instanceof NetworkRoute) {
      route = (NetworkRoute) leg.getRoute();
    }
  }
 @Override
 public final void handleLeg(Leg leg) {
   if (legScoringFunctions.containsKey(leg.getMode())) {
     legScoringFunctions.get(leg.getMode()).handleLeg(leg);
   } else {
     legScoringFunctions.get(TransportMode.other).handleLeg(leg);
   }
 }
 @Test
 public void testUnusualMode() {
   Fixture f = new Fixture();
   Leg leg = (Leg) f.plan.getPlanElements().get(1);
   leg.setMode("sackhuepfen");
   assertEquals(-3.0, calcScore(f), EPSILON); // default for unknown modes
   f.config.planCalcScore().addParam("traveling_sackhuepfen", "-30.0");
   assertEquals(-15.0, calcScore(f), EPSILON);
 }
  @Test
  public final void testSelectPlan() {
    Scenario sc = this.loadAndPrepareScenario();
    Set<String> mainModes = new HashSet<String>();
    mainModes.add("pt");
    mainModes.add("train");

    // Two plans with exactly same structure but a big difference in the scores
    PathSizeLogitSelector psls = new PathSizeLogitSelector(1, 2, mainModes);
    Plan plan =
        psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("555555", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    Assert.assertEquals(10.0, plan.getScore(), MatsimTestUtils.EPSILON);

    // Two plans with exactly same structure no difference in the scores
    psls = new PathSizeLogitSelector(50, 2, mainModes);
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("666666", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan); // can't test more both are exactly equal

    // Two exactly equal plans (structure + score) with a third pt plan that is not similar and
    // worse
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("777777", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    Leg leg = (Leg) plan.getPlanElements().get(3);
    Assert.assertEquals(
        "PT1===TXL===TXL_MUC_SBA===TXL_MUC_SBA23===MUC",
        ((GenericRoute) leg.getRoute()).getRouteDescription());

    // Two equal pt plans and one train plan
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("888888", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    leg = (Leg) plan.getPlanElements().get(3);
    Assert.assertEquals(
        "PT1===TXL===TXL_MUC_SBA===TXL_MUC_SBA23===MUC",
        ((GenericRoute) leg.getRoute()).getRouteDescription());

    // Two equal train plans and one pt plan with less score
    psls = new PathSizeLogitSelector(20, 2, mainModes);
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("999999", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    leg = (Leg) plan.getPlanElements().get(1);
    Assert.assertEquals("train", leg.getMode());

    // Same as last test but with lest ps logit beta
    psls = new PathSizeLogitSelector(10, 2, mainModes);
    plan = psls.selectPlan(sc.getPopulation().getPersons().get(Id.create("999999", Person.class)));
    System.out.println(plan);
    Assert.assertNotNull(plan);
    leg = (Leg) plan.getPlanElements().get(1);
    Assert.assertEquals("transit_walk", leg.getMode());
  }
 private static void unregisterPassengerFromDriverRoutes(final JointTrip toRemove) {
   for (Leg driverLeg : toRemove.getDriverLegs()) {
     final DriverRoute route = (DriverRoute) driverLeg.getRoute();
     route.removePassenger(toRemove.getPassengerId());
     if (route.getPassengersIds().isEmpty()) {
       driverLeg.setMode(TransportMode.car);
       driverLeg.setRoute(null);
     }
   }
 }
예제 #11
0
 double getPlanDistance(PlanImpl plan) {
   double distance = 0;
   for (PlanElement element : plan.getPlanElements()) {
     if (element.getClass() == LegImpl.class) {
       Leg leg = (Leg) element;
       distance += leg.getRoute().getDistance();
     }
   }
   return distance;
 }
  private void initializeTwoWayCarsharingEndWalkLeg(Leg leg, double now) {

    this.state = MobsimAgent.State.LEG;
    Route route = leg.getRoute();

    Link link = mapTW.get(scenario.getNetwork().getLinks().get(leg.getRoute().getEndLinkId()));
    mapTW.remove(scenario.getNetwork().getLinks().get(leg.getRoute().getEndLinkId()));
    initializeCSWalkLeg(
        "walk_rb", now, link, scenario.getNetwork().getLinks().get(route.getEndLinkId()));
  }
  private void initializeTwoWayCarsharingEndCarLeg(Link l, double now) {
    this.state = MobsimAgent.State.LEG;

    PlanElement pe = this.getCurrentPlanElement();

    Leg leg = (Leg) pe;
    Network network = scenario.getNetwork();
    Link link = mapTW.get(network.getLinks().get(leg.getRoute().getEndLinkId()));

    // create route for the car part of the twowaycarsharing trip
    initializeCSVehicleLeg(
        "twowaycarsharing", now, network.getLinks().get(leg.getRoute().getStartLinkId()), link);
  }
  private void initializeFreeFLoatingCarLeg(Link l, double now) {
    this.state = MobsimAgent.State.LEG;

    PlanElement pe = this.getCurrentPlanElement();

    Leg leg = (Leg) pe;

    // create route for the car part of the freefloating trip
    initializeCSVehicleLeg(
        "freefloating",
        now,
        l,
        scenario.getNetwork().getLinks().get(leg.getRoute().getEndLinkId()));
  }
예제 #15
0
 private void replaceSptByPtp() {
   for (Id<Person> pid : this.teleportPtUsers) {
     Person p = scenario.getPopulation().getPersons().get(pid);
     for (Plan plan : p.getPlans()) {
       for (PlanElement pe : plan.getPlanElements()) {
         if (pe instanceof Leg) {
           Leg leg = (Leg) pe;
           if (leg.getMode().equals("pt")) {
             leg.setMode("tpt");
           }
         }
       }
     }
   }
 }
예제 #16
0
 @SuppressWarnings("deprecation")
 private void computeTravelStatistics(final Person person) {
   this.totalDist = 0.0;
   this.totalTime = 0.0;
   final Plan plan = person.getSelectedPlan();
   if (plan == null) {
     return;
   }
   for (PlanElement element : plan.getPlanElements()) {
     if (element instanceof Leg) {
       final Leg leg = (Leg) element;
       this.totalTime += leg.getTravelTime();
       this.totalDist += leg.getRoute().getDistance();
     }
   }
 }
  @Override
  public final void endLegAndComputeNextState(final double now) {
    this.simulation
        .getEventsManager()
        .processEvent(
            new PersonArrivalEvent(
                now, this.getPerson().getId(), this.getDestinationLinkId(), currentLeg.getMode()));

    if ((!(this.currentLinkId == null && this.cachedDestinationLinkId == null)))
      if (!this.currentLinkId.equals(this.cachedDestinationLinkId)) {
        log.error(
            "The agent "
                + this.getPerson().getId()
                + " has destination link "
                + this.cachedDestinationLinkId
                + ", but arrived on link "
                + this.currentLinkId
                + ". Removing the agent from the simulation.");
        this.state = MobsimAgent.State.ABORT;
      } else {

        if (this.getVehicle() != null
            && (this.getVehicle().getId().toString().startsWith("TW")
                || this.getVehicle().getId().toString().startsWith("OW")
                || this.getVehicle().getId().toString().startsWith("FF")))
          parkCSVehicle(this.currentLeg, this.plan);

        advancePlan(now);
      }
  }
  @Override
  public final void endLegAndComputeNextState(final double now) {
    this.simulation
        .getEventsManager()
        .processEvent(
            new PersonArrivalEvent(
                now, this.getPerson().getId(), this.getDestinationLinkId(), currentLeg.getMode()));

    if ((!(this.currentLinkId == null && this.cachedDestinationLinkId == null))
        && !this.currentLinkId.equals(this.cachedDestinationLinkId)) {
      log.error(
          "The agent "
              + this.getPerson().getId()
              + " has destination link "
              + this.cachedDestinationLinkId
              + ", but arrived on link "
              + this.currentLinkId
              + ". Removing the agent from the simulation.");
      this.state = MobsimAgent.State.ABORT;
    } else {
      // note that when we are here we don't know if next is another leg, or an activity  Therefore,
      // we go to a general method:

      advancePlan(now);
    }
  }
  private void initializeLeg(Leg leg) {
    this.state = MobsimAgent.State.LEG;
    Route route = leg.getRoute();
    if (route == null) {
      log.error(
          "The agent "
              + this.getPerson().getId()
              + " has no route in its leg.  Setting agent state to ABORT "
              + "(but continuing the mobsim).");
      if (noRouteWrnCnt < 1) {
        log.info(
            "(Route is needed inside Leg even if you want teleportation since Route carries the start/endLinkId info.)");
        noRouteWrnCnt++;
      }
      this.state = MobsimAgent.State.ABORT;
      return;
    } else {
      this.cachedDestinationLinkId = route.getEndLinkId();

      this.currentLeg = leg;
      this.cachedRouteLinkIds = null;
      this.currentLinkIdIndex = 0;
      this.cachedNextLinkId = null;
      return;
    }
  }
예제 #20
0
  @Override
  public void endLegAndComputeNextState(double now) {
    // Post this event here.

    events.processEvent(new PersonArrivalEvent(now, id, currentLinkId, leg.getMode()));
    super.endLegAndComputeNextState(now);
  }
  private void initializeOneWayCarsharingStartWalkLeg(Leg leg, double now) {

    this.state = MobsimAgent.State.LEG;
    Route route = leg.getRoute();
    OneWayCarsharingRDWithParkingStation station =
        findClosestAvailableOWCar(route.getStartLinkId());

    if (station == null) {
      this.state = MobsimAgent.State.ABORT;
      this.simulation
          .getEventsManager()
          .processEvent(new NoVehicleCarSharingEvent(now, route.getStartLinkId(), "ow"));

      return;
    }
    startStationOW = station;
    owVehId = station.getIDs().get(0);
    this.carSharingVehicles.getOneWayVehicles().removeVehicle(station, owVehId);

    initializeCSWalkLeg(
        "walk_ow_sb",
        now,
        scenario.getNetwork().getLinks().get(route.getStartLinkId()),
        startStationOW.getLink());
  }
  private void initializeFreeFloatingEndWalkLeg(Leg leg, double now) {

    this.state = MobsimAgent.State.LEG;
    this.parkingModule.makeFFVehicleAvailable(
        Id.create((vehID), Vehicle.class), parkingSpot.getParking());
    Route route = leg.getRoute();

    double distance = 0.0; // this will be acquired from the parking module

    LegImpl walkLeg = new LegImpl("walk_ff");

    vehID = null;
    GenericRouteImpl walkRoute = new GenericRouteImpl(route.getEndLinkId(), route.getEndLinkId());

    // for the purposes of consistency setting walking time to 0
    final int travTime = 0;
    walkRoute.setTravelTime(travTime);
    walkRoute.setDistance(distance);

    walkLeg.setRoute(walkRoute);
    this.cachedDestinationLinkId = route.getEndLinkId();
    walkLeg.setDepartureTime(now);
    walkLeg.setTravelTime(travTime);
    walkLeg.setArrivalTime(now + travTime);
    // set the route according to the next leg
    this.currentLeg = walkLeg;
    this.cachedRouteLinkIds = null;
    this.currentLinkIdIndex = 0;
    this.cachedNextLinkId = null;

    return;
  }
 @Override
 public boolean judge(final Person person) {
   for (Plan plan : person.getPlans()) {
     for (int i = 1, n = plan.getPlanElements().size(); i < n; i += 2) {
       Leg leg = (Leg) plan.getPlanElements().get(i);
       if (leg.getRoute() == null) {
         if (judgeByBeeline(
             (Activity) plan.getPlanElements().get(i - 1),
             (Activity) plan.getPlanElements().get(i + 1))) {
           return true;
         }
       } else if (leg.getRoute() instanceof NetworkRoute) {
         List<Id<Link>> linkIds = ((NetworkRoute) leg.getRoute()).getLinkIds();
         if (linkIds.size() == 0) {
           if (judgeByBeeline(
               (Activity) plan.getPlanElements().get(i - 1),
               (Activity) plan.getPlanElements().get(i + 1))) {
             return true;
           }
         } else {
           for (Id<Link> link : linkIds) {
             if (this.areaOfInterest.containsKey(link)) {
               return true;
             }
           }
           // test departure link
           Id<Link> linkId = ((Activity) plan.getPlanElements().get(i - 1)).getLinkId();
           if ((linkId != null) && (this.areaOfInterest.containsKey(linkId))) {
             return true;
           }
           // test arrival link
           linkId = ((Activity) plan.getPlanElements().get(i + 1)).getLinkId();
           if ((linkId != null) && (this.areaOfInterest.containsKey(linkId))) {
             return true;
           }
         }
       } else { // leg.getRoute() instanceof GenericRoute
         if (judgeByBeeline(
             (Activity) plan.getPlanElements().get(i - 1),
             (Activity) plan.getPlanElements().get(i + 1))) {
           return true;
         }
       }
     }
   }
   return false;
 }
예제 #24
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;
  }
  @Override
  public void run(Plan plan) {

    List<Trip> t = TripStructureUtils.getTrips(plan, stageActivityTypes);
    boolean ffcard = false;
    boolean owcard = false;
    int cnt = t.size();
    Person p = plan.getPerson();
    if (cnt == 0) {
      return;
    }
    int rndIdx = this.rng.nextInt(cnt);

    for (Leg l : t.get(rndIdx).getLegsOnly())
      if (l.getMode().equals("car")
          || l.getMode().equals("bike")
          || l.getMode().equals("twowaycarsharing")) return;

    if (Boolean.parseBoolean(
        ((String)
            this.scenario
                .getPopulation()
                .getPersonAttributes()
                .getAttribute(plan.getPerson().getId().toString(), "FF_CARD")))) ffcard = true;
    if (Boolean.parseBoolean(
        ((String)
            this.scenario
                .getPopulation()
                .getPersonAttributes()
                .getAttribute(plan.getPerson().getId().toString(), "OW_CARD")))) owcard = true;
    double centerX = 683217.0;
    double centerY = 247300.0;
    Coord coord = new Coord(centerX, centerY);
    if (CoordUtils.calcDistance(t.get(rndIdx).getOriginActivity().getCoord(), coord) < 10500
        && CoordUtils.calcDistance(t.get(rndIdx).getDestinationActivity().getCoord(), coord)
            < 10500) {
      // don't change the trips between the same links
      if (!t.get(rndIdx)
          .getOriginActivity()
          .getLinkId()
          .toString()
          .equals(t.get(rndIdx).getDestinationActivity().getLinkId().toString()))
        setRandomTripMode(t.get(rndIdx), plan, ffcard, owcard);
      else return;
    } else return;
  }
예제 #26
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++;
      }
    }
  private void repareDriverTrips(final JointTrip toRemove, final JointPlan plan) {
    final List<TripStructureUtils.Trip> subtrips =
        getDriverTrip(toRemove, plan.getIndividualPlan(toRemove.getDriverId()));
    final List<PlanElement> newTrip = new ArrayList<PlanElement>();
    newTrip.add(PopulationUtils.createLeg(TransportMode.car));

    // "state" variables, changed in the loop:
    // - keeps track of the passengers currently in the vehicle.
    //   Pick-up or drop-offs are created at each change
    Set<Id> currentPassengers = Collections.<Id>emptySet();
    for (TripStructureUtils.Trip subtrip : subtrips) {
      final Leg leg = getDriverLegIfItIs(subtrip);
      final Route route = leg == null ? null : leg.getRoute();

      final Set<Id> newPassengers =
          route != null
              ? new HashSet<Id>(((DriverRoute) route).getPassengersIds())
              : Collections.<Id>emptySet();
      // note that no check of the mode is done...
      if (!newPassengers.equals(currentPassengers)) {
        newTrip.add(
            PopulationUtils.createActivityFromLinkId(
                JointActingTypes.INTERACTION,
                route != null ? route.getStartLinkId() : subtrip.getOriginActivity().getLinkId()));

        // as the spatial structure of the trip is modified, it is possible
        // that some pre-existing subtours are removed. Thus, a driver that may
        // have walked to a pick up (because at the same location as its departure)
        // may then have to drive to pick up the second passenger directly if
        // the first passenger was removed. Setting all non-driver legs
        // to car ensures to have a consistent mode chain.
        // XXX It could be done in a smarter way, so that if no subtour is removed, no modification
        // is done
        // For instance, when removing an "intern" trip, first PU and last DO are
        // left untouched, and thus access and egress leg need not be touched.
        newTrip.add(leg != null ? leg : PopulationUtils.createLeg(TransportMode.car));
        currentPassengers = newPassengers;
      }
    }

    TripRouter.insertTrip(
        plan.getIndividualPlan(toRemove.getDriverId()),
        subtrips.get(0).getOriginActivity(),
        newTrip,
        subtrips.get(subtrips.size() - 1).getDestinationActivity());
  }
예제 #28
0
 @Override
 public void run(Person person) {
   try {
     Plan plan = person.getSelectedPlan();
     this.transitLegsRemover.run(plan);
     //				for (Plan plan : person.getPlans()) {
     Activity prevAct = null;
     for (PlanElement pe : plan.getPlanElements()) {
       if (pe instanceof Activity) {
         Activity act = (Activity) pe;
         if (prevAct != null) {
           List<Leg> legs =
               router.calcRoute(
                   new FakeFacility(prevAct.getCoord()),
                   new FakeFacility(act.getCoord()),
                   act.getStartTime(),
                   person);
           out.write(
               person.getId()
                   + " "
                   + prevAct.getCoord()
                   + " -> "
                   + act.getCoord()
                   + " @ "
                   + Time.writeTime(act.getStartTime())
                   + " :\n");
           if (legs != null) {
             for (Leg l : legs) {
               out.write("  " + l.getMode());
               if (l.getRoute() instanceof ExperimentalTransitRoute) {
                 ExperimentalTransitRoute r = (ExperimentalTransitRoute) l.getRoute();
                 out.write(" " + r.getRouteDescription());
               }
               out.write("\n");
             }
           }
         }
         prevAct = act;
       }
     }
     //				}
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
예제 #29
0
  /** @param args */
  public static void main(String[] args) {
    MutableScenario scenario =
        (MutableScenario) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network net = scenario.getNetwork();
    MatsimIo.loadNetwork(DgPaths.IVTCHNET, scenario);
    Population plansCmcf = MatsimIo.loadPlans(cmcfPlansFile, net);
    Population plans = MatsimIo.loadPlans(plansFile, net);
    for (Person p : plans.getPersons().values()) {
      Plan pl = p.getSelectedPlan();
      Leg l = ((PlanImpl) pl).getNextLeg(((PlanImpl) pl).getFirstActivity());
      Plan plcmcf = plansCmcf.getPersons().get(p.getId()).getSelectedPlan();
      Leg lcmcf = ((PlanImpl) plcmcf).getNextLeg(((PlanImpl) plcmcf).getFirstActivity());
      l.setRoute(lcmcf.getRoute());
    }
    MatsimIo.writePlans(plans, net, outPlansFile);

    log.info("done");
  }
 @Override
 public Id<TransitStopFacility> getDesiredAccessStopId() {
   Leg leg = getCurrentLeg();
   if (!(leg.getRoute() instanceof ExperimentalTransitRoute)) {
     log.error(
         "pt-leg has no TransitRoute. Removing agent from simulation. Agent "
             + getId().toString());
     log.info(
         "route: "
             + leg.getRoute().getClass().getCanonicalName()
             + " "
             + leg.getRoute().getRouteDescription());
     return null;
   } else {
     ExperimentalTransitRoute route = (ExperimentalTransitRoute) leg.getRoute();
     Id<TransitStopFacility> accessStopId = route.getAccessStopId();
     return accessStopId;
   }
 }