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 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;
 }
 protected boolean containsId(
     List<TransitRouteStop> stopsToCome, Id<TransitStopFacility> egressStopId) {
   for (TransitRouteStop stop : stopsToCome) {
     if (egressStopId.equals(stop.getStopFacility().getId())) {
       return true;
     }
   }
   return false;
 }
 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;
 }
 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);
 }
  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();
        }
      }
    }
  }
  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;
  }
  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 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;
  }
  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.");
    }
  }
 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;
 }
  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;
  }
Beispiel #15
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();
    }
  }