protected boolean containsId(
     List<TransitRouteStop> stopsToCome, Id<TransitStopFacility> egressStopId) {
   for (TransitRouteStop stop : stopsToCome) {
     if (egressStopId.equals(stop.getStopFacility().getId())) {
       return true;
     }
   }
   return false;
 }
 private Set<Id> getStopsUsed(Collection<TransitRoute> routes) {
   Set<Id> stopsUsed = new TreeSet<Id>();
   for (TransitRoute route : routes) {
     for (TransitRouteStop stop : route.getStops()) {
       stopsUsed.add(stop.getStopFacility().getId());
     }
   }
   return stopsUsed;
 }
 public void testInitialization() {
   TransitStopFacility stopFacility =
       new TransitStopFacilityImpl(
           Id.create(1, TransitStopFacility.class), new CoordImpl(2, 3), false);
   double arrivalDelay = 4;
   double departureDelay = 5;
   TransitRouteStop routeStop = createTransitRouteStop(stopFacility, arrivalDelay, departureDelay);
   assertEquals(stopFacility, routeStop.getStopFacility());
   assertEquals(arrivalDelay, routeStop.getArrivalOffset(), EPSILON);
   assertEquals(departureDelay, routeStop.getDepartureOffset(), EPSILON);
 }
  public static TransitSchedule removeAllRoutesWithMissingLinksFromSchedule(
      TransitSchedule transitSchedule, Network network) {
    log.info("Removing stops and routes with missing links from the schedule");
    TransitSchedule tS = TransitScheduleCleaner.makeTransitScheduleModifiable(transitSchedule);
    printStatistic(tS);
    int removedRoutes = 0;

    // Remove routes with missing links
    for (TransitLine transitLine : tS.getTransitLines().values()) {

      Set<TransitRoute> transitRouteToBeRemoved = new HashSet<TransitRoute>();

      for (TransitRoute transitRoute : transitLine.getRoutes().values()) {

        // Remove Route, when links are missing in the network
        if (network.getLinks().get(transitRoute.getRoute().getStartLinkId()) == null) {
          transitRouteToBeRemoved.add(transitRoute);
          continue;
        }

        for (Id linkId : transitRoute.getRoute().getLinkIds()) {
          if (network.getLinks().get(linkId) == null) {
            transitRouteToBeRemoved.add(transitRoute);
            break;
          }
        }

        if (network.getLinks().get(transitRoute.getRoute().getEndLinkId()) == null) {
          transitRouteToBeRemoved.add(transitRoute);
          continue;
        }

        // Remove route, if one of its stops, has a missing link
        for (TransitRouteStop transitRouteStop : transitRoute.getStops()) {
          if (network.getLinks().get(transitRouteStop.getStopFacility().getLinkId()) == null) {
            transitRouteToBeRemoved.add(transitRoute);
            break;
          }
        }
      }

      for (TransitRoute transitRoute : transitRouteToBeRemoved) {
        if (transitLine.removeRoute(transitRoute) == true) {
          removedRoutes++;
        }
      }
    }

    log.info("Removed " + removedRoutes + " routes due to missing links or stops");
    printStatistic(tS);

    return tS;
  }
 public WaitTimeStuckCalculator(
     final Population population,
     final TransitSchedule transitSchedule,
     final int timeSlot,
     final int totalTime) {
   this.population = population;
   this.timeSlot = timeSlot;
   for (TransitLine line : transitSchedule.getTransitLines().values())
     for (TransitRoute route : line.getRoutes().values()) {
       double[] sortedDepartures = new double[route.getDepartures().size()];
       int d = 0;
       for (Departure departure : route.getDepartures().values())
         sortedDepartures[d++] = departure.getDepartureTime();
       Arrays.sort(sortedDepartures);
       Map<Id<TransitStopFacility>, WaitTimeData> stopsMap =
           new HashMap<Id<TransitStopFacility>, WaitTimeData>(100);
       Map<Id<TransitStopFacility>, double[]> stopsScheduledMap =
           new HashMap<Id<TransitStopFacility>, double[]>(100);
       for (TransitRouteStop stop : route.getStops()) {
         stopsMap.put(
             stop.getStopFacility().getId(), new WaitTimeDataArray(totalTime / timeSlot + 1));
         double[] cacheWaitTimes = new double[totalTime / timeSlot + 1];
         for (int i = 0; i < cacheWaitTimes.length; i++) {
           double endTime = timeSlot * (i + 1);
           if (endTime > 24 * 3600) endTime -= 24 * 3600;
           cacheWaitTimes[i] = Time.UNDEFINED_TIME;
           SORTED_DEPARTURES:
           for (double departure : sortedDepartures) {
             double arrivalTime =
                 departure
                     + (stop.getArrivalOffset() != Time.UNDEFINED_TIME
                         ? stop.getArrivalOffset()
                         : stop.getDepartureOffset());
             if (arrivalTime >= endTime) {
               cacheWaitTimes[i] = arrivalTime - endTime;
               break SORTED_DEPARTURES;
             }
           }
           if (cacheWaitTimes[i] == Time.UNDEFINED_TIME)
             cacheWaitTimes[i] =
                 sortedDepartures[0]
                     + 24 * 3600
                     + (stop.getArrivalOffset() != Time.UNDEFINED_TIME
                         ? stop.getArrivalOffset()
                         : stop.getDepartureOffset())
                     - endTime;
         }
         stopsScheduledMap.put(stop.getStopFacility().getId(), cacheWaitTimes);
       }
       Tuple<Id<TransitLine>, Id<TransitRoute>> key =
           new Tuple<Id<TransitLine>, Id<TransitRoute>>(line.getId(), route.getId());
       waitTimes.put(key, stopsMap);
       scheduledWaitTimes.put(key, stopsScheduledMap);
     }
 }
 public void testStopFacility() {
   TransitStopFacility stopFacility1 =
       new TransitStopFacilityImpl(
           Id.create(1, TransitStopFacility.class), new CoordImpl(2, 3), false);
   TransitStopFacility stopFacility2 =
       new TransitStopFacilityImpl(
           Id.create(2, TransitStopFacility.class), new CoordImpl(3, 4), false);
   double arrivalDelay = 4;
   double departureDelay = 5;
   TransitRouteStop routeStop =
       createTransitRouteStop(stopFacility1, arrivalDelay, departureDelay);
   assertEquals(stopFacility1, routeStop.getStopFacility());
   routeStop.setStopFacility(stopFacility2);
   assertEquals(stopFacility2, routeStop.getStopFacility());
 }
 private static boolean isRelatedWithLine(Person person, TransitLine line) {
   ExperimentalTransitRouteFactory factory = new ExperimentalTransitRouteFactory();
   for (Plan plan : person.getPlans())
     for (PlanElement planElement : plan.getPlanElements())
       if (planElement instanceof Leg && ((Leg) planElement).getRoute() instanceof Route) {
         Route origRoute = ((Leg) planElement).getRoute();
         ExperimentalTransitRoute route =
             (ExperimentalTransitRoute)
                 factory.createRoute(origRoute.getStartLinkId(), origRoute.getEndLinkId());
         route.setStartLinkId(origRoute.getStartLinkId());
         route.setEndLinkId(origRoute.getEndLinkId());
         route.setRouteDescription(origRoute.getRouteDescription());
         for (TransitRoute transitRoute : line.getRoutes().values())
           for (TransitRouteStop stop : transitRoute.getStops())
             if (stop.getStopFacility().getId().equals(route.getAccessStopId())
                 || stop.getStopFacility().getId().equals(route.getEgressStopId())) return true;
       }
   return false;
 }
  private LeastCostPathCalculator.Path getShortestPath(Node startNode, TransitRouteStop toStop) {
    LeastCostPathCalculator.Path shortestPath = null;

    for (Id<TransitStopFacility> toStopFacilityId :
        linkedStopFacilitiesTree.get(toStop.getStopFacility().getId())) {
      TransitStopFacility facility = this.schedule.getFacilities().get(toStopFacilityId);
      Id<Link> linkId = facility.getLinkId();
      Link link = this.network.getLinks().get(linkId);
      Node endNode = link.getFromNode();
      LeastCostPathCalculator.Path tempShortestPath =
          this.router.calcLeastCostPath(startNode, endNode, "", "");
      if (tempShortestPath != null
          && (shortestPath == null || (tempShortestPath.travelCost < shortestPath.travelCost))) {
        shortestPath = tempShortestPath;
        toStop.setStopFacility(this.schedule.getFacilities().get(toStopFacilityId));
      }
    }

    return shortestPath;
  }
  private final void createVehicleLinkSpeedAttributes() {
    for (TransitLine transitLine : scenario.getTransitSchedule().getTransitLines().values()) {
      for (TransitRoute transitRoute : transitLine.getRoutes().values()) {
        Set<Id> vehIds = new HashSet<Id>();
        for (Departure departure : transitRoute.getDepartures().values()) {
          vehIds.add(departure.getVehicleId());
        }

        Iterator<TransitRouteStop> iterator = transitRoute.getStops().iterator();
        double departure = iterator.next().getDepartureOffset();
        while (iterator.hasNext()) {
          TransitRouteStop routeStop = iterator.next();
          double arrival = routeStop.getArrivalOffset();
          Link link = scenario.getNetwork().getLinks().get(routeStop.getStopFacility().getLinkId());
          double speed = link.getLength() / (arrival - departure);
          if (speed >= 200.0) {
            System.out.println(
                "line="
                    + transitLine.getId()
                    + ";route="
                    + transitRoute.getId()
                    + "stop="
                    + routeStop.getStopFacility().getId()
                    + ": lLenth="
                    + link.getLength()
                    + ";arr="
                    + arrival
                    + ";dep="
                    + departure
                    + "");
          }

          for (Id vehId : vehIds) {
            this.vehicleAttributes.putAttribute(vehId.toString(), link.getId().toString(), speed);
          }

          departure = routeStop.getDepartureOffset();
        }
      }
    }
  }
 private void removeNonUsedStopFacilities() {
   // Collect all used stop facilities:
   Set<Id<TransitStopFacility>> usedStopFacilities = new HashSet<>();
   for (TransitLine line : this.schedule.getTransitLines().values()) {
     for (TransitRoute route : line.getRoutes().values()) {
       for (TransitRouteStop stop : route.getStops()) {
         usedStopFacilities.add(stop.getStopFacility().getId());
       }
     }
   }
   // Check all stop facilities if not used:
   Set<TransitStopFacility> unusedStopFacilites = new HashSet<>();
   for (Id<TransitStopFacility> facilityId : this.schedule.getFacilities().keySet()) {
     if (!usedStopFacilities.contains(facilityId)) {
       unusedStopFacilites.add(this.schedule.getFacilities().get(facilityId));
     }
   }
   // Remove all stop facilities not used:
   for (TransitStopFacility facility : unusedStopFacilites) {
     this.schedule.removeStopFacility(facility);
   }
 }
  public static TransitSchedule removeStopsNotUsed(TransitSchedule transitSchedule) {

    log.info("Removing stops not used");
    TransitSchedule tS = TransitScheduleCleaner.makeTransitScheduleModifiable(transitSchedule);
    printStatistic(tS);

    Set<Id> stopsInUse = new TreeSet<Id>();
    Set<Id> stopsToBeRemoved = new TreeSet<Id>();

    for (TransitLine transitLine : tS.getTransitLines().values()) {
      for (TransitRoute transitRoute : transitLine.getRoutes().values()) {
        for (TransitRouteStop stop : transitRoute.getStops()) {
          stopsInUse.add(stop.getStopFacility().getId());
        }
      }
    }

    for (TransitStopFacility transitStopFacility : tS.getFacilities().values()) {
      if (!stopsInUse.contains(transitStopFacility.getId())) {
        stopsToBeRemoved.add(transitStopFacility.getId());
      }
    }

    StringBuffer sB = new StringBuffer();

    for (Id transitStopFacilityId : stopsToBeRemoved) {
      tS.getFacilities().remove(transitStopFacilityId);
      sB.append(transitStopFacilityId.toString() + ", ");
    }

    printStatistic(tS);
    log.info(
        "Removed " + stopsToBeRemoved.size() + " stops from transitSchedule: " + sB.toString());

    return tS;
  }
 public void testAwaitDepartureTime() {
   TransitStopFacility stopFacility =
       new TransitStopFacilityImpl(
           Id.create(1, TransitStopFacility.class), new CoordImpl(2, 3), false);
   double arrivalDelay = 4;
   double departureDelay = 5;
   TransitRouteStop routeStop = createTransitRouteStop(stopFacility, arrivalDelay, departureDelay);
   assertFalse(routeStop.isAwaitDepartureTime());
   routeStop.setAwaitDepartureTime(true);
   assertTrue(routeStop.isAwaitDepartureTime());
   routeStop.setAwaitDepartureTime(false);
   assertFalse(routeStop.isAwaitDepartureTime());
 }
 protected List<Leg> convertPathToLegList(
     double departureTime, Path p, Coord fromCoord, Coord toCoord, Person person) {
   List<Leg> legs = new ArrayList<Leg>();
   Leg leg;
   double walkDistance, walkWaitTime, travelTime = 0;
   Route walkRoute;
   Coord coord = fromCoord;
   TransitRouteStop stop = null;
   double time = departureTime;
   for (Link link : p.links) {
     TransitRouterNetworkLink l = (TransitRouterNetworkLink) link;
     if (l.route != null) {
       // in line link
       double ttime = ttCalculator.getLinkTravelTime(l, time, person, null);
       travelTime += ttime;
       time += ttime;
     } else if (l.fromNode.route != null) {
       // inside link
       leg = new LegImpl(TransportMode.pt);
       ExperimentalTransitRoute ptRoute =
           new ExperimentalTransitRoute(
               stop.getStopFacility(),
               l.fromNode.line,
               l.fromNode.route,
               l.fromNode.stop.getStopFacility());
       leg.setRoute(ptRoute);
       leg.setTravelTime(travelTime);
       legs.add(leg);
       travelTime = 0;
       stop = l.fromNode.stop;
       coord = l.fromNode.stop.getStopFacility().getCoord();
     } else if (l.toNode.route != null) {
       // wait link
       leg = new LegImpl(TransportMode.transit_walk);
       walkDistance =
           CoordUtils.calcEuclideanDistance(coord, l.toNode.stop.getStopFacility().getCoord());
       walkWaitTime =
           walkDistance / this.config.getBeelineWalkSpeed()
               + ttCalculator.getLinkTravelTime(
                   l, time + walkDistance / this.config.getBeelineWalkSpeed(), person, null);
       walkRoute =
           new GenericRouteImpl(
               stop == null ? null : stop.getStopFacility().getLinkId(),
               l.toNode.stop.getStopFacility().getLinkId());
       walkRoute.setDistance(walkDistance);
       leg.setRoute(walkRoute);
       leg.setTravelTime(walkWaitTime);
       legs.add(leg);
       stop = l.toNode.stop;
       time += walkWaitTime;
     }
   }
   leg = new LegImpl(TransportMode.transit_walk);
   walkDistance = CoordUtils.calcEuclideanDistance(coord, toCoord);
   walkWaitTime = walkDistance / this.config.getBeelineWalkSpeed();
   walkRoute =
       new GenericRouteImpl(stop == null ? null : stop.getStopFacility().getLinkId(), null);
   walkRoute.setDistance(walkDistance);
   leg.setRoute(walkRoute);
   leg.setTravelTime(walkWaitTime);
   legs.add(leg);
   return legs;
 }
  private void assignRoute(TransitRoute route) {

    List<Id<Link>> links = new ArrayList<>();
    int i = 0;
    while (i < (route.getStops().size())) {
      TransitRouteStop presentStop = route.getStops().get(i);
      TransitRouteStop nextStop =
          (i < route.getStops().size() - 1) ? route.getStops().get(i + 1) : null;

      if (nextStop != null) {

        // 	Case 1: For both stops a link assigned, then just route between the two.
        if (linkedStopFacilities.contains(presentStop.getStopFacility().getId())
            && linkedStopFacilities.contains(nextStop.getStopFacility().getId())) {
          links.add(presentStop.getStopFacility().getLinkId());

          Node startNode =
              this.network.getLinks().get(presentStop.getStopFacility().getLinkId()).getToNode();
          LeastCostPathCalculator.Path path = getShortestPath(startNode, nextStop);
          if (path != null) {
            for (Link link : path.links) {
              links.add(link.getId());
            }
          } else {
            Node fromNode =
                network.getLinks().get(presentStop.getStopFacility().getLinkId()).getToNode();
            Node toNode =
                network.getLinks().get(nextStop.getStopFacility().getLinkId()).getFromNode();
            Link artificialLink =
                (artificiallyAddedLinks.containsKey(new Tuple<>(fromNode, toNode)))
                    ? artificiallyAddedLinks.get(new Tuple<>(fromNode, toNode))
                    : getNewLink(fromNode, toNode);
            links.add(artificialLink.getId());
            artificiallyAddedLinks.put(new Tuple<>(fromNode, toNode), artificialLink);
          }

          // Case 2: PresentStop has no link, but NextStop has link then create link to closest
          // network node and route between that node and link of follow-stop.
        } else if (!linkedStopFacilities.contains(presentStop.getStopFacility().getId())
            && linkedStopFacilities.contains(nextStop.getStopFacility().getId())) {

          ArtificiallyConnectedStopFacility thisStopFacility =
              getArtificiallyConnectedStopFacility(presentStop.getStopFacility());
          Node toNode =
              network.getLinks().get(nextStop.getStopFacility().getLinkId()).getFromNode();

          links.add(thisStopFacility.myLink.getId());
          links.add(thisStopFacility.getLinkToNode(toNode).getId());

          // Case 3: PresentStop has link, but NextStop has no link then create link to closest
          // network node for follow stop and then route between the two.
        } else if (linkedStopFacilities.contains(presentStop.getStopFacility().getId())
            && !linkedStopFacilities.contains(nextStop.getStopFacility().getId())) {

          ArtificiallyConnectedStopFacility nextStopFacility =
              getArtificiallyConnectedStopFacility(nextStop.getStopFacility());
          Node fromNode =
              network.getLinks().get(presentStop.getStopFacility().getLinkId()).getToNode();

          links.add(presentStop.getStopFacility().getLinkId());
          links.add(nextStopFacility.getLinkFromNode(fromNode).getId());

          // Case 4: Neither PresentStop nor NextStop has link then standard link creation as with
          // Marcel's network creator.
        } else {
          ArtificiallyConnectedStopFacility thisStopFacility =
              getArtificiallyConnectedStopFacility(presentStop.getStopFacility());
          ArtificiallyConnectedStopFacility nextStopFacility =
              getArtificiallyConnectedStopFacility(nextStop.getStopFacility());

          links.add(thisStopFacility.myLink.getId());
          links.add(nextStopFacility.getLinkFromNode(thisStopFacility.myNode).getId());
        }

        // If nextStop was null, this means we have reached the end of the route and just add the
        // final link.
      } else {
        if (linkedStopFacilities.contains(presentStop.getStopFacility().getId())) {
          links.add(presentStop.getStopFacility().getLinkId());
        } else {
          ArtificiallyConnectedStopFacility thisStopFacility =
              getArtificiallyConnectedStopFacility(presentStop.getStopFacility());
          links.add(thisStopFacility.myLink.getId());
        }
      }

      i++;
    }
    if (links.size() > 0) {
      route.setRoute(RouteUtils.createNetworkRoute(links, this.network));
    } else {
      log.warn("No route found for transit route " + route.toString() + ". No route assigned.");
    }
  }
Example #15
0
  public TransitRouteData(Network network, TransitRoute transitRoute) {

    this.transportMode = transitRoute.getTransportMode();

    this.firstDeparture = Double.MAX_VALUE;
    this.lastDeparture = -Double.MAX_VALUE;
    this.vehIds = new TreeSet<String>();
    this.numberOfDepartures = 0;

    for (Departure departure : transitRoute.getDepartures().values()) {
      this.firstDeparture = Math.min(this.firstDeparture, departure.getDepartureTime());
      this.lastDeparture = Math.max(this.lastDeparture, departure.getDepartureTime());
      this.vehIds.add(departure.getVehicleId().toString());
      this.numberOfDepartures++;
    }

    this.firstStop = transitRoute.getStops().get(0).getStopFacility();
    this.lastStop =
        transitRoute.getStops().get(transitRoute.getStops().size() - 1).getStopFacility();

    if (this.firstStop == this.lastStop) {
      // get the stop location of stop with the largest distance between first and last stop
      TransitStopFacility currentViaStop = null;
      double currentViaDistance = Double.NEGATIVE_INFINITY;
      for (TransitRouteStop stop : transitRoute.getStops()) {
        double distanceFirstPotentialVia =
            CoordUtils.calcDistance(this.firstStop.getCoord(), stop.getStopFacility().getCoord());
        double distanceLastProtenialVia =
            CoordUtils.calcDistance(this.lastStop.getCoord(), stop.getStopFacility().getCoord());
        double newDistance =
            Math.sqrt(
                Math.pow(distanceFirstPotentialVia, 2) + Math.pow(distanceLastProtenialVia, 2));

        if (newDistance > currentViaDistance) {
          // this one is farther away - keep it
          currentViaStop = stop.getStopFacility();
          currentViaDistance = newDistance;
        }
      }
      this.viaStop = currentViaStop;
    } else {
      // get the stop in the middle of the line
      this.viaStop =
          transitRoute.getStops().get((int) (transitRoute.getStops().size() / 2)).getStopFacility();
    }

    // calculate the length of the route
    double distance = 0.0;
    double freeSpeedTravelTime = 0.0;
    for (Id<Link> linkId : transitRoute.getRoute().getLinkIds()) {
      Link link = network.getLinks().get(linkId);
      distance += link.getLength();
      freeSpeedTravelTime += link.getLength() / link.getFreespeed();
    }
    // add last link but not the first link
    Link link = network.getLinks().get(transitRoute.getRoute().getEndLinkId());
    distance += link.getLength();
    freeSpeedTravelTime += link.getLength() / link.getFreespeed();

    this.distance = distance;
    this.freeSpeedTravelTime = freeSpeedTravelTime;

    this.travelTime =
        transitRoute.getStops().get(transitRoute.getStops().size() - 1).getArrivalOffset();

    this.avgSpeed = this.distance / this.travelTime;
  }
  @Override
  public double getLinkTravelTime(Link link, final double time, Person person, Vehicle vehicle) {

    // if its a RoutingNetworkLink, unwrap it
    if (link instanceof RoutingNetworkLink) link = ((RoutingNetworkLink) link).getLink();

    //		Link previousLink = this.previousLinks.get();
    //		Double previousTime = this.previousTimes.get();	// has to be Double since get() might return
    // null!

    //		if ((link == previousLink) && (time == previousTime)) {
    //			return this.cachedTravelTimes.get();
    //		}
    //		this.previousLinks.set(link);
    //		this.previousTimes.set(time);

    BufferedData bd = bufferedData.get();
    if (bd == null) {
      bd = new BufferedData();
      bufferedData.set(bd);
    }
    if ((link == bd.previousLink) && (time == bd.previousTime)) {
      return bd.cachedTravelTime;
    }
    bd.previousLink = link;
    bd.previousTime = time;

    TransitRouterNetworkLink wrapped = (TransitRouterNetworkLink) link;
    TransitRouteStop fromStop = wrapped.fromNode.stop;
    TransitRouteStop toStop = wrapped.toNode.stop;
    if (wrapped.getRoute() != null) {
      // (agent stays on the same route, so use transit line travel time)

      double bestDepartureTime =
          departureTimeCache.getNextDepartureTime(wrapped.getRoute(), fromStop, time);

      // the travel time on the link is
      //   the time until the departure (``dpTime - now'')
      //   + the travel time on the link (there.arrivalTime - here.departureTime)
      // But quite often, we only have the departure time at the next stop.  Then we use that:
      double arrivalOffset =
          (toStop.getArrivalOffset() != Time.UNDEFINED_TIME)
              ? toStop.getArrivalOffset()
              : toStop.getDepartureOffset();
      double time2 = (bestDepartureTime - time) + (arrivalOffset - fromStop.getDepartureOffset());
      if (time2 < 0) {
        // ( this can only happen, I think, when ``bestDepartureTime'' is after midnight but
        // ``time'' was before )
        time2 += MIDNIGHT;
      }
      //			this.cachedTravelTimes.set(time2);
      bd.cachedTravelTime = time2;
      return time2;
    }
    // different transit routes, so it must be a line switch
    double distance = wrapped.getLength();
    double time2 =
        distance / this.config.getBeelineWalkSpeed() + this.config.getAdditionalTransferTime();
    //		this.cachedTravelTimes.set(time2);
    bd.cachedTravelTime = time2;

    return time2;
  }
  private final void convertSchedules(
      OTTDataContainer dataContainer, ObjectAttributes trainTypes, boolean isPerformance) {
    TransitScheduleFactory scheduleFactory = scenario.getTransitSchedule().getFactory();
    VehiclesFactory vehiclesFactory = ((ScenarioImpl) scenario).getVehicles().getFactory();

    VehicleType vehicleType =
        vehiclesFactory.createVehicleType(new IdImpl(WagonSimConstants.DEFAULT_VEHICLE_TYPE));
    VehicleCapacity vehicleCapacity = vehiclesFactory.createVehicleCapacity();
    // we do not use this capacity. Therefore it should infinite, otherwise this capacity may exceed
    // before ``our'' capacities are exceeded // dr, oct'13
    vehicleCapacity.setSeats(999999);
    vehicleCapacity.setStandingRoom(999999);
    // we defined the vehicle-enter/leave-time is implicit included in transfer-times which
    // are defined in the transitrouterconfig (for handling see
    // WagonSimTripRouterFactoryImpl#WagonSimRouterWrapper)
    // dr, oct'13
    vehicleType.setAccessTime(0);
    vehicleType.setEgressTime(0);
    vehicleType.setCapacity(vehicleCapacity);
    ((ScenarioImpl) scenario).getVehicles().addVehicleType(vehicleType);

    Date startDate = extractStartDate(dataContainer, isPerformance);
    System.out.println("startDate=" + startDate.toString());

    for (Locomotive locomotive : dataContainer.locomotives.values()) {

      Departure departure = null;
      List<TransitRouteStop> transitRouteStops = new ArrayList<TransitRouteStop>();
      for (StationData stationData : locomotive.trips.values()) {

        TransitStopFacility stopFacility =
            scenario.getTransitSchedule().getFacilities().get(stationData.stationId);
        if (stopFacility == null) {
          throw new RuntimeException(
              "locomotive id="
                  + locomotive.id
                  + ": station id="
                  + stationData.stationId
                  + " not found. Bailing out.");
        }

        double arrivalDelay = Double.NaN;
        double departureDelay = Double.NaN;
        if (departure == null) {
          double lineDepartureOffset =
              (stationData.departure.getTime() - startDate.getTime()) / 1000.0;
          if (!isPerformance) {
            lineDepartureOffset -= stationData.delayDeparture;
          }
          departure = scheduleFactory.createDeparture(locomotive.id, lineDepartureOffset);
          arrivalDelay = 0.0;
        } else {
          arrivalDelay =
              (stationData.arrival.getTime() - startDate.getTime()) / 1000.0
                  - departure.getDepartureTime();
          if (!isPerformance) {
            arrivalDelay -= stationData.delayArrival;
          }
        }
        departureDelay =
            (stationData.departure.getTime() - startDate.getTime()) / 1000.0
                - departure.getDepartureTime();
        if (!isPerformance) {
          departureDelay -= stationData.delayDeparture;
        }

        if (departureDelay < arrivalDelay) {
          throw new RuntimeException(
              "locomotive id="
                  + locomotive.id
                  + ": arrival="
                  + stationData.arrival.toString()
                  + " does not fit with departure="
                  + stationData.departure.toString()
                  + ". ("
                  + departureDelay
                  + "<"
                  + arrivalDelay
                  + ") Bailing out.");
        }

        TransitRouteStop stop =
            scheduleFactory.createTransitRouteStop(stopFacility, arrivalDelay, departureDelay);
        stop.setAwaitDepartureTime(true);
        transitRouteStops.add(stop);
      }

      if (transitRouteStops.size() > 1) {

        // check if train type is given
        if (trainTypes.getAttribute(locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED)
            == null) {
          throw new RuntimeException(
              "locomotive id="
                  + locomotive.id
                  + ": type="
                  + locomotive.type
                  + " is not defined by the train type table. Bailing out.");
        }

        TransitLine line = scheduleFactory.createTransitLine(locomotive.id);
        scenario.getTransitSchedule().addTransitLine(line);
        TransitRoute route =
            scheduleFactory.createTransitRoute(
                line.getId(), null, transitRouteStops, TransportMode.pt);
        line.addRoute(route);

        Vehicle vehicle = vehiclesFactory.createVehicle(route.getId(), vehicleType);
        ((ScenarioImpl) scenario).getVehicles().addVehicle(vehicle);
        departure.setVehicleId(vehicle.getId());
        route.addDeparture(departure);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(), WagonSimConstants.TRAIN_TYPE, locomotive.type);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_SPEED,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_WEIGHT,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_WEIGHT));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_LENGTH,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_LENGTH));

        // the next day
        vehicle = vehiclesFactory.createVehicle(new IdImpl(route.getId() + ".1"), vehicleType);
        ((ScenarioImpl) scenario).getVehicles().addVehicle(vehicle);
        departure =
            scheduleFactory.createDeparture(
                vehicle.getId(), departure.getDepartureTime() + 24 * 3600);
        departure.setVehicleId(vehicle.getId());
        route.addDeparture(departure);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(), WagonSimConstants.TRAIN_TYPE, locomotive.type);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_SPEED,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_WEIGHT,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_WEIGHT));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_LENGTH,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_LENGTH));

        // the day after the next day
        vehicle = vehiclesFactory.createVehicle(new IdImpl(route.getId() + ".2"), vehicleType);
        ((ScenarioImpl) scenario).getVehicles().addVehicle(vehicle);
        departure =
            scheduleFactory.createDeparture(
                vehicle.getId(), departure.getDepartureTime() + 24 * 3600);
        departure.setVehicleId(vehicle.getId());
        route.addDeparture(departure);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(), WagonSimConstants.TRAIN_TYPE, locomotive.type);
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_SPEED,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_SPEED));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_WEIGHT,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_WEIGHT));
        this.vehicleAttributes.putAttribute(
            vehicle.getId().toString(),
            WagonSimConstants.TRAIN_MAX_LENGTH,
            (Double)
                trainTypes.getAttribute(
                    locomotive.type.toString(), WagonSimConstants.TRAIN_MAX_LENGTH));
      } else if (transitRouteStops.size() == 1) {
        System.out.println(
            "locomotive id="
                + locomotive.id
                + ": only one station given. Therefore, no transitLine created.");
      } else {
        System.out.println(
            "locomotive id="
                + locomotive.id
                + ": no station is given. Therefore, no transitLine created.");
      }
    }
  }
  public void testEquals() {
    TransitStopFacility stopFacility1 =
        new TransitStopFacilityImpl(
            Id.create(1, TransitStopFacility.class), new CoordImpl(2, 3), false);
    TransitStopFacility stopFacility2 =
        new TransitStopFacilityImpl(
            Id.create(2, TransitStopFacility.class), new CoordImpl(3, 4), false);
    TransitRouteStop stop1 = createTransitRouteStop(stopFacility1, 10, 50);
    TransitRouteStop stop2 = createTransitRouteStop(stopFacility1, 10, 50);
    TransitRouteStop stop3 = createTransitRouteStop(stopFacility2, 10, 50);
    TransitRouteStop stop4 = createTransitRouteStop(stopFacility1, 10, 30);
    TransitRouteStop stop5 = createTransitRouteStop(stopFacility1, 20, 50);
    TransitRouteStop stop6 = createTransitRouteStop(null, 10, 50);
    TransitRouteStop stop7 = createTransitRouteStop(null, 10, 50);

    assertTrue(stop1.equals(stop2));
    assertTrue(stop2.equals(stop1));
    assertTrue(stop1.equals(stop1));

    assertFalse(stop1.equals(stop3)); // different stop facility
    assertFalse(stop3.equals(stop1));
    assertFalse(stop1.equals(stop4)); // different departureDelay
    assertFalse(stop4.equals(stop1));
    assertFalse(stop1.equals(stop5)); // different arrivalDelay
    assertFalse(stop5.equals(stop1));

    assertFalse(stop1.equals(stop6)); // null stop facility in stop6
    assertFalse(stop6.equals(stop1));

    assertTrue(stop6.equals(stop7)); // both stop facilities are null
    assertTrue(stop7.equals(stop6));
  }
Example #19
0
  public void createGraph(final String filename, final TransitRoute route) {

    HashMap<Id, Integer> stopIndex = new HashMap<Id, Integer>();
    int idx = 0;
    for (TransitRouteStop stop : route.getStops()) {
      stopIndex.put(stop.getStopFacility().getId(), idx);
      idx++;
    }

    HashSet<Id> vehicles = new HashSet<Id>();
    for (Departure dep : route.getDepartures().values()) {
      vehicles.add(dep.getVehicleId());
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    int numSeries = 0;
    double earliestTime = Double.POSITIVE_INFINITY;
    double latestTime = Double.NEGATIVE_INFINITY;

    for (Map.Entry<Id, List<Tuple<Id, Double>>> entry : this.positions.entrySet()) {
      if (vehicles.contains(entry.getKey())) {
        XYSeries series = new XYSeries("t", false, true);
        for (Tuple<Id, Double> pos : entry.getValue()) {
          Integer stopIdx = stopIndex.get(pos.getFirst());
          if (stopIdx != null) {
            double time = pos.getSecond().doubleValue();
            series.add(stopIdx.intValue(), time);
            if (time < earliestTime) {
              earliestTime = time;
            }
            if (time > latestTime) {
              latestTime = time;
            }
          }
        }
        dataset.addSeries(series);
        numSeries++;
      }
    }

    JFreeChart c =
        ChartFactory.createXYLineChart(
            "Route-Time Diagram, Route = " + route.getId(),
            "stops",
            "time",
            dataset,
            PlotOrientation.VERTICAL,
            false, // legend?
            false, // tooltips?
            false // URLs?
            );
    c.setBackgroundPaint(new Color(1.0f, 1.0f, 1.0f, 1.0f));

    XYPlot p = (XYPlot) c.getPlot();

    p.getRangeAxis().setInverted(true);
    p.getRangeAxis().setRange(earliestTime, latestTime);
    XYItemRenderer renderer = p.getRenderer();
    for (int i = 0; i < numSeries; i++) {
      renderer.setSeriesPaint(i, Color.black);
    }

    try {
      ChartUtilities.saveChartAsPNG(new File(filename), c, 1024, 768, null, true, 9);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }