Search in sources :

Example 1 with TransitStopVertex

use of org.opentripplanner.routing.vertextype.TransitStopVertex in project OpenTripPlanner by opentripplanner.

the class NearbyStopFinder method findNearbyStopsViaStreets.

/**
 * Return all stops within a certain radius of the given vertex, using network distance along streets.
 * If the origin vertex is a StopVertex, the result will include it.
 *
 * @param originVertices the origin point of the street search
 * @param reverseDirection if true the paths returned instead originate at the nearby stops and have the
 *                         originVertex as the destination
 * @param removeTempEdges after creating a new routing request and routing context, remove all the temporary
 *                        edges that are part of that context. NOTE: this will remove _all_ temporary edges
 *                        coming out of the origin and destination vertices, including those in any other
 *                        RoutingContext referencing them, making routing from/to them totally impossible.
 *                        This is a stopgap solution until we rethink the lifecycle of RoutingContext.
 */
public List<StopAtDistance> findNearbyStopsViaStreets(Set<Vertex> originVertices, boolean reverseDirection, boolean removeTempEdges, RoutingRequest routingRequest) {
    routingRequest.arriveBy = reverseDirection;
    if (!reverseDirection) {
        routingRequest.setRoutingContext(graph, originVertices, null);
    } else {
        routingRequest.setRoutingContext(graph, null, originVertices);
    }
    int walkTime = (int) (radiusMeters / new RoutingRequest().walkSpeed);
    routingRequest.worstTime = routingRequest.dateTime + (reverseDirection ? -walkTime : walkTime);
    routingRequest.disableRemainingWeightHeuristic = true;
    routingRequest.rctx.remainingWeightHeuristic = new TrivialRemainingWeightHeuristic();
    routingRequest.dominanceFunction = new DominanceFunction.MinimumWeight();
    ShortestPathTree spt = astar.getShortestPathTree(routingRequest);
    List<StopAtDistance> stopsFound = Lists.newArrayList();
    Multimap<FlexStopLocation, State> locationsMap = ArrayListMultimap.create();
    if (spt != null) {
        // TODO use GenericAStar and a traverseVisitor? Add an earliestArrival switch to genericAStar?
        for (State state : spt.getAllStates()) {
            Vertex targetVertex = state.getVertex();
            if (originVertices.contains(targetVertex))
                continue;
            if (targetVertex instanceof TransitStopVertex && state.isFinal()) {
                stopsFound.add(StopAtDistance.stopAtDistanceForState(state, ((TransitStopVertex) targetVertex).getStop()));
            }
            if (OTPFeature.FlexRouting.isOn() && targetVertex instanceof StreetVertex && ((StreetVertex) targetVertex).flexStopLocations != null) {
                for (FlexStopLocation flexStopLocation : ((StreetVertex) targetVertex).flexStopLocations) {
                    // This is for a simplification, so that we only return one vertex from each
                    // stop location. All vertices are added to the multimap, which is filtered
                    // below, so that only the closest vertex is added to stopsFound
                    locationsMap.put(flexStopLocation, state);
                }
            }
        }
    }
    for (var locationStates : locationsMap.asMap().entrySet()) {
        FlexStopLocation flexStopLocation = locationStates.getKey();
        Collection<State> states = locationStates.getValue();
        // Select the vertex from all vertices that are reachable per FlexStopLocation by taking
        // the minimum walking distance
        State min = Collections.min(states, (s1, s2) -> (int) (s1.walkDistance - s2.walkDistance));
        stopsFound.add(StopAtDistance.stopAtDistanceForState(min, flexStopLocation));
    }
    /* Add the origin vertices if needed. The SPT does not include the initial state. FIXME shouldn't it? */
    for (Vertex vertex : originVertices) {
        if (vertex instanceof TransitStopVertex) {
            stopsFound.add(new StopAtDistance((TransitStopVertex) vertex, 0, Collections.emptyList(), null, new State(vertex, routingRequest)));
        }
    }
    if (removeTempEdges) {
        routingRequest.cleanup();
    }
    return stopsFound;
}
Also used : TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) Vertex(org.opentripplanner.routing.graph.Vertex) StreetVertex(org.opentripplanner.routing.vertextype.StreetVertex) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) State(org.opentripplanner.routing.core.State) TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) TrivialRemainingWeightHeuristic(org.opentripplanner.routing.algorithm.astar.strategies.TrivialRemainingWeightHeuristic) RoutingRequest(org.opentripplanner.routing.api.request.RoutingRequest) StopAtDistance(org.opentripplanner.routing.graphfinder.StopAtDistance) FlexStopLocation(org.opentripplanner.model.FlexStopLocation) StreetVertex(org.opentripplanner.routing.vertextype.StreetVertex) DominanceFunction(org.opentripplanner.routing.spt.DominanceFunction)

Example 2 with TransitStopVertex

use of org.opentripplanner.routing.vertextype.TransitStopVertex in project OpenTripPlanner by opentripplanner.

the class DirectTransferAnalyzer method buildGraph.

@Override
public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra, DataImportIssueStore issueStore) {
    /* Initialize graph index which is needed by the nearby stop finder. */
    graph.index = new GraphIndex(graph);
    LOG.info("Analyzing transfers (this can be time consuming)...");
    List<TransferInfo> directTransfersTooLong = new ArrayList<>();
    List<TransferInfo> directTransfersNotFound = new ArrayList<>();
    DirectGraphFinder nearbyStopFinderEuclidian = new DirectGraphFinder(graph);
    StreetGraphFinder nearbyStopFinderStreets = new StreetGraphFinder(graph);
    int stopsAnalyzed = 0;
    for (TransitStopVertex originStopVertex : Iterables.filter(graph.getVertices(), TransitStopVertex.class)) {
        if (++stopsAnalyzed % 1000 == 0) {
            LOG.info("{} stops analyzed", stopsAnalyzed);
        }
        /* Find nearby stops by euclidean distance */
        Coordinate c0 = originStopVertex.getCoordinate();
        Map<Stop, StopAtDistance> stopsEuclidean = nearbyStopFinderEuclidian.findClosestStops(c0.y, c0.x, radiusMeters).stream().filter(t -> t.stop instanceof Stop).collect(Collectors.toMap(t -> (Stop) t.stop, t -> t));
        /* Find nearby stops by street distance */
        Map<Stop, StopAtDistance> stopsStreets = nearbyStopFinderStreets.findClosestStops(c0.y, c0.x, radiusMeters * RADIUS_MULTIPLIER).stream().filter(t -> t.stop instanceof Stop).collect(Collectors.toMap(t -> (Stop) t.stop, t -> t));
        Stop originStop = originStopVertex.getStop();
        /* Get stops found by both street and euclidean search */
        List<Stop> stopsConnected = stopsEuclidean.keySet().stream().filter(t -> stopsStreets.keySet().contains(t) && t != originStop).collect(Collectors.toList());
        /* Get stops found by euclidean search but not street search */
        List<Stop> stopsUnconnected = stopsEuclidean.keySet().stream().filter(t -> !stopsStreets.keySet().contains(t) && t != originStop).collect(Collectors.toList());
        for (Stop destStop : stopsConnected) {
            StopAtDistance euclideanStop = stopsEuclidean.get(destStop);
            StopAtDistance streetStop = stopsStreets.get(destStop);
            TransferInfo transferInfo = new TransferInfo(originStop, destStop, euclideanStop.distance, streetStop.distance);
            /* Log transfer where the street distance is too long compared to the euclidean distance */
            if (transferInfo.ratio > MIN_RATIO_TO_LOG && transferInfo.streetDistance > MIN_STREET_DISTANCE_TO_LOG) {
                directTransfersTooLong.add(transferInfo);
            }
        }
        for (Stop destStop : stopsUnconnected) {
            StopAtDistance euclideanStop = stopsEuclidean.get(destStop);
            /* Log transfers that are found by euclidean search but not by street search */
            directTransfersNotFound.add(new TransferInfo(originStop, destStop, euclideanStop.distance, -1));
        }
    }
    /* Sort by street distance to euclidean distance ratio before adding to issues */
    directTransfersTooLong.sort(Comparator.comparingDouble(t -> t.ratio));
    Collections.reverse(directTransfersTooLong);
    for (TransferInfo transferInfo : directTransfersTooLong) {
        issueStore.add(new TransferRoutingDistanceTooLong(transferInfo.origin, transferInfo.destination, transferInfo.directDistance, transferInfo.streetDistance, transferInfo.ratio));
    }
    /* Sort by direct distance before adding to issues */
    directTransfersNotFound.sort(Comparator.comparingDouble(t -> t.directDistance));
    for (TransferInfo transferInfo : directTransfersNotFound) {
        issueStore.add(new TransferCouldNotBeRouted(transferInfo.origin, transferInfo.destination, transferInfo.directDistance));
    }
    LOG.info("Done analyzing transfers. {} transfers could not be routed and {} transfers had a too long routing" + " distance.", directTransfersNotFound.size(), directTransfersTooLong.size());
}
Also used : StopAtDistance(org.opentripplanner.routing.graphfinder.StopAtDistance) Iterables(com.google.common.collect.Iterables) Logger(org.slf4j.Logger) StreetGraphFinder(org.opentripplanner.routing.graphfinder.StreetGraphFinder) Stop(org.opentripplanner.model.Stop) TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) LoggerFactory(org.slf4j.LoggerFactory) Coordinate(org.locationtech.jts.geom.Coordinate) DirectGraphFinder(org.opentripplanner.routing.graphfinder.DirectGraphFinder) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) GraphIndex(org.opentripplanner.routing.graph.GraphIndex) TransferCouldNotBeRouted(org.opentripplanner.ext.transferanalyzer.annotations.TransferCouldNotBeRouted) List(java.util.List) GraphBuilderModule(org.opentripplanner.graph_builder.services.GraphBuilderModule) TransferRoutingDistanceTooLong(org.opentripplanner.ext.transferanalyzer.annotations.TransferRoutingDistanceTooLong) Graph(org.opentripplanner.routing.graph.Graph) Map(java.util.Map) DataImportIssueStore(org.opentripplanner.graph_builder.DataImportIssueStore) Comparator(java.util.Comparator) Collections(java.util.Collections) TransferRoutingDistanceTooLong(org.opentripplanner.ext.transferanalyzer.annotations.TransferRoutingDistanceTooLong) Stop(org.opentripplanner.model.Stop) ArrayList(java.util.ArrayList) StreetGraphFinder(org.opentripplanner.routing.graphfinder.StreetGraphFinder) Coordinate(org.locationtech.jts.geom.Coordinate) DirectGraphFinder(org.opentripplanner.routing.graphfinder.DirectGraphFinder) TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) GraphIndex(org.opentripplanner.routing.graph.GraphIndex) TransferCouldNotBeRouted(org.opentripplanner.ext.transferanalyzer.annotations.TransferCouldNotBeRouted) StopAtDistance(org.opentripplanner.routing.graphfinder.StopAtDistance)

Example 3 with TransitStopVertex

use of org.opentripplanner.routing.vertextype.TransitStopVertex in project OpenTripPlanner by opentripplanner.

the class Graph method calculateTransitCenter.

/**
 * Calculates Transit center from median of coordinates of all transitStops if graph
 * has transit. If it doesn't it isn't calculated. (mean walue of min, max latitude and longitudes are used)
 *
 * Transit center is saved in center variable
 *
 * This speeds up calculation, but problem is that median needs to have all of latitudes/longitudes
 * in memory, this can become problematic in large installations. It works without a problem on New York State.
 */
public void calculateTransitCenter() {
    if (hasTransit) {
        TDoubleList latitudes = new TDoubleLinkedList();
        TDoubleList longitudes = new TDoubleLinkedList();
        Median median = new Median();
        getVertices().stream().filter(v -> v instanceof TransitStopVertex).forEach(v -> {
            latitudes.add(v.getLat());
            longitudes.add(v.getLon());
        });
        median.setData(latitudes.toArray());
        double medianLatitude = median.evaluate();
        median = new Median();
        median.setData(longitudes.toArray());
        double medianLongitude = median.evaluate();
        this.center = new Coordinate(medianLongitude, medianLatitude);
    }
}
Also used : TDoubleList(gnu.trove.list.TDoubleList) TurnRestriction(org.opentripplanner.common.TurnRestriction) Trip(org.opentripplanner.model.Trip) Date(java.util.Date) MultiModalStation(org.opentripplanner.model.MultiModalStation) TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) LoggerFactory(org.slf4j.LoggerFactory) ObjectInputStream(java.io.ObjectInputStream) Coordinate(org.locationtech.jts.geom.Coordinate) NoFutureDates(org.opentripplanner.graph_builder.issues.NoFutureDates) CompactElevationProfile(org.opentripplanner.common.geometry.CompactElevationProfile) TransitLayerUpdater(org.opentripplanner.routing.algorithm.raptor.transit.mappers.TransitLayerUpdater) SphericalDistanceLibrary(org.opentripplanner.common.geometry.SphericalDistanceLibrary) ServiceDate(org.opentripplanner.model.calendar.ServiceDate) TransitLayer(org.opentripplanner.routing.algorithm.raptor.transit.TransitLayer) GraphUtils(org.opentripplanner.common.geometry.GraphUtils) HashMultimap(com.google.common.collect.HashMultimap) Median(org.apache.commons.math3.stat.descriptive.rank.Median) Map(java.util.Map) GroupOfStations(org.opentripplanner.model.GroupOfStations) TransitMode(org.opentripplanner.model.TransitMode) FeedScopedId(org.opentripplanner.model.FeedScopedId) BiMap(com.google.common.collect.BiMap) Station(org.opentripplanner.model.Station) MavenVersion(org.opentripplanner.common.MavenVersion) Operator(org.opentripplanner.model.Operator) TripPattern(org.opentripplanner.model.TripPattern) TimeZone(java.util.TimeZone) Stop(org.opentripplanner.model.Stop) TransferTable(org.opentripplanner.routing.core.TransferTable) StreetNotesService(org.opentripplanner.routing.services.notes.StreetNotesService) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Collectors(java.util.stream.Collectors) StopLocation(org.opentripplanner.model.StopLocation) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) FlexStopLocation(org.opentripplanner.model.FlexStopLocation) List(java.util.List) WgsCoordinate(org.opentripplanner.model.WgsCoordinate) Geometry(org.locationtech.jts.geom.Geometry) Optional(java.util.Optional) GraphUpdaterManager(org.opentripplanner.updater.GraphUpdaterManager) Iterables(com.google.common.collect.Iterables) T2(org.opentripplanner.common.model.T2) TransitAlertService(org.opentripplanner.routing.services.TransitAlertService) WorldEnvelope(org.opentripplanner.util.WorldEnvelope) TDoubleList(gnu.trove.list.TDoubleList) HashMap(java.util.HashMap) TimetableSnapshot(org.opentripplanner.model.TimetableSnapshot) Multimap(com.google.common.collect.Multimap) TDoubleLinkedList(gnu.trove.list.linked.TDoubleLinkedList) StreetEdge(org.opentripplanner.routing.edgetype.StreetEdge) Function(java.util.function.Function) CalendarServiceData(org.opentripplanner.model.calendar.CalendarServiceData) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) GraphUpdaterConfigurator(org.opentripplanner.updater.GraphUpdaterConfigurator) TransitEntity(org.opentripplanner.model.TransitEntity) DelegatingTransitAlertServiceImpl(org.opentripplanner.routing.impl.DelegatingTransitAlertServiceImpl) DataImportIssueStore(org.opentripplanner.graph_builder.DataImportIssueStore) EdgeWithCleanup(org.opentripplanner.routing.edgetype.EdgeWithCleanup) LinkedList(java.util.LinkedList) CalendarService(org.opentripplanner.model.calendar.CalendarService) CalendarServiceImpl(org.opentripplanner.model.calendar.impl.CalendarServiceImpl) Logger(org.slf4j.Logger) FlexLocationGroup(org.opentripplanner.model.FlexLocationGroup) GraphBundle(org.opentripplanner.model.GraphBundle) Notice(org.opentripplanner.model.Notice) IOException(java.io.IOException) Maps(com.google.common.collect.Maps) Agency(org.opentripplanner.model.Agency) Preferences(java.util.prefs.Preferences) HashBiMap(com.google.common.collect.HashBiMap) ConcurrentPublished(org.opentripplanner.routing.util.ConcurrentPublished) BikeRentalStationService(org.opentripplanner.routing.bike_rental.BikeRentalStationService) StreetVertexIndex(org.opentripplanner.routing.impl.StreetVertexIndex) FlexTrip(org.opentripplanner.ext.flex.trip.FlexTrip) SimpleTransfer(org.opentripplanner.model.SimpleTransfer) TimetableSnapshotProvider(org.opentripplanner.model.TimetableSnapshotProvider) Deduplicator(org.opentripplanner.routing.trippattern.Deduplicator) VisibleForTesting(com.google.common.annotations.VisibleForTesting) BitSet(java.util.BitSet) Envelope(org.locationtech.jts.geom.Envelope) Collections(java.util.Collections) FeedInfo(org.opentripplanner.model.FeedInfo) Coordinate(org.locationtech.jts.geom.Coordinate) WgsCoordinate(org.opentripplanner.model.WgsCoordinate) TDoubleLinkedList(gnu.trove.list.linked.TDoubleLinkedList) TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) Median(org.apache.commons.math3.stat.descriptive.rank.Median)

Example 4 with TransitStopVertex

use of org.opentripplanner.routing.vertextype.TransitStopVertex in project OpenTripPlanner by opentripplanner.

the class ShowGraph method drawVertices.

private void drawVertices() {
    /* turn off vertex display when zoomed out */
    final double METERS_PER_DEGREE_LAT = 111111.111111;
    boolean closeEnough = (modelBounds.getHeight() * METERS_PER_DEGREE_LAT / this.width < 5);
    /* Draw selected visible vertices */
    for (Vertex v : visibleVertices) {
        if (drawTransitStopVertices && closeEnough && v instanceof TransitStopVertex) {
            // Make transit stops blue dots
            fill(60, 60, 200);
            drawVertex(v, 7);
        }
        if (drawStreetVertices && v instanceof IntersectionVertex) {
            IntersectionVertex iv = (IntersectionVertex) v;
            if (iv.trafficLight) {
                // Make traffic lights red dots
                fill(120, 60, 60);
                drawVertex(v, 5);
            }
        }
        if (drawMultistateVertices && spt != null) {
            List<? extends State> states = spt.getStates(v);
            if (states != null) {
                fill(100, 60, 100);
                drawVertex(v, states.size() * 2);
            }
        }
    }
}
Also used : TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) Vertex(org.opentripplanner.routing.graph.Vertex) IntersectionVertex(org.opentripplanner.routing.vertextype.IntersectionVertex) TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) IntersectionVertex(org.opentripplanner.routing.vertextype.IntersectionVertex)

Example 5 with TransitStopVertex

use of org.opentripplanner.routing.vertextype.TransitStopVertex in project OpenTripPlanner by opentripplanner.

the class TestGeometryAndBlockProcessor method testRouting.

public void testRouting() throws Exception {
    Vertex stop_a = graph.getVertex(feedId + ":A");
    Vertex stop_b = graph.getVertex(feedId + ":B");
    Vertex stop_c = graph.getVertex(feedId + ":C");
    Vertex stop_d = graph.getVertex(feedId + ":D");
    Vertex stop_e = graph.getVertex(feedId + ":E");
    RoutingRequest options = new RoutingRequest();
    // test feed is designed for instantaneous transfers
    options.transferSlack = 0;
    long startTime = TestUtils.dateInSeconds("America/New_York", 2009, 8, 7, 0, 0, 0);
    options.dateTime = startTime;
    ShortestPathTree spt;
    GraphPath path;
    // A to B
    options.setRoutingContext(graph, stop_a, stop_b);
    spt = aStar.getShortestPathTree(options);
    path = spt.getPath(stop_b, false);
    assertNotNull(path);
    assertEquals(6, path.states.size());
    // A to C
    options.setRoutingContext(graph, stop_a, stop_c);
    spt = aStar.getShortestPathTree(options);
    path = spt.getPath(stop_c, false);
    assertNotNull(path);
    assertEquals(8, path.states.size());
    // A to D (change at C)
    options.setRoutingContext(graph, stop_a, stop_d);
    spt = aStar.getShortestPathTree(options);
    path = spt.getPath(stop_d, false);
    assertNotNull(path);
    // there are two paths of different lengths
    // both arrive at 40 minutes after midnight
    List<TransitStopVertex> stops = extractStopVertices(path);
    assertEquals(stops.size(), 3);
    assertEquals(stops.get(1), stop_c);
    long endTime = startTime + 40 * 60;
    assertEquals(endTime, path.getEndTime());
    // A to E (change at C)
    options.setRoutingContext(graph, stop_a, stop_e);
    spt = aStar.getShortestPathTree(options);
    path = spt.getPath(stop_e, false);
    assertNotNull(path);
    stops = extractStopVertices(path);
    assertEquals(stops.size(), 3);
    assertEquals(stops.get(1), stop_c);
    endTime = startTime + 70 * 60;
    assertEquals(endTime, path.getEndTime());
}
Also used : TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) Vertex(org.opentripplanner.routing.graph.Vertex) IntersectionVertex(org.opentripplanner.routing.vertextype.IntersectionVertex) ShortestPathTree(org.opentripplanner.routing.spt.ShortestPathTree) TransitStopVertex(org.opentripplanner.routing.vertextype.TransitStopVertex) GraphPath(org.opentripplanner.routing.spt.GraphPath) RoutingRequest(org.opentripplanner.routing.api.request.RoutingRequest)

Aggregations

TransitStopVertex (org.opentripplanner.routing.vertextype.TransitStopVertex)28 Stop (org.opentripplanner.model.Stop)12 Vertex (org.opentripplanner.routing.graph.Vertex)12 IntersectionVertex (org.opentripplanner.routing.vertextype.IntersectionVertex)8 StreetVertex (org.opentripplanner.routing.vertextype.StreetVertex)8 ArrayList (java.util.ArrayList)7 Coordinate (org.locationtech.jts.geom.Coordinate)7 Envelope (org.locationtech.jts.geom.Envelope)7 Graph (org.opentripplanner.routing.graph.Graph)7 LineString (org.locationtech.jts.geom.LineString)6 DataImportIssueStore (org.opentripplanner.graph_builder.DataImportIssueStore)5 StreetTransitLink (org.opentripplanner.routing.edgetype.StreetTransitLink)5 Iterables (com.google.common.collect.Iterables)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 StreetEdge (org.opentripplanner.routing.edgetype.StreetEdge)4 BikeRentalStationVertex (org.opentripplanner.routing.vertextype.BikeRentalStationVertex)4 SplitterVertex (org.opentripplanner.routing.vertextype.SplitterVertex)4 LinearLocation (org.locationtech.jts.linearref.LinearLocation)3 LocationIndexedLine (org.locationtech.jts.linearref.LocationIndexedLine)3