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); } }
public void startLeg(Leg leg) { this.leg = leg; routeIndex = 0; if (leg.getRoute() instanceof NetworkRoute) { route = (NetworkRoute) leg.getRoute(); } }
@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 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 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; } }
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 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(); }
@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; }
@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); } }
@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; } }
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 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); } } }
protected double calcLegScore( final double departureTime, final double arrivalTime, final Leg leg) { double tmpScore = 0.0; double travelTime = arrivalTime - departureTime; // traveltime in seconds double dist = 0.0; // distance in meters if (TransportMode.car.equals(leg.getMode())) { if (marginalUtilityOfFuel != 0.0) { /* we only as for the route when we have to calculate a distance cost, * because route.getDist() may calculate the distance if not yet * available, which is quite an expensive operation */ Route route = leg.getRoute(); dist = route.getDistance(); /* TODO the route-distance does not contain the length of the first or * last link of the route, because the route doesn't know those. Should * be fixed somehow, but how? MR, jan07 */ /* TODO in the case of within-day replanning, we cannot be sure that the * distance in the leg is the actual distance driven by the agent. */ } tmpScore += travelTime * marginalUtilityOfTraveling + marginalUtilityOfFuel * 0.12d / 1000.0d * dist; } else if (TransportMode.pt.equals(leg.getMode())) { if (marginalUtilityOfPtFare != 0.0) { Route route = leg.getRoute(); dist = route.getDistance(); } tmpScore = tmpScore + travelTime * marginalUtilityOfTravelingPT + marginalUtilityOfPtFare * 0.28d / 1000.0d * dist; } else if (TransportMode.walk.equals(leg.getMode())) { tmpScore += travelTime * marginalUtilityOfTravelingWalk; } else { // use the same values as for "car" tmpScore += travelTime * marginalUtilityOfTraveling + marginalUtilityOfFuel * dist; } return tmpScore; }
private void initializeOneWayCarsharingEndWalkLeg(Leg leg, double now) { this.state = MobsimAgent.State.LEG; Route route = leg.getRoute(); initializeCSWalkLeg( "walk_ow_sb", now, endStationOW.getLink(), scenario.getNetwork().getLinks().get(route.getEndLinkId())); }
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())); }
private void initializeTwoWayCarsharingStartWalkLeg(Leg leg, double now) { this.state = MobsimAgent.State.LEG; Route route = leg.getRoute(); TwoWayCSStation station = findClosestAvailableTWCar(route.getStartLinkId()); if (station == null) { this.state = MobsimAgent.State.ABORT; this.simulation .getEventsManager() .processEvent(new NoVehicleCarSharingEvent(now, route.getStartLinkId(), "rt")); return; } startLinkTW = station.getLink(); twVehId = station.getIDs().get(0); this.carSharingVehicles.getRoundTripVehicles().removeVehicle(station, station.getIDs().get(0)); mapTW.put(scenario.getNetwork().getLinks().get(leg.getRoute().getStartLinkId()), startLinkTW); initializeCSWalkLeg( "walk_rb", now, scenario.getNetwork().getLinks().get(route.getStartLinkId()), startLinkTW); }
@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(); } } }
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()); }
// added methods private void initializeFreeFloatingStartWalkLeg(Leg leg, double now) { this.state = MobsimAgent.State.LEG; Route route = leg.getRoute(); ParkingLinkInfo vehicleLocation = this.parkingModule.getNextFreeFloatingVehicle( this.scenario.getNetwork().getLinks().get(route.getStartLinkId()).getCoord(), this.person.getId(), now); if (vehicleLocation == null || vehicleLocation.getLinkId() == null) { log.warn( "Agent with id: " + this.getId().toString() + " was aborted because the freefloating vehicle was not avaialble or the vehicle id was not set up."); this.state = MobsimAgent.State.ABORT; return; } vehID = vehicleLocation.getVehicleId().toString(); startLink = this.scenario.getNetwork().getLinks().get(vehicleLocation.getLinkId()); LegImpl walkLeg = new LegImpl("walk_ff"); GenericRouteImpl walkRoute = new GenericRouteImpl(route.getStartLinkId(), startLink.getId()); final double dist = CoordUtils.calcEuclideanDistance( scenario.getNetwork().getLinks().get(route.getStartLinkId()).getCoord(), startLink.getCoord()); final double estimatedNetworkDistance = dist * this.beelineFactor; final int travTime = (int) (estimatedNetworkDistance / this.walkSpeed); walkRoute.setTravelTime(travTime); walkRoute.setDistance(estimatedNetworkDistance); walkLeg.setRoute(walkRoute); this.cachedDestinationLinkId = startLink.getId(); 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; }
/** @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"); }
private void initializeFreeFLoatingWalkLeg(Leg leg, double now) { this.state = MobsimAgent.State.LEG; Route route = leg.getRoute(); FreeFloatingStation location = findClosestAvailableCar(route.getStartLinkId()); if (location == null) { this.state = MobsimAgent.State.ABORT; this.simulation .getEventsManager() .processEvent(new NoVehicleCarSharingEvent(now, route.getStartLinkId(), "ff")); return; } ffVehId = location.getIDs().get(0); this.carSharingVehicles.getFreeFLoatingVehicles().removeVehicle(location.getLink(), ffVehId); startLinkFF = location.getLink(); initializeCSWalkLeg( "walk_ff", now, scenario.getNetwork().getLinks().get(route.getStartLinkId()), startLinkFF); }
private void handleLeg(EventsToScore eventsToScore, Fixture f, Leg leg) { eventsToScore.handleEvent( new PersonDepartureEvent( leg.getDepartureTime(), f.person.getId(), leg.getRoute().getStartLinkId(), leg.getMode())); if (leg.getRoute() instanceof NetworkRoute) { NetworkRoute networkRoute = (NetworkRoute) leg.getRoute(); eventsToScore.handleEvent( new LinkLeaveEvent( leg.getDepartureTime(), f.person.getId(), leg.getRoute().getStartLinkId(), networkRoute.getVehicleId())); for (Id<Link> linkId : networkRoute.getLinkIds()) { eventsToScore.handleEvent( new LinkEnterEvent( leg.getDepartureTime(), f.person.getId(), linkId, networkRoute.getVehicleId())); eventsToScore.handleEvent( new LinkLeaveEvent( leg.getDepartureTime(), f.person.getId(), linkId, networkRoute.getVehicleId())); } eventsToScore.handleEvent( new LinkEnterEvent( leg.getDepartureTime() + leg.getTravelTime(), f.person.getId(), leg.getRoute().getEndLinkId(), null)); } else { eventsToScore.handleEvent( new TeleportationArrivalEvent( leg.getDepartureTime() + leg.getTravelTime(), f.person.getId(), leg.getRoute().getDistance())); } eventsToScore.handleEvent( new PersonArrivalEvent( leg.getDepartureTime() + leg.getTravelTime(), f.person.getId(), leg.getRoute().getEndLinkId(), leg.getMode())); }
/** Why? dg 09-2013 */ private void createExperimentalTransitRoutes(Scenario sc) { for (Person person : sc.getPopulation().getPersons().values()) { for (Plan plan : person.getPlans()) { for (PlanElement pe : plan.getPlanElements()) { if (pe instanceof Leg) { Leg leg = (Leg) pe; if (leg.getMode().equals("pt")) { GenericRoute route = (GenericRoute) leg.getRoute(); ExperimentalTransitRoute tr = (ExperimentalTransitRoute) new ExperimentalTransitRouteFactory().createRoute(null, null); leg.setRoute(tr); tr.setRouteDescription( route.getStartLinkId(), route.getRouteDescription(), route.getEndLinkId()); tr.setDistance(route.getDistance()); } } } } } }
/** * Some data of the currently simulated Leg is cached to speed up the simulation. If the Leg * changes (for example the Route or the Destination Link), those cached data has to be reseted. * If the Leg has not changed, calling this method should have no effect on the Results of the * Simulation! */ void resetCaches() { // moving this method not to WithinDay for the time being since it seems to make some sense to // keep this where the internal are // known best. kai, oct'10 // Compromise: package-private here; making it public in the Withinday class. kai, nov'10 this.cachedNextLinkId = null; this.cachedRouteLinkIds = null; this.cachedDestinationLinkId = null; /* * The Leg may have been exchanged in the Person's Plan, so * we update the Reference to the currentLeg Object. */ PlanElement currentPlanElement = this.getPlanElements().get(this.currentPlanElementIndex); if (currentPlanElement instanceof Leg) { this.currentLeg = ((Leg) currentPlanElement); this.cachedRouteLinkIds = null; Route route = currentLeg.getRoute(); if (route == null) { log.error( "The agent " + this.getId() + " has no route in its leg. Removing the agent from the simulation."); // " (But as far as I can tell, this will not truly remove the agent??? kai, // nov'11)"); // this.simulation.getAgentCounter().decLiving(); // this.simulation.getAgentCounter().incLost(); this.state = MobsimAgent.State.ABORT; return; } this.cachedDestinationLinkId = route.getEndLinkId(); } else { // If an activity is performed, update its current activity. this.calculateAndSetDepartureTime((Activity) this.getCurrentPlanElement()); } }
private static void testRestrictedNetwork(final Config config) throws Exception { // create a simple scenario, with two parallel links, // a long one for cars, a short one for pt. final Scenario scenario = ScenarioUtils.createScenario(config); Network net = scenario.getNetwork(); Node n1 = net.getFactory().createNode(Id.create(1, Node.class), new Coord((double) 0, (double) 0)); Node n2 = net.getFactory().createNode(Id.create(2, Node.class), new Coord((double) 0, (double) 0)); Node n3 = net.getFactory().createNode(Id.create(3, Node.class), new Coord((double) 0, (double) 0)); Node n4 = net.getFactory().createNode(Id.create(4, Node.class), new Coord((double) 0, (double) 0)); Link l1 = net.getFactory().createLink(Id.create("l1", Link.class), n1, n2); Link l2c = net.getFactory().createLink(Id.create("l2c", Link.class), n2, n3); Link l2pt = net.getFactory().createLink(Id.create("l2pt", Link.class), n2, n3); Link l3 = net.getFactory().createLink(Id.create("l3", Link.class), n3, n4); l2c.setAllowedModes(Collections.singleton(TransportMode.car)); l2c.setLength(1000); l2pt.setAllowedModes(Collections.singleton(TransportMode.pt)); l2pt.setLength(10); net.addNode(n1); net.addNode(n2); net.addNode(n3); net.addNode(n4); net.addLink(l1); net.addLink(l2c); net.addLink(l2pt); net.addLink(l3); Injector injector = Injector.createInjector( scenario.getConfig(), new AbstractModule() { @Override public void install() { install( AbstractModule.override( Arrays.asList(new TripRouterModule()), new AbstractModule() { @Override public void install() { bind(Scenario.class).toInstance(scenario); addTravelTimeBinding("car") .toInstance( new FreespeedTravelTimeAndDisutility(config.planCalcScore())); addTravelDisutilityFactoryBinding("car") .toInstance(new OnlyTimeDependentTravelDisutilityFactory()); } })); } }); // create the factory, get a router, route. Provider<TripRouter> factory = injector.getProvider(TripRouter.class); TripRouter router = factory.get(); List<? extends PlanElement> trip = router.calcRoute( TransportMode.car, new LinkFacility(l1), new LinkFacility(l3), 0, PersonImpl.createPerson(Id.create("toto", Person.class))); Leg l = (Leg) trip.get(0); // actual test NetworkRoute r = (NetworkRoute) l.getRoute(); Assert.assertEquals("unexpected route length " + r.getLinkIds(), 1, r.getLinkIds().size()); Assert.assertEquals("unexpected link", l2c.getId(), r.getLinkIds().get(0)); }
/** Checks that routes are found when using a monomodal network (ie modes are not restricted) */ @Test public void testMonomodalNetwork() throws Exception { final Config config = ConfigUtils.createConfig(); final Scenario scenario = ScenarioUtils.createScenario(config); Network net = scenario.getNetwork(); Node n1 = net.getFactory().createNode(Id.create(1, Node.class), new Coord((double) 0, (double) 0)); Node n2 = net.getFactory().createNode(Id.create(2, Node.class), new Coord((double) 0, (double) 0)); Node n3 = net.getFactory().createNode(Id.create(3, Node.class), new Coord((double) 0, (double) 0)); Node n4 = net.getFactory().createNode(Id.create(4, Node.class), new Coord((double) 0, (double) 0)); Link l1 = net.getFactory().createLink(Id.create("l1", Link.class), n1, n2); Link l2long = net.getFactory().createLink(Id.create("l2long", Link.class), n2, n3); Link l2short = net.getFactory().createLink(Id.create("l2short", Link.class), n2, n3); Link l3 = net.getFactory().createLink(Id.create("l3", Link.class), n3, n4); l2long.setLength(1000); l2short.setLength(10); net.addNode(n1); net.addNode(n2); net.addNode(n3); net.addNode(n4); net.addLink(l1); net.addLink(l2long); net.addLink(l2short); net.addLink(l3); // create the factory, get a router, route. Injector injector = Injector.createInjector( scenario.getConfig(), new AbstractModule() { @Override public void install() { install( AbstractModule.override( Arrays.asList(new TripRouterModule()), new AbstractModule() { @Override public void install() { bind(Scenario.class).toInstance(scenario); addTravelTimeBinding("car") .toInstance( new FreespeedTravelTimeAndDisutility(config.planCalcScore())); addTravelDisutilityFactoryBinding("car") .toInstance(new OnlyTimeDependentTravelDisutilityFactory()); } })); } }); TripRouter router = injector.getInstance(TripRouter.class); List<? extends PlanElement> trip = router.calcRoute( TransportMode.car, new LinkFacility(l1), new LinkFacility(l3), 0, PersonImpl.createPerson(Id.create("toto", Person.class))); Leg l = (Leg) trip.get(0); // actual test NetworkRoute r = (NetworkRoute) l.getRoute(); Assert.assertEquals("unexpected route length " + r.getLinkIds(), 1, r.getLinkIds().size()); Assert.assertEquals("unexpected link", l2short.getId(), r.getLinkIds().get(0)); }
private boolean microRouteCurrentLegRoute( Leg leg, Person person, int currentLinkIndex, double time, Network network, TripRouter tripRouter, Random random, Plan plan) { Route route = leg.getRoute(); // if the route type is not supported (e.g., because it is a walking agent) if (!(route instanceof NetworkRoute)) return false; if (random.nextFloat() > 0.3) return false; // only 30% replanners PersonImpl p = (PersonImpl) person; int legnr = plan.getPlanElements().indexOf(leg); // logger.warn(legnr); if (p.getAge() == legnr) { // logger.error("agent already replanned"); // return false; // agent has been replanned already } else { // p.setAge(legnr); } NetworkRoute oldRoute = (NetworkRoute) route; /* * Get the Id of the current Link. * Create a List that contains all links of a route, including the Start- and EndLinks. */ List<Id<Link>> allLinkIds = getRouteLinkIds(oldRoute); // int links2go = allLinkIds.size() - (currentLinkIndex + 1); // if (links2go >= 3) { Id<Link> startLink = allLinkIds.get(0); Id<Link> endLink = allLinkIds.get(allLinkIds.size() - 1); // The linkIds of the new Route --------------------------- List<Id<Link>> linkIds = new ArrayList<Id<Link>>(); // start of the old route linkIds.addAll(allLinkIds.subList(1, currentLinkIndex)); // currentLinkIndex exclusive // micro-reroute part of route --------------------------- Id<Link> currentLinkId = allLinkIds.get(currentLinkIndex); // link 1, currentLinkIndex = 1 Link fromLink = network.getLinks().get(currentLinkId); int jump = random.nextInt(links2go - 2) + 2; // start with 2 int toLinkIndex = (currentLinkIndex + jump); // jump over one link // Id<Link> toLinkId = allLinkIds.get(toLinkIndex); // Link toLink = network.getLinks().get(toLinkId); // Facility<ActivityFacility> fromFacility = new LinkWrapperFacility(fromLink); Facility<ActivityFacility> toFacility = new LinkWrapperFacility(toLink); List<? extends PlanElement> planElements = tripRouter.calcRoute(leg.getMode(), fromFacility, toFacility, time, person); // if (planElements.size() != 1) { throw new RuntimeException( "Expected a list of PlanElements containing exactly one element, " + "but the returned list contained " + planElements.size() + " elements."); } Leg newLeg = (Leg) planElements.get(0); Route newRoute = newLeg.getRoute(); linkIds.addAll(getRouteLinkIds(newRoute)); // currentLinkIndex => startLink // remainder of the old route --------------------------- if (toLinkIndex + 1 < allLinkIds.size() - 1) { // if route is not yet finished: linkIds.addAll(allLinkIds.subList(toLinkIndex + 1, allLinkIds.size() - 1)); } // Overwrite old Route if (linkIds.size() > 2 && toLinkId.compareTo(fromLink.getId()) != 0) { List<Id<Link>> middleLinks = linkIds.subList(0, linkIds.size()); // to is exclusive // String str = oldRoute.toString(); // int lo = oldRoute.getLinkIds().size(); oldRoute.setLinkIds(startLink, middleLinks, endLink); // if (oldRoute.getLinkIds().size() != lo) { // logger.info(person.getId() + " :" + str + "\n" + // oldRoute.toString()); // } } // else do not replace route } return true; }
@Override public Double getExpectedTravelDistance() { return (currentLeg.getRoute().getDistance()); }