diff --git a/application/src/ext-test/java/org/opentripplanner/ext/flex/trip/ScheduledDeviatedTripIntegrationTest.java b/application/src/ext-test/java/org/opentripplanner/ext/flex/trip/ScheduledDeviatedTripIntegrationTest.java index 76b35b34875..95124690877 100644 --- a/application/src/ext-test/java/org/opentripplanner/ext/flex/trip/ScheduledDeviatedTripIntegrationTest.java +++ b/application/src/ext-test/java/org/opentripplanner/ext/flex/trip/ScheduledDeviatedTripIntegrationTest.java @@ -18,15 +18,19 @@ import org.opentripplanner.ext.flex.FlexIntegrationTestData; import org.opentripplanner.framework.geometry.EncodedPolyline; import org.opentripplanner.graph_builder.module.ValidateAndInterpolateStopTimesForEachTrip; +import org.opentripplanner.graph_builder.module.linking.TestVertexLinker; import org.opentripplanner.model.GenericLocation; import org.opentripplanner.model.StopTime; import org.opentripplanner.model.plan.Itinerary; import org.opentripplanner.routing.algorithm.raptoradapter.router.AdditionalSearchDays; import org.opentripplanner.routing.algorithm.raptoradapter.router.TransitRouter; import org.opentripplanner.routing.api.request.RouteRequest; +import org.opentripplanner.routing.api.request.StreetMode; import org.opentripplanner.routing.framework.DebugTimingAggregator; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.standalone.api.OtpServerRequestContext; +import org.opentripplanner.street.search.LinkingContext; +import org.opentripplanner.street.search.TemporaryVerticesContainer; import org.opentripplanner.transit.model.framework.FeedScopedId; import org.opentripplanner.transit.model.network.grouppriority.TransitGroupPriorityService; import org.opentripplanner.transit.service.TimetableRepository; @@ -167,16 +171,28 @@ private static List getItineraries( var transitStartOfTime = ServiceDateUtils.asStartOfService(request.dateTime(), zoneId); var additionalSearchDays = AdditionalSearchDays.defaults(dateTime); - var result = TransitRouter.route( - request, - serverContext, - TransitGroupPriorityService.empty(), - transitStartOfTime, - additionalSearchDays, - new DebugTimingAggregator() - ); - return result.getItineraries(); + try (var temporaryVerticesContainer = new TemporaryVerticesContainer()) { + var linkingContext = LinkingContext.of( + temporaryVerticesContainer, + serverContext.graph(), + TestVertexLinker.of(graph) + ) + .withFrom(from, StreetMode.WALK) + .withTo(to, StreetMode.WALK) + .build(); + var result = TransitRouter.route( + request, + serverContext, + TransitGroupPriorityService.empty(), + transitStartOfTime, + additionalSearchDays, + new DebugTimingAggregator(), + linkingContext.createFromToViaVertexRequest() + ); + + return result.getItineraries(); + } } private static FlexTrip getFlexTrip() { diff --git a/application/src/main/java/org/opentripplanner/apis/gtfs/GraphQLUtils.java b/application/src/main/java/org/opentripplanner/apis/gtfs/GraphQLUtils.java index fe363ee394d..a8d7a20e6b1 100644 --- a/application/src/main/java/org/opentripplanner/apis/gtfs/GraphQLUtils.java +++ b/application/src/main/java/org/opentripplanner/apis/gtfs/GraphQLUtils.java @@ -45,7 +45,8 @@ public static GraphQLInputField toGraphQL(InputField inputField) { return switch (inputField) { case DATE_TIME -> GraphQLInputField.DATE_TIME; case FROM_PLACE -> GraphQLInputField.FROM; - case TO_PLACE, INTERMEDIATE_PLACE -> GraphQLInputField.TO; + case TO_PLACE -> GraphQLInputField.TO; + case INTERMEDIATE_PLACE -> GraphQLInputField.VIA; }; } diff --git a/application/src/main/java/org/opentripplanner/apis/gtfs/generated/GraphQLTypes.java b/application/src/main/java/org/opentripplanner/apis/gtfs/generated/GraphQLTypes.java index 55b67cf06b1..7b65ce1f2f7 100644 --- a/application/src/main/java/org/opentripplanner/apis/gtfs/generated/GraphQLTypes.java +++ b/application/src/main/java/org/opentripplanner/apis/gtfs/generated/GraphQLTypes.java @@ -1007,6 +1007,7 @@ public enum GraphQLInputField { DATE_TIME, FROM, TO, + VIA, } public static class GraphQLInputFiltersInput { diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/RoutingWorker.java b/application/src/main/java/org/opentripplanner/routing/algorithm/RoutingWorker.java index 988d11710d0..a97944fe424 100644 --- a/application/src/main/java/org/opentripplanner/routing/algorithm/RoutingWorker.java +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/RoutingWorker.java @@ -4,6 +4,7 @@ import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; +import java.util.EnumSet; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -32,6 +33,9 @@ import org.opentripplanner.routing.framework.DebugTimingAggregator; import org.opentripplanner.service.paging.PagingService; import org.opentripplanner.standalone.api.OtpServerRequestContext; +import org.opentripplanner.street.search.LinkingContext; +import org.opentripplanner.street.search.TemporaryVerticesContainer; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; import org.opentripplanner.transit.model.network.grouppriority.TransitGroupPriorityService; import org.opentripplanner.utils.time.ServiceDateUtils; import org.slf4j.Logger; @@ -97,20 +101,31 @@ public RoutingResponse route() { var result = RoutingResult.empty(); - if (OTPFeature.ParallelRouting.isOn()) { - // TODO: This is not using {@link OtpRequestThreadFactory} which means we do not get - // log-trace-parameters-propagation and graceful timeout handling here. - try { - var r1 = CompletableFuture.supplyAsync(this::routeDirectStreet); - var r2 = CompletableFuture.supplyAsync(this::routeDirectFlex); - var r3 = CompletableFuture.supplyAsync(this::routeTransit); - - result.merge(r1.join(), r2.join(), r3.join()); - } catch (CompletionException e) { - RoutingValidationException.unwrapAndRethrowCompletionException(e); + try (var temporaryVerticesContainer = new TemporaryVerticesContainer()) { + var linkingContextBuilder = createTemporaryVerticesContainer(temporaryVerticesContainer); + var requestVertexService = linkingContextBuilder.createFromToViaVertexRequest(); + + if (OTPFeature.ParallelRouting.isOn()) { + // TODO: This is not using {@link OtpRequestThreadFactory} which means we do not get + // log-trace-parameters-propagation and graceful timeout handling here. + try { + var r1 = CompletableFuture.supplyAsync(() -> routeDirectStreet(requestVertexService)); + var r2 = CompletableFuture.supplyAsync(() -> routeDirectFlex(requestVertexService)); + var r3 = CompletableFuture.supplyAsync(() -> routeTransit(requestVertexService)); + + result.merge(r1.join(), r2.join(), r3.join()); + } catch (CompletionException e) { + RoutingValidationException.unwrapAndRethrowCompletionException(e); + } + } else { + result.merge( + routeDirectStreet(requestVertexService), + routeDirectFlex(requestVertexService), + routeTransit(requestVertexService) + ); } - } else { - result.merge(routeDirectStreet(), routeDirectFlex(), routeTransit()); + } catch (RoutingValidationException e) { + result.merge(RoutingResult.failed(e.getRoutingErrors())); } // Set C2 value for Street and FLEX if transit-group-priority is used @@ -208,7 +223,7 @@ private Duration searchWindowUsed() { : Duration.ofSeconds(raptorSearchParamsUsed.searchWindowInSeconds()); } - private RoutingResult routeDirectStreet() { + private RoutingResult routeDirectStreet(FromToViaVertexRequest fromToViaVertexRequest) { // TODO: Add support for via search to the direct-street search and remove this. // The direct search is used to prune away silly transit results and it // would be nice to also support via as a feature in the direct-street @@ -232,31 +247,33 @@ private RoutingResult routeDirectStreet() { debugTimingAggregator.startedDirectStreetRouter(); try { return RoutingResult.ok( - DirectStreetRouter.route(serverContext, directBuilder.buildRequest()), + DirectStreetRouter.route( + serverContext, + directBuilder.buildRequest(), + fromToViaVertexRequest + ), emptyDirectModeHandler.removeWalkAllTheWayResults() ); - } catch (RoutingValidationException e) { - return RoutingResult.failed(e.getRoutingErrors()); } finally { debugTimingAggregator.finishedDirectStreetRouter(); } } - private RoutingResult routeDirectFlex() { + private RoutingResult routeDirectFlex(FromToViaVertexRequest fromToViaVertexRequest) { if (!OTPFeature.FlexRouting.isOn()) { return RoutingResult.ok(List.of()); } debugTimingAggregator.startedDirectFlexRouter(); try { - return RoutingResult.ok(DirectFlexRouter.route(serverContext, request, additionalSearchDays)); - } catch (RoutingValidationException e) { - return RoutingResult.failed(e.getRoutingErrors()); + return RoutingResult.ok( + DirectFlexRouter.route(serverContext, request, additionalSearchDays, fromToViaVertexRequest) + ); } finally { debugTimingAggregator.finishedDirectFlexRouter(); } } - private RoutingResult routeTransit() { + private RoutingResult routeTransit(FromToViaVertexRequest fromToViaVertexRequest) { debugTimingAggregator.startedTransitRouting(); try { var transitResults = TransitRouter.route( @@ -265,12 +282,11 @@ private RoutingResult routeTransit() { transitGroupPriorityService, transitSearchTimeZero, additionalSearchDays, - debugTimingAggregator + debugTimingAggregator, + fromToViaVertexRequest ); raptorSearchParamsUsed = transitResults.getSearchParams(); return RoutingResult.ok(transitResults.getItineraries()); - } catch (RoutingValidationException e) { - return RoutingResult.failed(e.getRoutingErrors()); } finally { debugTimingAggregator.finishedTransitRouter(); } @@ -291,4 +307,44 @@ private PagingService createPagingService(List itineraries) { itineraries ); } + + private LinkingContext createTemporaryVerticesContainer(TemporaryVerticesContainer container) { + var fromModes = request.journey().transit().enabled() + ? EnumSet.of(request.journey().access().mode()) + : EnumSet.noneOf(StreetMode.class); + var toModes = request.journey().transit().enabled() + ? EnumSet.of(request.journey().egress().mode()) + : EnumSet.noneOf(StreetMode.class); + var viaModes = request.journey().transit().enabled() + ? EnumSet.of( + request.journey().access().mode(), + request.journey().egress().mode(), + request.journey().transfer().mode() + ) + : EnumSet.noneOf(StreetMode.class); + var directMode = resolveDirectMode(); + if (directMode != StreetMode.NOT_SET) { + fromModes.add(directMode); + toModes.add(directMode); + viaModes.add(directMode); + } + return LinkingContext.of( + container, + serverContext.graph(), + serverContext.vertexLinker(), + serverContext.transitService()::findStopOrChildIds + ) + .withFrom(request.from(), fromModes) + .withTo(request.to(), toModes) + .withVia(request.listVisitViaLocations(), viaModes) + .build(); + } + + private StreetMode resolveDirectMode() { + var emptyDirectModeHandler = new FilterTransitWhenDirectModeIsEmpty( + request.journey().direct().mode(), + request.pageCursor() != null + ); + return emptyDirectModeHandler.resolveDirectMode(); + } } diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/TransitRouter.java b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/TransitRouter.java index 9d0d3685b88..e4cc916e021 100644 --- a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/TransitRouter.java +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/TransitRouter.java @@ -44,7 +44,7 @@ import org.opentripplanner.routing.framework.DebugTimingAggregator; import org.opentripplanner.routing.via.ViaCoordinateTransferFactory; import org.opentripplanner.standalone.api.OtpServerRequestContext; -import org.opentripplanner.street.search.TemporaryVerticesContainer; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; import org.opentripplanner.transit.model.framework.EntityNotFoundException; import org.opentripplanner.transit.model.framework.FeedScopedId; import org.opentripplanner.transit.model.network.grouppriority.TransitGroupPriorityService; @@ -60,8 +60,8 @@ public class TransitRouter { private final DebugTimingAggregator debugTimingAggregator; private final ZonedDateTime transitSearchTimeZero; private final AdditionalSearchDays additionalSearchDays; - private final TemporaryVerticesContainer temporaryVerticesContainer; private final ViaCoordinateTransferFactory viaTransferResolver; + private final FromToViaVertexRequest fromToViaVertexRequest; private TransitRouter( RouteRequest request, @@ -69,7 +69,8 @@ private TransitRouter( TransitGroupPriorityService transitGroupPriorityService, ZonedDateTime transitSearchTimeZero, AdditionalSearchDays additionalSearchDays, - DebugTimingAggregator debugTimingAggregator + DebugTimingAggregator debugTimingAggregator, + FromToViaVertexRequest fromToViaVertexRequest ) { this.request = request; this.serverContext = serverContext; @@ -77,8 +78,8 @@ private TransitRouter( this.transitSearchTimeZero = transitSearchTimeZero; this.additionalSearchDays = additionalSearchDays; this.debugTimingAggregator = debugTimingAggregator; - this.temporaryVerticesContainer = createTemporaryVerticesContainer(request, serverContext); this.viaTransferResolver = serverContext.viaTransferResolver(); + this.fromToViaVertexRequest = fromToViaVertexRequest; } public static TransitRouterResult route( @@ -87,7 +88,8 @@ public static TransitRouterResult route( TransitGroupPriorityService priorityGroupConfigurator, ZonedDateTime transitSearchTimeZero, AdditionalSearchDays additionalSearchDays, - DebugTimingAggregator debugTimingAggregator + DebugTimingAggregator debugTimingAggregator, + FromToViaVertexRequest fromToViaVertexRequest ) { TransitRouter transitRouter = new TransitRouter( request, @@ -95,18 +97,11 @@ public static TransitRouterResult route( priorityGroupConfigurator, transitSearchTimeZero, additionalSearchDays, - debugTimingAggregator + debugTimingAggregator, + fromToViaVertexRequest ); - return transitRouter.routeAndCleanupAfter(); - } - - private TransitRouterResult routeAndCleanupAfter() { - // try(auto-close): - // Make sure we clean up graph by removing temp-edges from the graph before we exit. - try (temporaryVerticesContainer) { - return route(); - } + return transitRouter.route(); } private TransitRouterResult route() { @@ -144,7 +139,8 @@ private TransitRouterResult route() { accessEgresses.getEgresses(), serverContext.meterRegistry(), viaTransferResolver, - this::listStopIndexes + this::listStopIndexes, + fromToViaVertexRequest ); // Route transit @@ -272,12 +268,12 @@ private Collection fetchAccessEgresses(AccessEgre var nearbyStops = AccessEgressRouter.findAccessEgresses( accessRequest, - temporaryVerticesContainer, streetRequest, serverContext.dataOverlayContext(accessRequest), type, durationLimit, - stopCountLimit + stopCountLimit, + fromToViaVertexRequest ); var accessEgresses = AccessEgressMapper.mapNearbyStops(nearbyStops, type); accessEgresses = timeshiftRideHailing(streetRequest, type, accessEgresses); @@ -288,12 +284,12 @@ private Collection fetchAccessEgresses(AccessEgre if (OTPFeature.FlexRouting.isOn() && mode == StreetMode.FLEXIBLE) { var flexAccessList = FlexAccessEgressRouter.routeAccessEgress( accessRequest, - temporaryVerticesContainer, serverContext, additionalSearchDays, serverContext.flexParameters(), serverContext.dataOverlayContext(accessRequest), - type + type, + fromToViaVertexRequest ); results.addAll(AccessEgressMapper.mapFlexAccessEgresses(flexAccessList, type)); @@ -375,21 +371,6 @@ private void checkIfTransitConnectionExists(RaptorResponse respons } } - private TemporaryVerticesContainer createTemporaryVerticesContainer( - RouteRequest request, - OtpServerRequestContext serverContext - ) { - return new TemporaryVerticesContainer( - serverContext.graph(), - serverContext.vertexLinker(), - serverContext.transitService()::findStopOrChildIds, - request.from(), - request.to(), - request.journey().access().mode(), - request.journey().egress().mode() - ); - } - private IntStream listStopIndexes(FeedScopedId stopLocationId) { Collection stops = serverContext .transitService() diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/AccessEgressRouter.java b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/AccessEgressRouter.java index 54014a8cb8e..2e3e0c61d08 100644 --- a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/AccessEgressRouter.java +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/AccessEgressRouter.java @@ -11,7 +11,7 @@ import org.opentripplanner.routing.api.request.RouteRequest; import org.opentripplanner.routing.api.request.request.StreetRequest; import org.opentripplanner.routing.graphfinder.NearbyStop; -import org.opentripplanner.street.search.TemporaryVerticesContainer; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; import org.opentripplanner.utils.collection.ListUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,12 +30,12 @@ private AccessEgressRouter() {} */ public static Collection findAccessEgresses( RouteRequest request, - TemporaryVerticesContainer verticesContainer, StreetRequest streetRequest, @Nullable DataOverlayContext dataOverlayContext, AccessEgressType accessOrEgress, Duration durationLimit, - int maxStopCount + int maxStopCount, + FromToViaVertexRequest fromToViaVertexRequest ) { OTPRequestTimeoutException.checkForTimeout(); @@ -43,10 +43,10 @@ public static Collection findAccessEgresses( // Then we do street search. This is because some stations might use the centroid for street // routing, but should still give zero distance access/egresses to its child-stops. var zeroDistanceAccessEgress = findAccessEgressWithZeroDistance( - verticesContainer, request, streetRequest, - accessOrEgress + accessOrEgress, + fromToViaVertexRequest ); // When looking for street accesses/egresses we ignore the already found direct accesses/egresses @@ -56,8 +56,8 @@ public static Collection findAccessEgresses( .collect(Collectors.toSet()); var originVertices = accessOrEgress.isAccess() - ? verticesContainer.getFromVertices() - : verticesContainer.getToVertices(); + ? fromToViaVertexRequest.findVertices(request.from()) + : fromToViaVertexRequest.findVertices(request.to()); var streetAccessEgress = new StreetNearbyStopFinder( durationLimit, maxStopCount, @@ -75,14 +75,14 @@ public static Collection findAccessEgresses( * return an empty list if the source/destination is not a stopId. */ private static List findAccessEgressWithZeroDistance( - TemporaryVerticesContainer verticesContainer, RouteRequest routeRequest, StreetRequest streetRequest, - AccessEgressType accessOrEgress + AccessEgressType accessOrEgress, + FromToViaVertexRequest fromToViaVertexRequest ) { var transitStopVertices = accessOrEgress.isAccess() - ? verticesContainer.getFromStopVertices() - : verticesContainer.getToStopVertices(); + ? fromToViaVertexRequest.fromStops() + : fromToViaVertexRequest.toStops(); return NearbyStop.nearbyStopsForTransitStopVerticesFiltered( transitStopVertices, diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/DirectFlexRouter.java b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/DirectFlexRouter.java index 28e37d4a35d..13ab399c866 100644 --- a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/DirectFlexRouter.java +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/DirectFlexRouter.java @@ -13,64 +13,53 @@ import org.opentripplanner.routing.api.request.StreetMode; import org.opentripplanner.routing.graphfinder.NearbyStop; import org.opentripplanner.standalone.api.OtpServerRequestContext; -import org.opentripplanner.street.search.TemporaryVerticesContainer; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; public class DirectFlexRouter { public static List route( OtpServerRequestContext serverContext, RouteRequest request, - AdditionalSearchDays additionalSearchDays + AdditionalSearchDays additionalSearchDays, + FromToViaVertexRequest fromToViaVertexRequest ) { if (!StreetMode.FLEXIBLE.equals(request.journey().direct().mode())) { return Collections.emptyList(); } OTPRequestTimeoutException.checkForTimeout(); - try ( - var temporaryVertices = new TemporaryVerticesContainer( - serverContext.graph(), - serverContext.vertexLinker(), - serverContext.transitService()::findStopOrChildIds, - request.from(), - request.to(), - request.journey().direct().mode(), - request.journey().direct().mode() - ) - ) { - // Prepare access/egress transfers - Collection accessStops = AccessEgressRouter.findAccessEgresses( - request, - temporaryVertices, - request.journey().direct(), - serverContext.dataOverlayContext(request), - AccessEgressType.ACCESS, - serverContext.flexParameters().maxAccessWalkDuration(), - 0 - ); - Collection egressStops = AccessEgressRouter.findAccessEgresses( - request, - temporaryVertices, - request.journey().direct(), - serverContext.dataOverlayContext(request), - AccessEgressType.EGRESS, - serverContext.flexParameters().maxEgressWalkDuration(), - 0 - ); + // Prepare access/egress transfers + Collection accessStops = AccessEgressRouter.findAccessEgresses( + request, + request.journey().direct(), + serverContext.dataOverlayContext(request), + AccessEgressType.ACCESS, + serverContext.flexParameters().maxAccessWalkDuration(), + 0, + fromToViaVertexRequest + ); + Collection egressStops = AccessEgressRouter.findAccessEgresses( + request, + request.journey().direct(), + serverContext.dataOverlayContext(request), + AccessEgressType.EGRESS, + serverContext.flexParameters().maxEgressWalkDuration(), + 0, + fromToViaVertexRequest + ); - var flexRouter = new FlexRouter( - serverContext.graph(), - serverContext.transitService(), - serverContext.flexParameters(), - FilterMapper.map(request.journey().transit().filters()), - request.dateTime(), - request.bookingTime(), - additionalSearchDays.additionalSearchDaysInPast(), - additionalSearchDays.additionalSearchDaysInFuture(), - accessStops, - egressStops - ); + var flexRouter = new FlexRouter( + serverContext.graph(), + serverContext.transitService(), + serverContext.flexParameters(), + FilterMapper.map(request.journey().transit().filters()), + request.dateTime(), + request.bookingTime(), + additionalSearchDays.additionalSearchDaysInPast(), + additionalSearchDays.additionalSearchDaysInFuture(), + accessStops, + egressStops + ); - return new ArrayList<>(flexRouter.createFlexOnlyItineraries(request.arriveBy())); - } + return new ArrayList<>(flexRouter.createFlexOnlyItineraries(request.arriveBy())); } } diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/DirectStreetRouter.java b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/DirectStreetRouter.java index 1eba7f9bc5b..35ddc8758e8 100644 --- a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/DirectStreetRouter.java +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/DirectStreetRouter.java @@ -15,7 +15,7 @@ import org.opentripplanner.standalone.api.OtpServerRequestContext; import org.opentripplanner.street.model.edge.Edge; import org.opentripplanner.street.model.vertex.Vertex; -import org.opentripplanner.street.search.TemporaryVerticesContainer; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; import org.opentripplanner.street.search.state.State; /** @@ -26,25 +26,18 @@ */ public class DirectStreetRouter { - public static List route(OtpServerRequestContext serverContext, RouteRequest request) { + public static List route( + OtpServerRequestContext serverContext, + RouteRequest request, + FromToViaVertexRequest fromToViaVertexRequest + ) { if (request.journey().direct().mode() == StreetMode.NOT_SET) { return Collections.emptyList(); } OTPRequestTimeoutException.checkForTimeout(); - - try ( - var temporaryVertices = new TemporaryVerticesContainer( - serverContext.graph(), - serverContext.vertexLinker(), - serverContext.transitService()::findStopOrChildIds, - request.from(), - request.to(), - request.journey().direct().mode(), - request.journey().direct().mode() - ) - ) { + try { var maxCarSpeed = serverContext.streetLimitationParametersService().getMaxCarSpeed(); - if (!straightLineDistanceIsWithinLimit(request, temporaryVertices, maxCarSpeed)) { + if (!straightLineDistanceIsWithinLimit(request, maxCarSpeed, fromToViaVertexRequest)) { return Collections.emptyList(); } @@ -56,7 +49,7 @@ public static List route(OtpServerRequestContext serverContext, Route ); List> paths = gpFinder.graphPathFinderEntryPoint( request, - temporaryVertices + fromToViaVertexRequest ); // Convert the internal GraphPaths to itineraries @@ -79,14 +72,14 @@ public static List route(OtpServerRequestContext serverContext, Route private static boolean straightLineDistanceIsWithinLimit( RouteRequest request, - TemporaryVerticesContainer vertexContainer, - float maxCarSpeed + float maxCarSpeed, + FromToViaVertexRequest fromToViaVertexRequest ) { // TODO This currently only calculates the distances between the first fromVertex // and the first toVertex double distance = SphericalDistanceLibrary.distance( - vertexContainer.getFromVertices().iterator().next().getCoordinate(), - vertexContainer.getToVertices().iterator().next().getCoordinate() + fromToViaVertexRequest.findVertices(request.from()).iterator().next().getCoordinate(), + fromToViaVertexRequest.findVertices(request.to()).iterator().next().getCoordinate() ); return distance < calculateDistanceMaxLimit(request, maxCarSpeed); } diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/FlexAccessEgressRouter.java b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/FlexAccessEgressRouter.java index ac55a9f5d47..b6d4af69801 100644 --- a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/FlexAccessEgressRouter.java +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/FlexAccessEgressRouter.java @@ -14,7 +14,7 @@ import org.opentripplanner.routing.api.request.request.StreetRequest; import org.opentripplanner.routing.graphfinder.NearbyStop; import org.opentripplanner.standalone.api.OtpServerRequestContext; -import org.opentripplanner.street.search.TemporaryVerticesContainer; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; import org.opentripplanner.transit.service.TransitService; public class FlexAccessEgressRouter { @@ -23,12 +23,12 @@ private FlexAccessEgressRouter() {} public static Collection routeAccessEgress( RouteRequest request, - TemporaryVerticesContainer verticesContainer, OtpServerRequestContext serverContext, AdditionalSearchDays searchDays, FlexParameters config, DataOverlayContext dataOverlayContext, - AccessEgressType accessOrEgress + AccessEgressType accessOrEgress, + FromToViaVertexRequest fromToViaVertexRequest ) { OTPRequestTimeoutException.checkForTimeout(); @@ -37,24 +37,24 @@ public static Collection routeAccessEgress( Collection accessStops = accessOrEgress.isAccess() ? AccessEgressRouter.findAccessEgresses( request, - verticesContainer, new StreetRequest(StreetMode.WALK), dataOverlayContext, AccessEgressType.ACCESS, serverContext.flexParameters().maxAccessWalkDuration(), - 0 + 0, + fromToViaVertexRequest ) : List.of(); Collection egressStops = accessOrEgress.isEgress() ? AccessEgressRouter.findAccessEgresses( request, - verticesContainer, new StreetRequest(StreetMode.WALK), dataOverlayContext, AccessEgressType.EGRESS, serverContext.flexParameters().maxEgressWalkDuration(), - 0 + 0, + fromToViaVertexRequest ) : List.of(); diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/mappers/RaptorRequestMapper.java b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/mappers/RaptorRequestMapper.java index 6c3d118fe72..125db058571 100644 --- a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/mappers/RaptorRequestMapper.java +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/mappers/RaptorRequestMapper.java @@ -31,11 +31,17 @@ import org.opentripplanner.routing.api.request.framework.CostLinearFunction; import org.opentripplanner.routing.api.request.preference.TransitPreferences; import org.opentripplanner.routing.api.request.via.ViaLocation; +import org.opentripplanner.routing.api.request.via.VisitViaLocation; import org.opentripplanner.routing.via.ViaCoordinateTransferFactory; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; import org.opentripplanner.transit.model.network.grouppriority.DefaultTransitGroupPriorityCalculator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class RaptorRequestMapper { + private static final Logger LOG = LoggerFactory.getLogger(RaptorRequestMapper.class); + private final RouteRequest request; private final Collection accessPaths; private final Collection egressPaths; @@ -44,6 +50,7 @@ public class RaptorRequestMapper { private final MeterRegistry meterRegistry; private final ViaCoordinateTransferFactory viaTransferResolver; private final LookupStopIndexCallback lookUpStopIndex; + private final FromToViaVertexRequest fromToViaVertexRequest; private RaptorRequestMapper( RouteRequest request, @@ -53,7 +60,8 @@ private RaptorRequestMapper( long transitSearchTimeZeroEpocSecond, @Nullable MeterRegistry meterRegistry, ViaCoordinateTransferFactory viaTransferResolver, - LookupStopIndexCallback lookUpStopIndex + LookupStopIndexCallback lookUpStopIndex, + FromToViaVertexRequest fromToViaVertexRequest ) { this.request = Objects.requireNonNull(request); this.isMultiThreadedEnbled = isMultiThreaded; @@ -63,6 +71,7 @@ private RaptorRequestMapper( this.meterRegistry = meterRegistry; this.viaTransferResolver = Objects.requireNonNull(viaTransferResolver); this.lookUpStopIndex = Objects.requireNonNull(lookUpStopIndex); + this.fromToViaVertexRequest = Objects.requireNonNull(fromToViaVertexRequest); } public static RaptorRequest mapRequest( @@ -73,7 +82,8 @@ public static RaptorRequest mapRequest( Collection egressPaths, MeterRegistry meterRegistry, ViaCoordinateTransferFactory viaTransferResolver, - LookupStopIndexCallback lookUpStopIndex + LookupStopIndexCallback lookUpStopIndex, + FromToViaVertexRequest fromToViaVertexRequest ) { return new RaptorRequestMapper( request, @@ -83,7 +93,8 @@ public static RaptorRequest mapRequest( transitSearchTimeZero.toEpochSecond(), meterRegistry, viaTransferResolver, - lookUpStopIndex + lookUpStopIndex, + fromToViaVertexRequest ).doMap(); } @@ -205,19 +216,19 @@ private RaptorRequest doMap() { private boolean hasPassThroughOnly() { return ( request.isViaSearch() && - request.getViaLocations().stream().allMatch(ViaLocation::isPassThroughLocation) + request.listViaLocations().stream().allMatch(ViaLocation::isPassThroughLocation) ); } private boolean hasViaLocationsOnly() { return ( request.isViaSearch() && - request.getViaLocations().stream().noneMatch(ViaLocation::isPassThroughLocation) + request.listViaLocations().stream().noneMatch(ViaLocation::isPassThroughLocation) ); } private boolean hasViaLocationsAndPassThroughLocations() { - var c = request.getViaLocations(); + var c = request.listViaLocations(); return ( request.isViaSearch() && c.stream().anyMatch(ViaLocation::isPassThroughLocation) && @@ -226,7 +237,7 @@ private boolean hasViaLocationsAndPassThroughLocations() { } private List mapViaLocations() { - return request.getViaLocations().stream().map(this::mapViaLocation).toList(); + return request.listViaLocations().stream().map(this::mapViaLocation).toList(); } private RaptorViaLocation mapViaLocation(ViaLocation input) { @@ -246,19 +257,27 @@ private RaptorViaLocation mapViaLocation(ViaLocation input) { viaStops.add(stopIndex); } for (var coordinate : input.coordinates()) { - var viaTransfers = viaTransferResolver.createViaTransfers( - request, - input.label(), - coordinate + var vertices = fromToViaVertexRequest.findVertices( + ((VisitViaLocation) input).coordinateLocation() ); - for (var it : viaTransfers) { - // If via-stop and via-transfers are used together then walking from a stop - // to the coordinate and back is not pareto optimal, using just the stop - // is the optimal option. - if (it.stop() == it.fromStopIndex() && viaStops.contains(it.stop())) { - continue; + if (vertices.isEmpty()) { + LOG.warn( + "Found no vertices for the visit via location {} which indicates a problem.", + input + ); + continue; + } + for (var vertex : vertices) { + var viaTransfers = viaTransferResolver.createViaTransfers(request, vertex, coordinate); + for (var it : viaTransfers) { + // If via-stop and via-transfers are used together then walking from a stop + // to the coordinate and back is not pareto optimal, using just the stop + // is the optimal option. + if (it.stop() == it.fromStopIndex() && viaStops.contains(it.stop())) { + continue; + } + builder.addViaTransfer(it.fromStopIndex(), it); } - builder.addViaTransfer(it.fromStopIndex(), it); } } return builder.build(); diff --git a/application/src/main/java/org/opentripplanner/routing/api/request/RouteRequest.java b/application/src/main/java/org/opentripplanner/routing/api/request/RouteRequest.java index dd287133147..acb4df8315d 100644 --- a/application/src/main/java/org/opentripplanner/routing/api/request/RouteRequest.java +++ b/application/src/main/java/org/opentripplanner/routing/api/request/RouteRequest.java @@ -17,6 +17,7 @@ import org.opentripplanner.routing.api.request.preference.RoutingPreferences; import org.opentripplanner.routing.api.request.request.JourneyRequest; import org.opentripplanner.routing.api.request.via.ViaLocation; +import org.opentripplanner.routing.api.request.via.VisitViaLocation; import org.opentripplanner.routing.api.response.InputField; import org.opentripplanner.routing.api.response.RoutingError; import org.opentripplanner.routing.api.response.RoutingErrorCode; @@ -292,10 +293,21 @@ public boolean isViaSearch() { return !via.isEmpty(); } - public List getViaLocations() { + public List listViaLocations() { return via; } + /** + * Return the via locations that are of type {@link VisitViaLocation}. + */ + public List listVisitViaLocations() { + return via + .stream() + .filter(VisitViaLocation.class::isInstance) + .map(VisitViaLocation.class::cast) + .toList(); + } + /** * This is the time/duration in seconds from the earliest-departure-time(EDT) to * latest-departure-time(LDT). In case of a reverse search, it will be the time from earliest to diff --git a/application/src/main/java/org/opentripplanner/routing/api/request/RouteRequestBuilder.java b/application/src/main/java/org/opentripplanner/routing/api/request/RouteRequestBuilder.java index 8518e12eb93..09f2c0924bc 100644 --- a/application/src/main/java/org/opentripplanner/routing/api/request/RouteRequestBuilder.java +++ b/application/src/main/java/org/opentripplanner/routing/api/request/RouteRequestBuilder.java @@ -49,7 +49,7 @@ public RouteRequestBuilder(RouteRequest original) { this.original = original; this.from = original.from(); this.to = original.to(); - this.via = original.getViaLocations(); + this.via = original.listViaLocations(); this.dateTime = original.dateTime(); this.arriveBy = original.arriveBy(); this.timetableView = original.timetableView(); diff --git a/application/src/main/java/org/opentripplanner/routing/api/request/via/VisitViaLocation.java b/application/src/main/java/org/opentripplanner/routing/api/request/via/VisitViaLocation.java index ae8c82de38a..57d4d8a20d5 100644 --- a/application/src/main/java/org/opentripplanner/routing/api/request/via/VisitViaLocation.java +++ b/application/src/main/java/org/opentripplanner/routing/api/request/via/VisitViaLocation.java @@ -5,6 +5,7 @@ import java.util.Objects; import javax.annotation.Nullable; import org.opentripplanner.framework.geometry.WgsCoordinate; +import org.opentripplanner.model.GenericLocation; import org.opentripplanner.transit.model.framework.FeedScopedId; import org.opentripplanner.utils.time.DurationUtils; import org.opentripplanner.utils.tostring.ToStringBuilder; @@ -44,6 +45,20 @@ public VisitViaLocation( } } + /** + * Returns the location's coordinate as a {@link GenericLocation}. {@code null} is returned if the + * location has only stop locations. + */ + @Nullable + public GenericLocation coordinateLocation() { + if (coordinates.isEmpty()) { + return null; + } + // TODO we will remove support for multiple coordinates + var coordinate = coordinates.getFirst(); + return new GenericLocation(label(), null, coordinate.latitude(), coordinate.longitude()); + } + /** * The minimum wait time is used to force the trip to stay the given duration at the via location * before the trip is continued. This cannot be used together with allow-pass-through, since a diff --git a/application/src/main/java/org/opentripplanner/routing/api/response/RoutingError.java b/application/src/main/java/org/opentripplanner/routing/api/response/RoutingError.java index 741d3e8a30a..a55a22cb6c4 100644 --- a/application/src/main/java/org/opentripplanner/routing/api/response/RoutingError.java +++ b/application/src/main/java/org/opentripplanner/routing/api/response/RoutingError.java @@ -1,11 +1,14 @@ package org.opentripplanner.routing.api.response; import java.util.Objects; +import javax.annotation.Nullable; import org.opentripplanner.utils.tostring.ToStringBuilder; public class RoutingError { public final RoutingErrorCode code; + + @Nullable public final InputField inputField; public RoutingError(RoutingErrorCode code, InputField inputField) { diff --git a/application/src/main/java/org/opentripplanner/routing/graphfinder/StreetGraphFinder.java b/application/src/main/java/org/opentripplanner/routing/graphfinder/StreetGraphFinder.java index c70f9e9f376..9c79bc61e18 100644 --- a/application/src/main/java/org/opentripplanner/routing/graphfinder/StreetGraphFinder.java +++ b/application/src/main/java/org/opentripplanner/routing/graphfinder/StreetGraphFinder.java @@ -4,7 +4,6 @@ import java.util.Comparator; import java.util.List; -import java.util.Set; import org.locationtech.jts.geom.Coordinate; import org.opentripplanner.astar.spi.SkipEdgeStrategy; import org.opentripplanner.astar.spi.TraverseVisitor; @@ -14,6 +13,7 @@ import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.linking.VertexLinker; import org.opentripplanner.street.model.edge.Edge; +import org.opentripplanner.street.search.LinkingContext; import org.opentripplanner.street.search.StreetSearchBuilder; import org.opentripplanner.street.search.TemporaryVerticesContainer; import org.opentripplanner.street.search.state.State; @@ -98,23 +98,17 @@ private void findClosestUsingStreets( // RR dateTime defaults to currentTime. // If elapsed time is not capped, searches are very slow. - try ( - var temporaryVertices = new TemporaryVerticesContainer( - graph, - linker, - id -> Set.of(), - GenericLocation.fromCoordinate(lat, lon), - GenericLocation.UNKNOWN, - StreetMode.WALK, - StreetMode.WALK - ) - ) { + try (var temporaryVerticesContainer = new TemporaryVerticesContainer()) { + var linkerContext = LinkingContext.of(temporaryVerticesContainer, graph, linker) + .withFrom(GenericLocation.fromCoordinate(lat, lon), StreetMode.WALK) + .build(); StreetSearchBuilder.of() .setSkipEdgeStrategy(skipEdgeStrategy) .setTraverseVisitor(visitor) .setDominanceFunction(new DominanceFunctions.LeastWalk()) .setRequest(request) - .setVerticesContainer(temporaryVertices) + .setFrom(linkerContext.fromVertices()) + .setTo(linkerContext.toVertices()) .getShortestPathTree(); } } diff --git a/application/src/main/java/org/opentripplanner/routing/impl/GraphPathFinder.java b/application/src/main/java/org/opentripplanner/routing/impl/GraphPathFinder.java index 286f6438138..fbc85be85f8 100644 --- a/application/src/main/java/org/opentripplanner/routing/impl/GraphPathFinder.java +++ b/application/src/main/java/org/opentripplanner/routing/impl/GraphPathFinder.java @@ -17,7 +17,7 @@ import org.opentripplanner.street.model.edge.Edge; import org.opentripplanner.street.model.vertex.Vertex; import org.opentripplanner.street.search.StreetSearchBuilder; -import org.opentripplanner.street.search.TemporaryVerticesContainer; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; import org.opentripplanner.street.search.state.State; import org.opentripplanner.street.search.strategy.DominanceFunctions; import org.opentripplanner.street.search.strategy.EuclideanRemainingWeightHeuristic; @@ -121,12 +121,12 @@ public List> getPaths( */ public List> graphPathFinderEntryPoint( RouteRequest request, - TemporaryVerticesContainer vertexContainer + FromToViaVertexRequest fromToViaVertexRequest ) { return graphPathFinderEntryPoint( request, - vertexContainer.getFromVertices(), - vertexContainer.getToVertices() + fromToViaVertexRequest.findVertices(request.from()), + fromToViaVertexRequest.findVertices(request.to()) ); } diff --git a/application/src/main/java/org/opentripplanner/routing/linking/DisposableEdgeCollection.java b/application/src/main/java/org/opentripplanner/routing/linking/DisposableEdgeCollection.java index f5c15fb7832..61ed7870abb 100644 --- a/application/src/main/java/org/opentripplanner/routing/linking/DisposableEdgeCollection.java +++ b/application/src/main/java/org/opentripplanner/routing/linking/DisposableEdgeCollection.java @@ -33,6 +33,13 @@ public void addEdge(Edge edge) { this.edges.add(edge); } + /** + * This collection is empty and there is no need to dispose edges. + */ + public boolean isEmpty() { + return edges.isEmpty(); + } + /** * Removes all the edges in this collection from the graph. */ diff --git a/application/src/main/java/org/opentripplanner/routing/linking/SameEdgeAdjuster.java b/application/src/main/java/org/opentripplanner/routing/linking/SameEdgeAdjuster.java index 55b9ce75a82..4784864dfe5 100644 --- a/application/src/main/java/org/opentripplanner/routing/linking/SameEdgeAdjuster.java +++ b/application/src/main/java/org/opentripplanner/routing/linking/SameEdgeAdjuster.java @@ -22,7 +22,7 @@ public class SameEdgeAdjuster { private SameEdgeAdjuster() {} /** - * Utility class. If the from and to vertices are generated and lie along some of the same edges, + * Utility class. If the from, to or via vertices are generated and lie along some of the same edges, * we need to wire them up along those edges so that we don't get odd circuitous routes for really * short trips. */ diff --git a/application/src/main/java/org/opentripplanner/routing/via/ViaCoordinateTransferFactory.java b/application/src/main/java/org/opentripplanner/routing/via/ViaCoordinateTransferFactory.java index 363ce1bd6b9..50e5c56f0e1 100644 --- a/application/src/main/java/org/opentripplanner/routing/via/ViaCoordinateTransferFactory.java +++ b/application/src/main/java/org/opentripplanner/routing/via/ViaCoordinateTransferFactory.java @@ -4,6 +4,7 @@ import org.opentripplanner.framework.geometry.WgsCoordinate; import org.opentripplanner.routing.api.request.RouteRequest; import org.opentripplanner.routing.via.model.ViaCoordinateTransfer; +import org.opentripplanner.street.model.vertex.Vertex; /** * This class is a factory for creating {@link ViaCoordinateTransfer}s. It is injected into @@ -12,7 +13,7 @@ public interface ViaCoordinateTransferFactory { List createViaTransfers( RouteRequest request, - String label, + Vertex viaVertex, WgsCoordinate coordinate ); } diff --git a/application/src/main/java/org/opentripplanner/routing/via/configure/ViaModule.java b/application/src/main/java/org/opentripplanner/routing/via/configure/ViaModule.java index 1accb01b9e6..c6088e7ca35 100644 --- a/application/src/main/java/org/opentripplanner/routing/via/configure/ViaModule.java +++ b/application/src/main/java/org/opentripplanner/routing/via/configure/ViaModule.java @@ -3,7 +3,6 @@ import dagger.Module; import dagger.Provides; import org.opentripplanner.routing.graph.Graph; -import org.opentripplanner.routing.linking.VertexLinker; import org.opentripplanner.routing.via.ViaCoordinateTransferFactory; import org.opentripplanner.routing.via.service.DefaultViaCoordinateTransferFactory; import org.opentripplanner.standalone.config.BuildConfig; @@ -16,12 +15,10 @@ public abstract class ViaModule { static ViaCoordinateTransferFactory providesViaTransferResolver( BuildConfig buildConfig, TransitService transitService, - Graph graph, - VertexLinker linker + Graph graph ) { return new DefaultViaCoordinateTransferFactory( graph, - linker, transitService, buildConfig.maxTransferDuration ); diff --git a/application/src/main/java/org/opentripplanner/routing/via/service/DefaultViaCoordinateTransferFactory.java b/application/src/main/java/org/opentripplanner/routing/via/service/DefaultViaCoordinateTransferFactory.java index e0f6ebcf5bf..b5b0b13d4a6 100644 --- a/application/src/main/java/org/opentripplanner/routing/via/service/DefaultViaCoordinateTransferFactory.java +++ b/application/src/main/java/org/opentripplanner/routing/via/service/DefaultViaCoordinateTransferFactory.java @@ -5,43 +5,31 @@ import java.util.ArrayList; import java.util.List; import org.opentripplanner.framework.geometry.WgsCoordinate; -import org.opentripplanner.framework.i18n.I18NString; import org.opentripplanner.graph_builder.module.nearbystops.NearbyStopFinder; import org.opentripplanner.graph_builder.module.nearbystops.StraightLineNearbyStopFinder; import org.opentripplanner.graph_builder.module.nearbystops.StreetNearbyStopFinder; import org.opentripplanner.routing.api.request.RouteRequest; -import org.opentripplanner.routing.api.request.StreetMode; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.graphfinder.NearbyStop; -import org.opentripplanner.routing.linking.DisposableEdgeCollection; -import org.opentripplanner.routing.linking.VertexLinker; import org.opentripplanner.routing.via.ViaCoordinateTransferFactory; import org.opentripplanner.routing.via.model.ViaCoordinateTransfer; -import org.opentripplanner.street.model.edge.LinkingDirection; -import org.opentripplanner.street.model.edge.TemporaryFreeEdge; -import org.opentripplanner.street.model.vertex.TemporaryStreetLocation; -import org.opentripplanner.street.search.TraverseMode; -import org.opentripplanner.street.search.TraverseModeSet; +import org.opentripplanner.street.model.vertex.Vertex; import org.opentripplanner.transit.service.TransitService; -import org.opentripplanner.utils.lang.StringUtils; public class DefaultViaCoordinateTransferFactory implements ViaCoordinateTransferFactory { private final Graph graph; private final TransitService transitService; private final Duration radiusAsDuration; - private final VertexLinker linker; @Inject public DefaultViaCoordinateTransferFactory( Graph graph, - VertexLinker linker, TransitService transitService, Duration radiusAsDuration ) { this.graph = graph; this.transitService = transitService; - this.linker = linker; // We divide the regular transfer radius by two, since we have two "transfers" after each // other here. This reduces the number of possible transfers to one fourth. The radius should @@ -53,76 +41,32 @@ public DefaultViaCoordinateTransferFactory( @Override public List createViaTransfers( RouteRequest request, - String viaLabel, + Vertex location, WgsCoordinate coordinate ) { - DisposableEdgeCollection tempEdges = null; - try { - var nearbyStopFinder = createNearbyStopFinder(radiusAsDuration); - var name = I18NString.of( - (StringUtils.hasValue(viaLabel) ? viaLabel : "Via") + " " + coordinate - ); + var nearbyStopFinder = createNearbyStopFinder(radiusAsDuration); - var viaVertex = new TemporaryStreetLocation(coordinate.asJtsCoordinate(), name); + var toStops = findNearbyStops(nearbyStopFinder, location, request, false); + var fromStops = findNearbyStops(nearbyStopFinder, location, request, true); - var m = mapTransferMode(request.journey().modes().transferMode); + var transfers = new ArrayList(); - tempEdges = linker.linkVertexForRequest( - viaVertex, - new TraverseModeSet(m), - LinkingDirection.BIDIRECTIONAL, - (via, street) -> { - var v = (TemporaryStreetLocation) via; - return List.of( - TemporaryFreeEdge.createTemporaryFreeEdge(street, v), - TemporaryFreeEdge.createTemporaryFreeEdge(v, street) - ); - } - ); - - var toStops = findNearbyStops(nearbyStopFinder, viaVertex, request, false); - var fromStops = findNearbyStops(nearbyStopFinder, viaVertex, request, true); - - var transfers = new ArrayList(); - - for (NearbyStop from : fromStops) { - for (NearbyStop to : toStops) { - transfers.add( - new ViaCoordinateTransfer( - coordinate, - from.stop.getIndex(), - to.stop.getIndex(), - from.edges, - to.edges, - (int) (from.state.getElapsedTimeSeconds() + to.state.getElapsedTimeSeconds()), - from.state.getWeight() + to.state.getWeight() - ) - ); - } - } - return transfers; - } catch (RuntimeException ex) { - // This make sure we dispose the edges in case something goes wrong. - if (tempEdges != null) { - tempEdges.disposeEdges(); - } - throw ex; - } - } - - private static TraverseMode mapTransferMode(StreetMode streetMode) { - if (streetMode.transferAllowed()) { - if (streetMode.includesBiking()) { - return TraverseMode.BICYCLE; - } - if (streetMode.includesDriving()) { - return TraverseMode.CAR; - } - if (streetMode.includesWalking()) { - return TraverseMode.WALK; + for (NearbyStop from : fromStops) { + for (NearbyStop to : toStops) { + transfers.add( + new ViaCoordinateTransfer( + coordinate, + from.stop.getIndex(), + to.stop.getIndex(), + from.edges, + to.edges, + (int) (from.state.getElapsedTimeSeconds() + to.state.getElapsedTimeSeconds()), + from.state.getWeight() + to.state.getWeight() + ) + ); } } - throw new IllegalStateException("Mode not allowed for transfer: " + streetMode); + return transfers; } /** @@ -142,7 +86,7 @@ private NearbyStopFinder createNearbyStopFinder(Duration radiusAsDuration) { */ private List findNearbyStops( NearbyStopFinder finder, - TemporaryStreetLocation viaVertex, + Vertex viaVertex, RouteRequest request, boolean reverseDirection ) { diff --git a/application/src/main/java/org/opentripplanner/street/search/LinkingContext.java b/application/src/main/java/org/opentripplanner/street/search/LinkingContext.java new file mode 100644 index 00000000000..760b36e2a19 --- /dev/null +++ b/application/src/main/java/org/opentripplanner/street/search/LinkingContext.java @@ -0,0 +1,104 @@ +package org.opentripplanner.street.search; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import org.opentripplanner.model.GenericLocation; +import org.opentripplanner.routing.graph.Graph; +import org.opentripplanner.routing.linking.VertexLinker; +import org.opentripplanner.street.model.vertex.TransitStopVertex; +import org.opentripplanner.street.model.vertex.Vertex; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; +import org.opentripplanner.transit.model.framework.FeedScopedId; + +/** + * This class contains temporary vertices and edges that are used in A-Star searches. After they + * are no longer needed, this class removes the temporary vertices and edges. It implements + * AutoCloseable and the cleanup is automatically done with a try-with-resources statement. + */ +public class LinkingContext { + + private final GenericLocation from; + private final GenericLocation to; + private final Map> verticesByLocation; + private final Set fromStopVertices; + private final Set toStopVertices; + + public LinkingContext(LinkingContextBuilder builder) { + this.from = builder.from(); + this.to = builder.to(); + this.fromStopVertices = builder.fromStopVertices(); + this.verticesByLocation = builder.verticesByLocation(); + this.toStopVertices = builder.toStopVertices(); + } + + /** + * Create builder when stop locations are not used for locations. + */ + public static LinkingContextBuilder of( + TemporaryVerticesContainer container, + Graph graph, + VertexLinker linker + ) { + return new LinkingContextBuilder(container, graph, linker, id -> Set.of()); + } + + /** + * Create builder when stop locations are potentially used for locations. + */ + public static LinkingContextBuilder of( + TemporaryVerticesContainer container, + Graph graph, + VertexLinker linker, + Function> resolveSiteIds + ) { + return new LinkingContextBuilder(container, graph, linker, resolveSiteIds); + } + + /** + * Vertices that are used for from (origin). This includes both street and stop vertices. + */ + public Set fromVertices() { + return verticesByLocation.getOrDefault(from, Set.of()); + } + + /** + * Vertices that are used for to (destination). This includes both street and stop vertices. + */ + public Set toVertices() { + return verticesByLocation.getOrDefault(to, Set.of()); + } + + /** + * Vertices that are used for either origin, destination or for via locations. Only the visit via + * locations that have a coordinate specified will have vertices available. Stop vertices are not + * included via locations. + */ + public Map> verticesByLocation() { + return verticesByLocation; + } + + /** + * If from location (origin) has a stop id defined, this will include vertices related to it. If + * the stop is a station, the child stops will be included. + */ + public Set fromStopVertices() { + return fromStopVertices; + } + + /** + * If to location (destination) has a stop id defined, this will include vertices related to it. + * If the stop is a station, the child stops will be included. + */ + public Set toStopVertices() { + return toStopVertices; + } + + /** + * Creates a {@link FromToViaVertexRequest} that contains vertices from this container. + */ + public FromToViaVertexRequest createFromToViaVertexRequest() { + return new FromToViaVertexRequest(fromStopVertices, toStopVertices, verticesByLocation); + } +} diff --git a/application/src/main/java/org/opentripplanner/street/search/LinkingContextBuilder.java b/application/src/main/java/org/opentripplanner/street/search/LinkingContextBuilder.java new file mode 100644 index 00000000000..5d16668d4a2 --- /dev/null +++ b/application/src/main/java/org/opentripplanner/street/search/LinkingContextBuilder.java @@ -0,0 +1,464 @@ +package org.opentripplanner.street.search; + +import com.google.common.collect.Sets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.geom.GeometryFactory; +import org.opentripplanner.framework.geometry.GeometryUtils; +import org.opentripplanner.framework.i18n.I18NString; +import org.opentripplanner.framework.i18n.LocalizedString; +import org.opentripplanner.framework.i18n.NonLocalizedString; +import org.opentripplanner.model.GenericLocation; +import org.opentripplanner.routing.api.request.StreetMode; +import org.opentripplanner.routing.api.request.via.VisitViaLocation; +import org.opentripplanner.routing.api.response.InputField; +import org.opentripplanner.routing.api.response.RoutingError; +import org.opentripplanner.routing.api.response.RoutingErrorCode; +import org.opentripplanner.routing.error.RoutingValidationException; +import org.opentripplanner.routing.graph.Graph; +import org.opentripplanner.routing.linking.DisposableEdgeCollection; +import org.opentripplanner.routing.linking.SameEdgeAdjuster; +import org.opentripplanner.routing.linking.VertexLinker; +import org.opentripplanner.street.model.edge.Edge; +import org.opentripplanner.street.model.edge.LinkingDirection; +import org.opentripplanner.street.model.edge.TemporaryFreeEdge; +import org.opentripplanner.street.model.vertex.StreetVertex; +import org.opentripplanner.street.model.vertex.TemporaryStreetLocation; +import org.opentripplanner.street.model.vertex.TransitStopVertex; +import org.opentripplanner.street.model.vertex.Vertex; +import org.opentripplanner.transit.model.framework.FeedScopedId; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is responsible for linking the RouteRequest origin, destination and visit via + * locations that contain coordinates to the Graph used in the A-Star search. This builder also + * validates that it was possible to link the locations to the graph. The responsibility of cleaning + * up the temporary vertices and edges is on the {@link TemporaryVerticesContainer}. + */ +public class LinkingContextBuilder { + + private static final Logger LOG = LoggerFactory.getLogger(LinkingContextBuilder.class); + + private final TemporaryVerticesContainer container; + private final Graph graph; + private final VertexLinker vertexLinker; + private final Function> resolveSiteIds; + private final List tempEdges = new ArrayList<>(); + private GenericLocation from = GenericLocation.UNKNOWN; + private GenericLocation to = GenericLocation.UNKNOWN; + private List visitViaLocationsWithCoordinates = List.of(); + private Set fromVertices = Set.of(); + private Set toVertices = Set.of(); + private Map> visitViaLocationVertices = Map.of(); + private Set fromStopVertices = Set.of(); + private Set toStopVertices = Set.of(); + + LinkingContextBuilder( + TemporaryVerticesContainer container, + Graph graph, + VertexLinker vertexLinker, + Function> resolveSiteIds + ) { + this.container = container; + this.graph = graph; + this.vertexLinker = vertexLinker; + this.resolveSiteIds = resolveSiteIds; + } + + public LinkingContextBuilder withFrom(GenericLocation location, StreetMode mode) { + return withFrom(location, EnumSet.of(mode)); + } + + public LinkingContextBuilder withFrom(GenericLocation location, EnumSet modes) { + this.from = location; + this.fromVertices = getStreetVerticesForLocation(location, modes, LocationType.FROM); + if (location.stopId != null) { + this.fromStopVertices = findStopOrChildStopVertices(location.stopId); + } + return this; + } + + public GenericLocation from() { + return from; + } + + public Set fromStopVertices() { + return fromStopVertices; + } + + public LinkingContextBuilder withTo(GenericLocation location, StreetMode mode) { + return withTo(location, EnumSet.of(mode)); + } + + public LinkingContextBuilder withTo(GenericLocation location, EnumSet modes) { + this.to = location; + this.toVertices = getStreetVerticesForLocation(to, modes, LocationType.TO); + if (location.stopId != null) { + this.toStopVertices = findStopOrChildStopVertices(location.stopId); + } + return this; + } + + public GenericLocation to() { + return to; + } + + public Set toStopVertices() { + return toStopVertices; + } + + public LinkingContextBuilder withVia( + List visitViaLocations, + EnumSet modes + ) { + var visitViaLocationsWithCoordinates = visitViaLocations + .stream() + .map(VisitViaLocation::coordinateLocation) + .filter(Objects::nonNull) + .toList(); + if (visitViaLocationsWithCoordinates.isEmpty()) { + return this; + } + this.visitViaLocationsWithCoordinates = visitViaLocationsWithCoordinates; + this.visitViaLocationVertices = visitViaLocationsWithCoordinates + .stream() + .collect( + Collectors.toMap( + location -> location, + location -> getStreetVerticesForLocation(location, modes, LocationType.VISIT_VIA_LOCATION) + ) + ); + return this; + } + + public Map> verticesByLocation() { + var verticesByLocation = new HashMap>(); + verticesByLocation.put(from, fromVertices); + verticesByLocation.put(to, toVertices); + verticesByLocation.putAll(visitViaLocationVertices); + return Collections.unmodifiableMap(verticesByLocation); + } + + public LinkingContext build() { + checkIfVerticesFound(); + addAdjustedEdges(); + return new LinkingContext(this); + } + + private void addAdjustedEdges() { + addAdjustedEdgesBetween(fromVertices, toVertices); + if (visitViaLocationsWithCoordinates.isEmpty()) { + return; + } + addAdjustedEdgesBetween( + fromVertices, + visitViaLocationVertices.get(visitViaLocationsWithCoordinates.getFirst()) + ); + addAdjustedEdgesBetween( + visitViaLocationVertices.get(visitViaLocationsWithCoordinates.getLast()), + toVertices + ); + var i = 1; + while (i < visitViaLocationsWithCoordinates.size()) { + Set fromViaVertices = visitViaLocationVertices.get( + visitViaLocationsWithCoordinates.get(i - 1) + ); + Set toViaVertices = visitViaLocationVertices.get( + visitViaLocationsWithCoordinates.get(i) + ); + addAdjustedEdgesBetween(fromViaVertices, toViaVertices); + i++; + } + } + + private void addAdjustedEdgesBetween(Set fromVertices, Set toVertices) { + for (Vertex fromVertex : fromVertices) { + for (Vertex toVertex : toVertices) { + container.addEdgeCollection(SameEdgeAdjuster.adjust(fromVertex, toVertex, graph)); + } + } + } + + /** + * Gets a set of vertices corresponding to the location provided. It first tries to match one of + * the stop or station types by id, and if not successful, it uses the coordinates if provided. + */ + private Set getStreetVerticesForLocation( + GenericLocation location, + EnumSet streetModes, + LocationType type + ) { + if (!location.isSpecified()) { + return Set.of(); + } + + // Differentiate between driving and non-driving, as driving is not available from transit stops + List modes = streetModes + .stream() + .map(streetMode -> getTraverseModeForLinker(streetMode, type)) + .distinct() + .toList(); + + var results = new HashSet(); + if (location.stopId != null) { + if (!modes.stream().allMatch(TraverseMode::isInCar)) { + results.addAll(getStreetVerticesForStop(location)); + } + if (modes.stream().anyMatch(TraverseMode::isInCar)) { + // Ensure that there is a car routable vertex (that can originate from stop's coordinate). + var carRoutableVertex = getCarRoutableStreetVertex(location, type); + carRoutableVertex.ifPresent(results::add); + } + } else if (location.getCoordinate() != null) { + // Connect a temporary vertex from coordinate to graph + results.add( + createVertexFromCoordinate(location.getCoordinate(), location.label, modes, type) + ); + } + + return results; + } + + private Set getStreetVerticesForStop(GenericLocation location) { + // check if there is a stop by the given id + var stopVertex = graph.findStopVertex(location.stopId); + if (stopVertex.isPresent()) { + return Set.of(stopVertex.get()); + } + + // station centroids may be used instead of child stop vertices for stations + var centroidVertex = graph.findStationCentroidVertex(location.stopId); + if (centroidVertex.isPresent()) { + return Set.of(centroidVertex.get()); + } + + // in the regular case you want to resolve a (multi-modal) station into its child stops + var childVertices = findStopOrChildStopVertices(location.stopId); + if (!childVertices.isEmpty()) { + return childVertices.stream().map(Vertex.class::cast).collect(Collectors.toUnmodifiableSet()); + } + return Set.of(); + } + + /** + * We need to use coordinates of the stop for cars as an alternative as not all stops are routable + * with cars. + */ + private Optional getCarRoutableStreetVertex(GenericLocation location, LocationType type) { + // Fetch coordinate from stop, if not given in request + if (location.getCoordinate() == null) { + var stopVertex = graph.getStopVertex(location.stopId); + if (stopVertex != null) { + var c = stopVertex.getStop().getCoordinate(); + location = new GenericLocation( + location.label, + location.stopId, + c.latitude(), + c.longitude() + ); + } + } + return location.getCoordinate() != null + ? Optional.of( + createVertexFromCoordinate( + location.getCoordinate(), + location.label, + List.of(TraverseMode.CAR), + type + ) + ) + : Optional.empty(); + } + + private TraverseMode getTraverseModeForLinker(StreetMode streetMode, LocationType type) { + TraverseMode nonTransitMode = TraverseMode.WALK; + // for park and ride we will start in car mode and walk to the end vertex + boolean parkAndRideDepart = streetMode == StreetMode.CAR_TO_PARK && type == LocationType.FROM; + boolean onlyCarAvailable = streetMode == StreetMode.CAR; + if (onlyCarAvailable || parkAndRideDepart) { + nonTransitMode = TraverseMode.CAR; + } + return nonTransitMode; + } + + private Vertex createVertexFromCoordinate( + Coordinate coordinate, + @Nullable String label, + List modes, + LocationType type + ) { + LOG.debug("Creating {} vertex for {}", type.description(), coordinate); + + I18NString name = label == null || label.isEmpty() + ? new LocalizedString(type.translationKey()) + : new NonLocalizedString(label); + + var temporaryStreetLocation = new TemporaryStreetLocation(coordinate, name); + + container.addEdgeCollection( + vertexLinker.linkVertexForRequest( + temporaryStreetLocation, + new TraverseModeSet(modes), + mapDirection(type), + (vertex, streetVertex) -> createEdges((TemporaryStreetLocation) vertex, streetVertex, type) + ) + ); + + if ( + temporaryStreetLocation.getIncoming().isEmpty() && + temporaryStreetLocation.getOutgoing().isEmpty() + ) { + LOG.warn("Couldn't link {}", coordinate); + } + + temporaryStreetLocation.setWheelchairAccessible(true); + + return temporaryStreetLocation; + } + + private void checkIfVerticesFound() { + List routingErrors = new ArrayList<>(); + + // check that vertices where found if from-location was specified + if (from.isSpecified() && isDisconnected(fromVertices, LocationType.FROM)) { + routingErrors.add( + new RoutingError(getRoutingErrorCodeForDisconnected(from), InputField.FROM_PLACE) + ); + } + + // check that vertices where found if to-location was specified + if (to.isSpecified() && isDisconnected(toVertices, LocationType.TO)) { + routingErrors.add( + new RoutingError(getRoutingErrorCodeForDisconnected(to), InputField.TO_PLACE) + ); + } + + // check that vertices where found if visit via locations with coordinates were specified + if (!visitViaLocationsWithCoordinates.isEmpty()) { + var errors = visitViaLocationVertices + .entrySet() + .stream() + .filter(entry -> isDisconnected(entry.getValue(), LocationType.VISIT_VIA_LOCATION)) + .map(entry -> + new RoutingError( + getRoutingErrorCodeForDisconnected(entry.getKey()), + InputField.INTERMEDIATE_PLACE + ) + ) + .toList(); + routingErrors.addAll(errors); + } + + // if from and to share any vertices, the user is already at their destination, and the result + // is a trivial path + if (!Sets.intersection(fromVertices, toVertices).isEmpty()) { + routingErrors.add(new RoutingError(RoutingErrorCode.WALKING_BETTER_THAN_TRANSIT, null)); + } + + if (!routingErrors.isEmpty()) { + throw new RoutingValidationException(routingErrors); + } + } + + private static boolean isDisconnected(Set vertices, LocationType type) { + // Not connected if linking was not attempted, and vertices were not specified in the request. + if (vertices.isEmpty()) { + return true; + } + + Predicate isNotTransit = Predicate.not(TransitStopVertex.class::isInstance); + Predicate hasNoIncoming = v -> v.getIncoming().isEmpty(); + Predicate hasNoOutgoing = v -> v.getOutgoing().isEmpty(); + + // Not connected if linking did not create incoming/outgoing edges depending on the + // location type. + Predicate isNotConnected = + switch (type) { + case FROM -> isNotTransit.and(hasNoOutgoing); + case TO -> isNotTransit.and(hasNoIncoming); + case VISIT_VIA_LOCATION -> hasNoIncoming.or(hasNoOutgoing); + }; + + return vertices.stream().allMatch(isNotTransit.and(isNotConnected)); + } + + private RoutingErrorCode getRoutingErrorCodeForDisconnected(GenericLocation location) { + Coordinate coordinate = location.getCoordinate(); + GeometryFactory gf = GeometryUtils.getGeometryFactory(); + return coordinate != null && graph.getConvexHull().disjoint(gf.createPoint(coordinate)) + ? RoutingErrorCode.OUTSIDE_BOUNDS + : RoutingErrorCode.LOCATION_NOT_FOUND; + } + + private LinkingDirection mapDirection(LocationType type) { + return switch (type) { + case FROM -> LinkingDirection.INCOMING; + case TO -> LinkingDirection.OUTGOING; + case VISIT_VIA_LOCATION -> LinkingDirection.BIDIRECTIONAL; + }; + } + + private List createEdges( + TemporaryStreetLocation location, + StreetVertex streetVertex, + LocationType type + ) { + return switch (type) { + case FROM -> List.of(TemporaryFreeEdge.createTemporaryFreeEdge(location, streetVertex)); + case TO -> List.of(TemporaryFreeEdge.createTemporaryFreeEdge(streetVertex, location)); + case VISIT_VIA_LOCATION -> List.of( + TemporaryFreeEdge.createTemporaryFreeEdge(location, streetVertex), + TemporaryFreeEdge.createTemporaryFreeEdge(streetVertex, location) + ); + }; + } + + private Set findStopOrChildStopVertices(FeedScopedId stopId) { + return resolveSiteIds + .apply(stopId) + .stream() + .flatMap(id -> graph.findStopVertex(id).stream()) + .collect(Collectors.toUnmodifiableSet()); + } + + private enum LocationType { + FROM("origin"), + TO("destination"), + VISIT_VIA_LOCATION("visit via location", "via_location"); + + private final String description; + private final String translationKey; + + LocationType(String description) { + this(description, description); + } + + LocationType(String description, String translationKey) { + this.description = description; + this.translationKey = translationKey; + } + + public String description() { + return description; + } + + public String translationKey() { + return translationKey; + } + } +} diff --git a/application/src/main/java/org/opentripplanner/street/search/StreetSearchBuilder.java b/application/src/main/java/org/opentripplanner/street/search/StreetSearchBuilder.java index 59e6137970d..aec2f7114cf 100644 --- a/application/src/main/java/org/opentripplanner/street/search/StreetSearchBuilder.java +++ b/application/src/main/java/org/opentripplanner/street/search/StreetSearchBuilder.java @@ -46,12 +46,6 @@ public StreetSearchBuilder setStreetRequest(StreetRequest streetRequest) { return this; } - public StreetSearchBuilder setVerticesContainer(TemporaryVerticesContainer container) { - setFrom(container.getFromVertices()); - setTo(container.getToVertices()); - return this; - } - public StreetSearchBuilder setIntersectionTraversalCalculator( IntersectionTraversalCalculator intersectionTraversalCalculator ) { diff --git a/application/src/main/java/org/opentripplanner/street/search/TemporaryVerticesContainer.java b/application/src/main/java/org/opentripplanner/street/search/TemporaryVerticesContainer.java index 6e7cae4f082..87964d6a6d7 100644 --- a/application/src/main/java/org/opentripplanner/street/search/TemporaryVerticesContainer.java +++ b/application/src/main/java/org/opentripplanner/street/search/TemporaryVerticesContainer.java @@ -1,354 +1,30 @@ package org.opentripplanner.street.search; -import com.google.common.collect.Sets; import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; import java.util.List; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.GeometryFactory; -import org.opentripplanner.framework.geometry.GeometryUtils; -import org.opentripplanner.framework.i18n.I18NString; -import org.opentripplanner.framework.i18n.LocalizedString; -import org.opentripplanner.framework.i18n.NonLocalizedString; -import org.opentripplanner.model.GenericLocation; -import org.opentripplanner.routing.api.request.StreetMode; -import org.opentripplanner.routing.api.response.InputField; -import org.opentripplanner.routing.api.response.RoutingError; -import org.opentripplanner.routing.api.response.RoutingErrorCode; -import org.opentripplanner.routing.error.RoutingValidationException; -import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.linking.DisposableEdgeCollection; -import org.opentripplanner.routing.linking.SameEdgeAdjuster; -import org.opentripplanner.routing.linking.VertexLinker; -import org.opentripplanner.street.model.edge.LinkingDirection; -import org.opentripplanner.street.model.edge.TemporaryFreeEdge; -import org.opentripplanner.street.model.vertex.TemporaryStreetLocation; -import org.opentripplanner.street.model.vertex.TransitStopVertex; -import org.opentripplanner.street.model.vertex.Vertex; -import org.opentripplanner.transit.model.framework.FeedScopedId; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** - * This class is responsible for linking the RouteRequest origin and destination to the Graph used - * in the A-Star search, as well as removing them after the search has been done. - *

- * It also facilitates the lookup of site ids to the correct vertices. - *

- * It implements - * AutoCloseable, in order to be able to use the try-with-resources statement, making the clean-up - * automatic. + * This class contains temporary vertices and edges that are used in A-Star searches. After they + * are no longer needed, this class removes the temporary vertices and edges. It implements + * AutoCloseable and the cleanup is automatically done with a try-with-resources statement. */ public class TemporaryVerticesContainer implements AutoCloseable { - private static final Logger LOG = LoggerFactory.getLogger(TemporaryVerticesContainer.class); + private final List tempEdgeCollections = new ArrayList<>(); - private final Graph graph; - private final Set tempEdges; - private final Set fromVertices; - private final Set toVertices; - private final GenericLocation from; - private final GenericLocation to; - private final VertexLinker vertexLinker; - private final Function> resolveSiteIds; - - /** - * @param resolveSiteIds A function that takes a site id (stop, station, multi-modal station...) - * and returns a list of the input value (if it's a stop) or of the of - * child stop ids if it's a grouping of stops. - */ - public TemporaryVerticesContainer( - Graph graph, - VertexLinker linker, - Function> resolveSiteIds, - GenericLocation from, - GenericLocation to, - StreetMode accessMode, - StreetMode egressMode - ) { - this.resolveSiteIds = resolveSiteIds; - this.tempEdges = new HashSet<>(); - - this.graph = graph; - this.vertexLinker = linker; - this.from = from; - this.to = to; - fromVertices = getStreetVerticesForLocation(from, accessMode, false, tempEdges); - toVertices = getStreetVerticesForLocation(to, egressMode, true, tempEdges); - - checkIfVerticesFound(); - - if (fromVertices != null && toVertices != null) { - for (Vertex fromVertex : fromVertices) { - for (Vertex toVertex : toVertices) { - tempEdges.add(SameEdgeAdjuster.adjust(fromVertex, toVertex, graph)); - } - } + void addEdgeCollection(DisposableEdgeCollection collection) { + if (!collection.isEmpty()) { + this.tempEdgeCollections.add(collection); } } - /* INSTANCE METHODS */ - /** * Tear down this container, removing any temporary edges from the "permanent" graph objects. This * enables all temporary objects for garbage collection. */ @Override public void close() { - this.tempEdges.forEach(DisposableEdgeCollection::disposeEdges); - } - - public Set getFromVertices() { - return fromVertices; - } - - public Set getToVertices() { - return toVertices; - } - - /** - * Get the stop vertices that correspond to the from location. If the from location only contains - * coordinates, this will return an empty set. If the from location is a station id this will - * return the child stops of that station. - */ - public Set getFromStopVertices() { - if (from.stopId == null) { - return Set.of(); - } - return findStopOrChildStopVertices(from.stopId); - } - - /** - * Get the stop vertices that correspond to the to location. If the to location only contains - * coordinates, this will return an empty set. If the to location is a station id this will - * return the child stops of that station. - */ - public Set getToStopVertices() { - if (to.stopId == null) { - return Set.of(); - } - return findStopOrChildStopVertices(to.stopId); - } - - /* PRIVATE METHODS */ - - /** - * Gets a set of vertices corresponding to the location provided. It first tries to match one of - * the stop or station types by id, and if not successful, it uses the coordinates if provided. - * - * @param endVertex: whether this is a start vertex (if it's false) or end vertex (if it's true) - */ - @Nullable - private Set getStreetVerticesForLocation( - GenericLocation location, - StreetMode streetMode, - boolean endVertex, - Set tempEdges - ) { - if (!location.isSpecified()) { - return null; - } - - // Differentiate between driving and non-driving, as driving is not available from transit stops - TraverseMode mode = getTraverseModeForLinker(streetMode, endVertex); - - if (mode.isInCar()) { - // Fetch coordinate from stop, if not given in request - if (location.stopId != null && location.getCoordinate() == null) { - var stopVertex = graph.getStopVertex(location.stopId); - if (stopVertex != null) { - var c = stopVertex.getStop().getCoordinate(); - location = new GenericLocation( - location.label, - location.stopId, - c.latitude(), - c.longitude() - ); - } - } - } else { - if (location.stopId != null) { - // check if there is a stop by the given id - var stopVertex = graph.findStopVertex(location.stopId); - if (stopVertex.isPresent()) { - return Set.of(stopVertex.get()); - } - - // station centroids may be used instead of child stop vertices for stations - var centroidVertex = graph.findStationCentroidVertex(location.stopId); - if (centroidVertex.isPresent()) { - return Set.of(centroidVertex.get()); - } - - // in the regular case you want to resolve a (multi-modal) station into its child stops - var childVertices = findStopOrChildStopVertices(location.stopId); - if (!childVertices.isEmpty()) { - return childVertices - .stream() - .map(Vertex.class::cast) - .collect(Collectors.toUnmodifiableSet()); - } - } - } - - // Check if coordinate is provided and connect it to graph - if (location.getCoordinate() != null) { - return Set.of( - createVertexFromCoordinate( - location.getCoordinate(), - location.label, - streetMode, - endVertex, - tempEdges - ) - ); - } - - return null; - } - - private Set findStopOrChildStopVertices(FeedScopedId stopId) { - return resolveSiteIds - .apply(stopId) - .stream() - .flatMap(id -> graph.findStopVertex(id).stream()) - .collect(Collectors.toUnmodifiableSet()); - } - - private TraverseMode getTraverseModeForLinker(StreetMode streetMode, boolean endVertex) { - TraverseMode nonTransitMode = TraverseMode.WALK; - // for park and ride we will start in car mode and walk to the end vertex - boolean parkAndRideDepart = streetMode == StreetMode.CAR_TO_PARK && !endVertex; - boolean onlyCarAvailable = streetMode == StreetMode.CAR; - if (onlyCarAvailable || parkAndRideDepart) { - nonTransitMode = TraverseMode.CAR; - } - return nonTransitMode; - } - - private Vertex createVertexFromCoordinate( - Coordinate coordinate, - @Nullable String label, - StreetMode streetMode, - boolean endVertex, - Set tempEdges - ) { - if (endVertex) { - LOG.debug("Creating end vertex for {}", coordinate); - } else { - LOG.debug("Creating start vertex for {}", coordinate); - } - - I18NString name; - if (label == null || label.isEmpty()) { - if (endVertex) { - name = new LocalizedString("destination"); - } else { - name = new LocalizedString("origin"); - } - } else { - name = new NonLocalizedString(label); - } - - var temporaryStreetLocation = new TemporaryStreetLocation(coordinate, name); - - TraverseMode nonTransitMode = getTraverseModeForLinker(streetMode, endVertex); - - tempEdges.add( - vertexLinker.linkVertexForRequest( - temporaryStreetLocation, - new TraverseModeSet(nonTransitMode), - endVertex ? LinkingDirection.OUTGOING : LinkingDirection.INCOMING, - endVertex - ? (vertex, streetVertex) -> - List.of( - TemporaryFreeEdge.createTemporaryFreeEdge( - streetVertex, - (TemporaryStreetLocation) vertex - ) - ) - : (vertex, streetVertex) -> - List.of( - TemporaryFreeEdge.createTemporaryFreeEdge( - (TemporaryStreetLocation) vertex, - streetVertex - ) - ) - ) - ); - - if ( - temporaryStreetLocation.getIncoming().isEmpty() && - temporaryStreetLocation.getOutgoing().isEmpty() - ) { - LOG.warn("Couldn't link {}", coordinate); - } - - temporaryStreetLocation.setWheelchairAccessible(true); - - return temporaryStreetLocation; - } - - private void checkIfVerticesFound() { - List routingErrors = new ArrayList<>(); - - // check that vertices where found if from-location was specified - if (from.isSpecified() && isDisconnected(fromVertices, true)) { - routingErrors.add( - new RoutingError(getRoutingErrorCodeForDisconnected(from), InputField.FROM_PLACE) - ); - } - - // check that vertices where found if to-location was specified - if (to.isSpecified() && isDisconnected(toVertices, false)) { - routingErrors.add( - new RoutingError(getRoutingErrorCodeForDisconnected(to), InputField.TO_PLACE) - ); - } - - // if from and to share any vertices, the user is already at their destination, and the result - // is a trivial path - if ( - fromVertices != null && - toVertices != null && - !Sets.intersection(fromVertices, toVertices).isEmpty() - ) { - routingErrors.add(new RoutingError(RoutingErrorCode.WALKING_BETTER_THAN_TRANSIT, null)); - } - - if (!routingErrors.isEmpty()) { - throw new RoutingValidationException(routingErrors); - } - } - - private static boolean isDisconnected(Set vertices, boolean isFrom) { - // Not connected if linking was not attempted, and vertices were not specified in the request. - if (vertices == null) { - return true; - } - - Predicate isNotTransit = Predicate.not(TransitStopVertex.class::isInstance); - Predicate hasNoIncoming = v -> v.getIncoming().isEmpty(); - Predicate hasNoOutgoing = v -> v.getOutgoing().isEmpty(); - - // Not connected if linking did not create incoming/outgoing edges depending on the - // direction and the end. - Predicate isNotConnected = isFrom ? hasNoOutgoing : hasNoIncoming; - - return vertices.stream().allMatch(isNotTransit.and(isNotConnected)); - } - - private RoutingErrorCode getRoutingErrorCodeForDisconnected(GenericLocation location) { - Coordinate coordinate = location.getCoordinate(); - GeometryFactory gf = GeometryUtils.getGeometryFactory(); - return coordinate != null && graph.getConvexHull().disjoint(gf.createPoint(coordinate)) - ? RoutingErrorCode.OUTSIDE_BOUNDS - : RoutingErrorCode.LOCATION_NOT_FOUND; + this.tempEdgeCollections.forEach(DisposableEdgeCollection::disposeEdges); } } diff --git a/application/src/main/java/org/opentripplanner/street/search/request/FromToViaVertexRequest.java b/application/src/main/java/org/opentripplanner/street/search/request/FromToViaVertexRequest.java new file mode 100644 index 00000000000..c4fb6002e61 --- /dev/null +++ b/application/src/main/java/org/opentripplanner/street/search/request/FromToViaVertexRequest.java @@ -0,0 +1,75 @@ +package org.opentripplanner.street.search.request; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.opentripplanner.model.GenericLocation; +import org.opentripplanner.street.model.vertex.TransitStopVertex; +import org.opentripplanner.street.model.vertex.Vertex; +import org.opentripplanner.utils.tostring.ToStringBuilder; + +/** + * Holds vertices (mainly temporary) that are meant to be used within the scope of a single route + * request that can contain access/egress/direct/transfer routing. The temporary vertices will be + * disposed by {@link org.opentripplanner.street.search.TemporaryVerticesContainer} after the search + * is over. + */ +public class FromToViaVertexRequest { + + private final Set fromStops; + private final Set toStops; + private final Map> verticesByLocation; + + public FromToViaVertexRequest( + Set fromStops, + Set toStops, + Map> verticesByLocation + ) { + this.fromStops = fromStops; + this.toStops = toStops; + this.verticesByLocation = verticesByLocation; + } + + /** + * If from location (origin) has a stop id defined, this will include vertices related to it. If + * the stop is a station, the child stops will be included. + */ + public Set fromStops() { + return fromStops; + } + + /** + * If to location (destination) has a stop id defined, this will include vertices related to it. + * If the stop is a station, the child stops will be included. + */ + public Set toStops() { + return toStops; + } + + /** + * Vertices that are used for either origin, destination or for via locations. Only the visit via + * locations that have a coordinate specified will have vertices available. Stop vertices are not + * included via locations. + */ + public Set findVertices(GenericLocation location) { + return verticesByLocation.getOrDefault(location, Set.of()); + } + + @Override + public String toString() { + return ToStringBuilder.of(FromToViaVertexRequest.class) + .addCol("fromStops", fromStops, Set.of()) + .addCol("toStops", toStops, Set.of()) + .addCol( + "verticesByLocation", + verticesByLocation + .entrySet() + .stream() + .sorted(Map.Entry.comparingByKey(Comparator.comparing(GenericLocation::hashCode))) + .toList(), + List.of() + ) + .toString(); + } +} diff --git a/application/src/main/java/org/opentripplanner/visualizer/GraphVisualizer.java b/application/src/main/java/org/opentripplanner/visualizer/GraphVisualizer.java index 83d1228f548..f50158c3637 100644 --- a/application/src/main/java/org/opentripplanner/visualizer/GraphVisualizer.java +++ b/application/src/main/java/org/opentripplanner/visualizer/GraphVisualizer.java @@ -28,7 +28,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Queue; -import java.util.Set; import javax.swing.AbstractListModel; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; @@ -77,6 +76,7 @@ import org.opentripplanner.street.model.vertex.IntersectionVertex; import org.opentripplanner.street.model.vertex.Vertex; import org.opentripplanner.street.model.vertex.VertexLabel; +import org.opentripplanner.street.search.LinkingContext; import org.opentripplanner.street.search.TemporaryVerticesContainer; import org.opentripplanner.street.search.state.State; import org.opentripplanner.street.search.strategy.DominanceFunctions; @@ -514,24 +514,22 @@ protected void route(String from, String to) { var request = builder.buildRequest(); long t0 = System.currentTimeMillis(); // TODO: check options properly intialized (AMB) - try ( - var temporaryVertices = new TemporaryVerticesContainer( + try (var temporaryVerticesContainer = new TemporaryVerticesContainer()) { + var linkerContext = LinkingContext.of( + temporaryVerticesContainer, graph, new VertexLinker( graph, VisibilityMode.TRAVERSE_AREA_EDGES, StreetConstants.DEFAULT_MAX_AREA_NODES - ), - id -> Set.of(), - request.from(), - request.to(), - request.journey().direct().mode(), - request.journey().direct().mode() + ) ) - ) { + .withFrom(request.from(), request.journey().direct().mode()) + .withTo(request.from(), request.journey().direct().mode()) + .build(); List> paths = finder.graphPathFinderEntryPoint( request, - temporaryVertices + linkerContext.createFromToViaVertexRequest() ); long dt = System.currentTimeMillis() - t0; searchTimeElapsedLabel.setText("search time elapsed: " + dt + "ms"); diff --git a/application/src/main/resources/internals.properties b/application/src/main/resources/internals.properties index 8c907ae2e10..120705deb72 100644 --- a/application/src/main/resources/internals.properties +++ b/application/src/main/resources/internals.properties @@ -2,6 +2,7 @@ corner = corner of %s and %s unnamedStreet = unnamed origin = Origin destination = Destination +via_location = Via location partOf = %s (part of %s) locationGroup = Location group diff --git a/application/src/main/resources/internals_fi.properties b/application/src/main/resources/internals_fi.properties index faafb464758..abd52a5897d 100644 --- a/application/src/main/resources/internals_fi.properties +++ b/application/src/main/resources/internals_fi.properties @@ -2,4 +2,5 @@ corner = katujen %s ja %s kulma unnamedStreet = nimetön origin = Lähtöpaikka destination = Määränpää +via_location = Välipiste partOf = %s (alueella %s) diff --git a/application/src/main/resources/org/opentripplanner/apis/gtfs/schema.graphqls b/application/src/main/resources/org/opentripplanner/apis/gtfs/schema.graphqls index 932f886648e..db1e1721bf2 100644 --- a/application/src/main/resources/org/opentripplanner/apis/gtfs/schema.graphqls +++ b/application/src/main/resources/org/opentripplanner/apis/gtfs/schema.graphqls @@ -3224,6 +3224,7 @@ enum InputField { DATE_TIME FROM TO + VIA } """ diff --git a/application/src/test/java/org/opentripplanner/TestServerContext.java b/application/src/test/java/org/opentripplanner/TestServerContext.java index 9a96122d67f..62fbf076dd1 100644 --- a/application/src/test/java/org/opentripplanner/TestServerContext.java +++ b/application/src/test/java/org/opentripplanner/TestServerContext.java @@ -167,11 +167,6 @@ public static ViaCoordinateTransferFactory createViaTransferResolver( Graph graph, TransitService transitService ) { - return new DefaultViaCoordinateTransferFactory( - graph, - TestVertexLinker.of(graph), - transitService, - Duration.ofMinutes(30) - ); + return new DefaultViaCoordinateTransferFactory(graph, transitService, Duration.ofMinutes(30)); } } diff --git a/application/src/test/java/org/opentripplanner/apis/gtfs/mapping/routerequest/LegacyRouteRequestMapperTest.java b/application/src/test/java/org/opentripplanner/apis/gtfs/mapping/routerequest/LegacyRouteRequestMapperTest.java index 2b7f0769c23..b512662de9d 100644 --- a/application/src/test/java/org/opentripplanner/apis/gtfs/mapping/routerequest/LegacyRouteRequestMapperTest.java +++ b/application/src/test/java/org/opentripplanner/apis/gtfs/mapping/routerequest/LegacyRouteRequestMapperTest.java @@ -293,14 +293,14 @@ void via() { ); assertEquals( "[PassThroughViaLocation{label: a label, stopLocationIds: [F:stop1]}]", - routeRequest.getViaLocations().toString() + routeRequest.listViaLocations().toString() ); var noParamsReq = LegacyRouteRequestMapper.toRouteRequest( executionContext(decorateWithRequiredParams(Map.of())), context ); - assertEquals(List.of(), noParamsReq.getViaLocations()); + assertEquals(List.of(), noParamsReq.listViaLocations()); } private DataFetchingEnvironment executionContext(Map arguments) { diff --git a/application/src/test/java/org/opentripplanner/apis/gtfs/mapping/routerequest/RouteRequestMapperTest.java b/application/src/test/java/org/opentripplanner/apis/gtfs/mapping/routerequest/RouteRequestMapperTest.java index 7009b819b60..a0b0bede4e9 100644 --- a/application/src/test/java/org/opentripplanner/apis/gtfs/mapping/routerequest/RouteRequestMapperTest.java +++ b/application/src/test/java/org/opentripplanner/apis/gtfs/mapping/routerequest/RouteRequestMapperTest.java @@ -253,13 +253,13 @@ void via() { ); assertEquals( "[PassThroughViaLocation{label: a label, stopLocationIds: [F:stop1]}]", - routeRequest.getViaLocations().toString() + routeRequest.listViaLocations().toString() ); var noParamsReq = RouteRequestMapper.toRouteRequest( testCtx.executionContext(testCtx.basicRequest()), testCtx.context() ); - assertEquals(List.of(), noParamsReq.getViaLocations()); + assertEquals(List.of(), noParamsReq.listViaLocations()); } } diff --git a/application/src/test/java/org/opentripplanner/apis/transmodel/mapping/TripRequestMapperTest.java b/application/src/test/java/org/opentripplanner/apis/transmodel/mapping/TripRequestMapperTest.java index 321d3e83963..baa0a126424 100644 --- a/application/src/test/java/org/opentripplanner/apis/transmodel/mapping/TripRequestMapperTest.java +++ b/application/src/test/java/org/opentripplanner/apis/transmodel/mapping/TripRequestMapperTest.java @@ -326,7 +326,7 @@ void testViaLocations() { final List viaLocations = MAPPER.createRequest( executionContext(arguments) - ).getViaLocations(); + ).listViaLocations(); assertEquals( "PassThroughViaLocation{label: PTP1, stopLocationIds: [F:ST:stop1, F:ST:stop2, F:ST:stop3]}", viaLocations.get(0).toString() diff --git a/application/src/test/java/org/opentripplanner/routing/TestHalfEdges.java b/application/src/test/java/org/opentripplanner/routing/TestHalfEdges.java index aa128a7deaa..8cb4010b47c 100644 --- a/application/src/test/java/org/opentripplanner/routing/TestHalfEdges.java +++ b/application/src/test/java/org/opentripplanner/routing/TestHalfEdges.java @@ -2,6 +2,7 @@ import static com.google.common.collect.Iterables.filter; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -564,26 +565,20 @@ public void testTemporaryVerticesContainer() { .buildRequest(); try ( - var container = new TemporaryVerticesContainer( - graph, - TestVertexLinker.of(graph), - id -> Set.of(), - walking.from(), - walking.to(), - StreetMode.WALK, - StreetMode.WALK - ) + var container = TemporaryVerticesContainer.of(graph, TestVertexLinker.of(graph)) + .withFrom(walking.from(), StreetMode.WALK) + .withTo(walking.to(), StreetMode.WALK) + .build(); ) { - assertNotNull(container.getFromVertices()); - assertNotNull(container.getToVertices()); + assertFalse(container.fromVertices().isEmpty()); + assertFalse(container.toVertices().isEmpty()); ShortestPathTree spt = StreetSearchBuilder.of() .setHeuristic(new EuclideanRemainingWeightHeuristic()) .setRequest(walking) - .setVerticesContainer(container) + .setFrom(container.fromVertices()) + .setTo(container.toVertices()) .getShortestPathTree(); - GraphPath path = spt.getPath( - container.getToVertices().iterator().next() - ); + GraphPath path = spt.getPath(container.toVertices().iterator().next()); for (State s : path.states) { assertNotSame(s.getBackEdge(), top); } diff --git a/application/src/test/java/org/opentripplanner/routing/algorithm/StreetModeLinkingTest.java b/application/src/test/java/org/opentripplanner/routing/algorithm/StreetModeLinkingTest.java index 0aecfab5999..0695b86d982 100644 --- a/application/src/test/java/org/opentripplanner/routing/algorithm/StreetModeLinkingTest.java +++ b/application/src/test/java/org/opentripplanner/routing/algorithm/StreetModeLinkingTest.java @@ -15,7 +15,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; -import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -225,39 +224,29 @@ private void assertLinking( var linker = TestVertexLinker.of(graph); for (final StreetMode streetMode : streetModes) { try ( - var temporaryVertices = new TemporaryVerticesContainer( - graph, - linker, - id -> Set.of(), - location, - ANY_PLACE, - streetMode, - streetMode - ) + var temporaryVerticesContainer = TemporaryVerticesContainer.of(graph, linker) + .withFrom(location, streetMode) + .withTo(ANY_PLACE, streetMode) + .build() ) { assertFromLink( expectedFromStreetName.name(), streetMode, - temporaryVertices.getFromVertices().iterator().next() + temporaryVerticesContainer.fromVertices().iterator().next() ); } try ( - var temporaryVertices = new TemporaryVerticesContainer( - graph, - linker, - id -> Set.of(), - ANY_PLACE, - location, - streetMode, - streetMode - ) + var temporaryVerticesContainer = TemporaryVerticesContainer.of(graph, linker) + .withFrom(ANY_PLACE, streetMode) + .withTo(location, streetMode) + .build() ) { if (expectedToStreetName != null) { assertToLink( expectedToStreetName.name(), streetMode, - temporaryVertices.getToVertices().iterator().next() + temporaryVerticesContainer.toVertices().iterator().next() ); } } diff --git a/application/src/test/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/AccessEgressRouterTest.java b/application/src/test/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/AccessEgressRouterTest.java index 2ebc8c9e0f2..9b183f4cc71 100644 --- a/application/src/test/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/AccessEgressRouterTest.java +++ b/application/src/test/java/org/opentripplanner/routing/algorithm/raptoradapter/router/street/AccessEgressRouterTest.java @@ -258,24 +258,21 @@ private Collection findAccessEgressFromTo( var request = requestFromTo(from, to); try ( - var verticesContainer = new TemporaryVerticesContainer( - graph, - TestVertexLinker.of(graph), - id -> new DefaultTransitService(timetableRepository).findStopOrChildIds(id), - from, - to, - StreetMode.WALK, - StreetMode.WALK + var verticesContainer = TemporaryVerticesContainer.of(graph, TestVertexLinker.of(graph), id -> + new DefaultTransitService(timetableRepository).findStopOrChildIds(id) ) + .withFrom(from, StreetMode.WALK) + .withTo(to, StreetMode.WALK) + .build() ) { return AccessEgressRouter.findAccessEgresses( request, - verticesContainer, StreetRequest.DEFAULT, null, accessEgress, durationLimit, - maxStopCount + maxStopCount, + verticesContainer.createFromToViaVertexRequest() ); } } diff --git a/application/src/test/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/mappers/RaptorRequestMapperTest.java b/application/src/test/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/mappers/RaptorRequestMapperTest.java index c89683a44fc..44c5f863eaa 100644 --- a/application/src/test/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/mappers/RaptorRequestMapperTest.java +++ b/application/src/test/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/mappers/RaptorRequestMapperTest.java @@ -12,6 +12,7 @@ import java.time.ZonedDateTime; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.jupiter.api.Assertions; @@ -32,6 +33,9 @@ import org.opentripplanner.routing.api.request.via.VisitViaLocation; import org.opentripplanner.routing.via.ViaCoordinateTransferFactory; import org.opentripplanner.routing.via.model.ViaCoordinateTransfer; +import org.opentripplanner.street.model.vertex.LabelledIntersectionVertex; +import org.opentripplanner.street.model.vertex.Vertex; +import org.opentripplanner.street.search.request.FromToViaVertexRequest; import org.opentripplanner.transit.model._data.TimetableRepositoryForTest; import org.opentripplanner.transit.model.framework.FeedScopedId; import org.opentripplanner.transit.model.site.StopLocation; @@ -65,6 +69,12 @@ class RaptorRequestMapperTest { 10, 12.0 ); + private static final VisitViaLocation VISIT_VIA_LOCATION_COORDINATE = new VisitViaLocation( + "Via coordinate", + Duration.ofMinutes(10), + List.of(), + List.of(VIA_COORDINATE) + ); private static final CostLinearFunction R1 = CostLinearFunction.of("50 + 1.0x"); private static final CostLinearFunction R2 = CostLinearFunction.of("0 + 1.5x"); @@ -132,13 +142,7 @@ void testPassThroughPoints() { @Test void testViaCoordinate() { var req = requestBuilder(); - Duration minimumWaitTime = Duration.ofMinutes(10); - - req.withViaLocations( - List.of( - new VisitViaLocation("Via coordinate", minimumWaitTime, List.of(), List.of(VIA_COORDINATE)) - ) - ); + req.withViaLocations(List.of(VISIT_VIA_LOCATION_COORDINATE)); var result = map(req.buildRequest()); @@ -269,7 +273,15 @@ private static RaptorRequest map(RouteRequest request) { EGRESS, null, new DummyViaCoordinateTransferFactory(), - id -> IntStream.of(STOPS_MAP.get(id).getIndex()) + id -> IntStream.of(STOPS_MAP.get(id).getIndex()), + new FromToViaVertexRequest( + Set.of(), + Set.of(), + Map.of( + VISIT_VIA_LOCATION_COORDINATE.coordinateLocation(), + Set.of(new LabelledIntersectionVertex("viapoint", 1, 1, false, false)) + ) + ) ); } @@ -324,10 +336,10 @@ private static RouteRequestBuilder setFeaturesOnRequest( ) { return switch (feature) { case VIA_VISIT -> req.withViaLocations( - ListUtils.combine(req.buildRequest().getViaLocations(), List.of(VISIT_VIA_LOCATION)) + ListUtils.combine(req.buildRequest().listViaLocations(), List.of(VISIT_VIA_LOCATION)) ); case VIA_PASS_THROUGH -> req.withViaLocations( - ListUtils.combine(req.buildRequest().getViaLocations(), List.of(PASS_THROUGH_VIA_LOCATION)) + ListUtils.combine(req.buildRequest().listViaLocations(), List.of(PASS_THROUGH_VIA_LOCATION)) ); case TRANSIT_GROUP_PRIORITY -> req.withPreferences(p -> p.withTransit(t -> t.withRelaxTransitGroupPriority(RELAX_TRANSIT_GROUP_PRIORITY)) @@ -354,7 +366,7 @@ private static class DummyViaCoordinateTransferFactory implements ViaCoordinateT @Override public List createViaTransfers( RouteRequest request, - String ignore, + Vertex viaVertex, WgsCoordinate coordinate ) { // Make sure the input is the expected via-coordinate diff --git a/application/src/test/java/org/opentripplanner/routing/core/RouteRequestTest.java b/application/src/test/java/org/opentripplanner/routing/core/RouteRequestTest.java index e3dfc3a2d9e..e9147f52f96 100644 --- a/application/src/test/java/org/opentripplanner/routing/core/RouteRequestTest.java +++ b/application/src/test/java/org/opentripplanner/routing/core/RouteRequestTest.java @@ -114,7 +114,7 @@ void to() { @Test void via() { - assertEquals(VIA, subject.getViaLocations()); + assertEquals(VIA, subject.listViaLocations()); } @Test diff --git a/application/src/test/java/org/opentripplanner/routing/core/TemporaryVerticesContainerTest.java b/application/src/test/java/org/opentripplanner/routing/core/TemporaryVerticesContainerTest.java index 1feb5144a58..7a30a80b511 100644 --- a/application/src/test/java/org/opentripplanner/routing/core/TemporaryVerticesContainerTest.java +++ b/application/src/test/java/org/opentripplanner/routing/core/TemporaryVerticesContainerTest.java @@ -1,20 +1,32 @@ package org.opentripplanner.routing.core; +import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.EnumSet; import java.util.List; +import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.locationtech.jts.geom.GeometryFactory; +import org.opentripplanner.framework.geometry.GeometryUtils; import org.opentripplanner.framework.geometry.SphericalDistanceLibrary; +import org.opentripplanner.framework.geometry.WgsCoordinate; import org.opentripplanner.framework.i18n.I18NString; import org.opentripplanner.graph_builder.module.linking.TestVertexLinker; import org.opentripplanner.model.GenericLocation; import org.opentripplanner.routing.api.request.StreetMode; +import org.opentripplanner.routing.api.request.via.VisitViaLocation; +import org.opentripplanner.routing.api.response.InputField; +import org.opentripplanner.routing.api.response.RoutingErrorCode; +import org.opentripplanner.routing.error.RoutingValidationException; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.street.model.StreetTraversalPermission; import org.opentripplanner.street.model._data.StreetModelForTest; @@ -22,67 +34,247 @@ import org.opentripplanner.street.model.edge.TemporaryEdge; import org.opentripplanner.street.model.vertex.StreetVertex; import org.opentripplanner.street.model.vertex.TemporaryVertex; +import org.opentripplanner.street.model.vertex.TransitStopVertex; import org.opentripplanner.street.model.vertex.Vertex; import org.opentripplanner.street.search.TemporaryVerticesContainer; +import org.opentripplanner.street.search.TraverseMode; import org.opentripplanner.transit.model.framework.Deduplicator; +import org.opentripplanner.transit.model.framework.FeedScopedId; +import org.opentripplanner.transit.model.site.RegularStop; public class TemporaryVerticesContainerTest { + private final GeometryFactory gf = GeometryUtils.getGeometryFactory(); // Given: - // - a graph with 3 intersections/vertexes + // - a graph with 4 intersections/vertexes and a stop private final Graph g = new Graph(new Deduplicator()); private final StreetVertex a = StreetModelForTest.intersectionVertex("A", 1.0, 1.0); private final StreetVertex b = StreetModelForTest.intersectionVertex("B", 1.0, 0.0); private final StreetVertex c = StreetModelForTest.intersectionVertex("C", 0.0, 1.0); - private final List permanentVertexes = Arrays.asList(a, b, c); + private final StreetVertex d = StreetModelForTest.intersectionVertex("D", 0.0, 2.0); + private final FeedScopedId stopId = new FeedScopedId("test", "1"); + private final TransitStopVertex s = TransitStopVertex.of() + .withStop(RegularStop.of(stopId, () -> 1).withCoordinate(WgsCoordinate.GREENWICH).build()) + .build(); + private final List permanentVertexes = Arrays.asList(a, b, c, d, s); // - And travel *origin* is 0,4 degrees on the road from B to A private final GenericLocation from = GenericLocation.fromCoordinate(1.0, 0.4); // - and *destination* is slightly off 0.7 degrees on road from C to A private final GenericLocation to = GenericLocation.fromCoordinate(0.701, 1.001); - private TemporaryVerticesContainer subject; + private final List viaLocations = List.of( + new VisitViaLocation("Via1", null, List.of(), List.of(new WgsCoordinate(0.0, 1.5))), + new VisitViaLocation("Via2", null, List.of(FeedScopedId.parse("F:1")), List.of()), + new VisitViaLocation( + "Via3", + null, + List.of(FeedScopedId.parse("F:2")), + List.of(new WgsCoordinate(0.1, 1.9)) + ) + ); // - and some roads @BeforeEach - public void setup() { + void setup() { permanentVertexes.forEach(g::addVertex); - createStreetEdge(a, b, "a -> b"); - createStreetEdge(b, a, "b -> a"); + createStreetEdge(a, b, "a -> b WALK"); + createStreetEdge(a, b, "a -> b CAR", StreetTraversalPermission.CAR); + createStreetEdge(b, a, "b -> a WALK"); + createStreetEdge(b, a, "b -> a CAR", StreetTraversalPermission.CAR); createStreetEdge(a, c, "a -> c"); + createStreetEdge(c, d, "c -> d"); + createStreetEdge(d, c, "c -> d"); + createStreetEdge(a, d, "a -> d"); g.index(); + g.calculateConvexHull(); } @Test - public void temporaryChangesRemovedOnClose() { - // When - the container is created - subject = new TemporaryVerticesContainer( - g, - TestVertexLinker.of(g), - id -> List.of(), - from, - to, - StreetMode.WALK, - StreetMode.WALK + void createFromToViaVertexRequest() { + var fromWithStops = new GenericLocation("From with stops", stopId, 1.0, 0.4); + var subject = TemporaryVerticesContainer.of(g, TestVertexLinker.of(g), Set::of) + .withFrom(fromWithStops, StreetMode.WALK) + .withTo(to, StreetMode.WALK) + .withVia(viaLocations, EnumSet.of(StreetMode.WALK)) + .build(); + var request = subject.createFromToViaVertexRequest(); + var fromVertices = request.findVertices(fromWithStops); + assertThat(fromVertices).isNotEmpty(); + assertEquals(subject.fromVertices(), fromVertices); + var toVertices = request.findVertices(to); + assertThat(toVertices).isNotEmpty(); + assertEquals(subject.toVertices(), toVertices); + assertThat(request.fromStops()).isNotEmpty(); + assertEquals(subject.fromStopVertices(), request.fromStops()); + assertThat(request.toStops()).isEmpty(); + assertEquals(subject.toStopVertices(), request.toStops()); + var firstViaVertices = request.findVertices(viaLocations.get(0).coordinateLocation()); + assertThat(firstViaVertices).isNotEmpty(); + assertEquals( + subject.verticesByLocation().get(viaLocations.get(0).coordinateLocation()), + firstViaVertices + ); + var thirdViaVertices = request.findVertices(viaLocations.get(2).coordinateLocation()); + assertThat(thirdViaVertices).isNotEmpty(); + assertEquals( + subject.verticesByLocation().get(viaLocations.get(2).coordinateLocation()), + thirdViaVertices ); + } + + @Test + void temporaryChangesRemovedOnClose() { + // When - the container is created + var subject = TemporaryVerticesContainer.of(g, TestVertexLinker.of(g)) + .withFrom(from, StreetMode.WALK) + .withTo(to, StreetMode.WALK) + .build(); // Then: - originAndDestinationInsertedCorrect(); + originAndDestinationInsertedCorrect(subject, false); + cleanUpAndValidate(subject); + } - // And When: - subject.close(); + @Test + void multipleModes() { + try ( + var subject = TemporaryVerticesContainer.of(g, TestVertexLinker.of(g)) + .withFrom(from, EnumSet.of(StreetMode.WALK, StreetMode.CAR_TO_PARK)) + .withTo(to, StreetMode.WALK) + .build() + ) { + // When - the container is created - // Then - permanent vertexes - for (Vertex v : permanentVertexes) { - // - does not reference the any temporary nodes anymore - for (Edge e : v.getIncoming()) { - assertVertexEdgeIsNotReferencingTemporaryElements(v, e, e.getFromVertex()); - } - for (Edge e : v.getOutgoing()) { - assertVertexEdgeIsNotReferencingTemporaryElements(v, e, e.getToVertex()); - } + // Then: + assertThat(subject.fromVertices()).hasSize(1); + var fromOutgoing = subject.fromVertices().iterator().next().getOutgoing(); + assertThat(fromOutgoing).hasSize(4); + assertTrue(outgoingEdgeIsTraversableWith(fromOutgoing, TraverseMode.WALK)); + assertTrue(outgoingEdgeIsTraversableWith(fromOutgoing, TraverseMode.CAR)); } } + @Test + void temporaryChangesRemovedOnCloseWithVia() { + // When - the container is created + var subject = TemporaryVerticesContainer.of(g, TestVertexLinker.of(g)) + .withFrom(from, StreetMode.WALK) + .withTo(to, StreetMode.WALK) + .withVia(viaLocations, EnumSet.of(StreetMode.WALK)) + .build(); + + // Then: + locationsInsertedCorrect(subject); + cleanUpAndValidate(subject); + } + + @Test + void locationNotFoundException() { + // Stops not found + var fromException = assertThrows(RoutingValidationException.class, () -> + TemporaryVerticesContainer.of(g, TestVertexLinker.of(g)) + .withFrom( + new GenericLocation("Stop not found", new FeedScopedId("F", "stop1"), null, null), + StreetMode.WALK + ) + .build() + .close() + ); + assertThat(fromException.getRoutingErrors()).hasSize(1); + var fromError = fromException.getRoutingErrors().getFirst(); + assertEquals(InputField.FROM_PLACE, fromError.inputField); + assertEquals(RoutingErrorCode.LOCATION_NOT_FOUND, fromError.code); + + var toException = assertThrows(RoutingValidationException.class, () -> + TemporaryVerticesContainer.of(g, TestVertexLinker.of(g)) + .withFrom(from, StreetMode.WALK) + .withTo( + new GenericLocation("Stop not found", new FeedScopedId("F", "stop1"), null, null), + StreetMode.WALK + ) + .build() + .close() + ); + + assertThat(toException.getRoutingErrors()).hasSize(1); + var toError = toException.getRoutingErrors().getFirst(); + assertEquals(InputField.TO_PLACE, toError.inputField); + assertEquals(RoutingErrorCode.LOCATION_NOT_FOUND, toError.code); + + // Coordinate not found (but in bounds) + var viaException = assertThrows(RoutingValidationException.class, () -> + TemporaryVerticesContainer.of(g, TestVertexLinker.of(g)) + .withFrom(from, StreetMode.WALK) + .withTo(to, StreetMode.WALK) + .withVia( + List.of(new VisitViaLocation("Via1", null, List.of(), List.of(new WgsCoordinate(10, 0)))), + EnumSet.of(StreetMode.WALK) + ) + .build() + .close() + ); + assertThat(viaException.getRoutingErrors()).hasSize(1); + var viaError = viaException.getRoutingErrors().getFirst(); + assertEquals(InputField.INTERMEDIATE_PLACE, viaError.inputField); + assertEquals(RoutingErrorCode.LOCATION_NOT_FOUND, viaError.code); + } + + @Test + void locationOutsideBoundsException() { + var exception = assertThrows(RoutingValidationException.class, () -> + TemporaryVerticesContainer.of(g, TestVertexLinker.of(g)) + .withFrom(GenericLocation.fromCoordinate(0, 0.02), StreetMode.WALK) + .withTo(GenericLocation.fromCoordinate(0, 0.01), StreetMode.WALK) + .withVia( + List.of(new VisitViaLocation("Via1", null, List.of(), List.of(new WgsCoordinate(78, 0)))), + EnumSet.of(StreetMode.WALK) + ) + .build() + .close() + ); + + assertThat(exception.getRoutingErrors()).hasSize(3); + var fromError = exception.getRoutingErrors().get(0); + assertEquals(InputField.FROM_PLACE, fromError.inputField); + assertEquals(RoutingErrorCode.OUTSIDE_BOUNDS, fromError.code); + var toError = exception.getRoutingErrors().get(1); + assertEquals(InputField.TO_PLACE, toError.inputField); + assertEquals(RoutingErrorCode.OUTSIDE_BOUNDS, toError.code); + var viaError = exception.getRoutingErrors().get(2); + assertEquals(InputField.INTERMEDIATE_PLACE, viaError.inputField); + assertEquals(RoutingErrorCode.OUTSIDE_BOUNDS, viaError.code); + } + + @Test + void walkingBetterThanTransitException() { + var exception = assertThrows(RoutingValidationException.class, () -> + TemporaryVerticesContainer.of(g, TestVertexLinker.of(g)) + .withFrom(from, StreetMode.WALK) + .withTo(from, StreetMode.WALK) + .build() + .close() + ); + + assertThat(exception.getRoutingErrors()).hasSize(1); + var fromError = exception.getRoutingErrors().getFirst(); + assertNull(fromError.inputField); + assertEquals(RoutingErrorCode.WALKING_BETTER_THAN_TRANSIT, fromError.code); + } + + @Test + void cleanUpWhenExceptionThrown() { + assertThrows(RoutingValidationException.class, () -> + TemporaryVerticesContainer.of(g, TestVertexLinker.of(g)) + .withFrom(from, StreetMode.WALK) + .withTo(from, StreetMode.WALK) + .withVia(viaLocations, EnumSet.of(StreetMode.WALK)) + .build() + .close() + ); + + validateCleanup(); + } + private static > T findAllReachableVertexes( Vertex vertex, boolean forward, @@ -103,14 +295,21 @@ private static > T findAllReachableVertexes( return list; } - private void originAndDestinationInsertedCorrect() { + private void originAndDestinationInsertedCorrect( + TemporaryVerticesContainer subject, + boolean hasViaLocations + ) { // Then - the origin and destination is - assertEquals("Origin", subject.getFromVertices().iterator().next().getDefaultName()); - assertEquals("Destination", subject.getToVertices().iterator().next().getDefaultName()); + var originVertices = subject.fromVertices(); + assertThat(originVertices).hasSize(1); + assertEquals("Origin", originVertices.iterator().next().getDefaultName()); + var destinationVertices = subject.toVertices(); + assertThat(destinationVertices).hasSize(1); + assertEquals("Destination", destinationVertices.iterator().next().getDefaultName()); // And - from the origin Collection vertexesReachableFromOrigin = findAllReachableVertexes( - subject.getFromVertices().iterator().next(), + subject.fromVertices().iterator().next(), true, new ArrayList<>() ); @@ -120,11 +319,17 @@ private void originAndDestinationInsertedCorrect() { assertTrue(vertexesReachableFromOrigin.contains("A"), msg); assertTrue(vertexesReachableFromOrigin.contains("B"), msg); assertTrue(vertexesReachableFromOrigin.contains("C"), msg); + assertTrue(vertexesReachableFromOrigin.contains("D"), msg); assertTrue(vertexesReachableFromOrigin.contains("Destination"), msg); + if (hasViaLocations) { + assertTrue(vertexesReachableFromOrigin.contains("Via1"), msg); + assertTrue(vertexesReachableFromOrigin.contains("Via3"), msg); + } + // And - from the destination we can backtrack Collection vertexesReachableFromDestination = findAllReachableVertexes( - subject.getToVertices().iterator().next(), + subject.toVertices().iterator().next(), false, new ArrayList<>() ); @@ -139,7 +344,120 @@ private void originAndDestinationInsertedCorrect() { assertFalse(vertexesReachableFromDestination.contains("C"), msg); } + private void locationsInsertedCorrect(TemporaryVerticesContainer subject) { + originAndDestinationInsertedCorrect(subject, true); + // Then - only via locations with coordinates are included + var verticesByLocation = subject.verticesByLocation(); + assertThat(verticesByLocation).hasSize(4); + var firstViaVertices = verticesByLocation.get(viaLocations.get(0).coordinateLocation()); + assertThat(firstViaVertices).hasSize(1); + assertEquals("Via1", firstViaVertices.iterator().next().getDefaultName()); + var thirdViaVertices = verticesByLocation.get(viaLocations.get(2).coordinateLocation()); + assertThat(thirdViaVertices).hasSize(1); + assertEquals("Via3", thirdViaVertices.iterator().next().getDefaultName()); + + // And - from the first via location + Collection vertexesReachableFromFirstViaForward = findAllReachableVertexes( + firstViaVertices.iterator().next(), + true, + new ArrayList<>() + ); + Collection vertexesReachableFromFirstViaBackward = findAllReachableVertexes( + firstViaVertices.iterator().next(), + false, + new ArrayList<>() + ); + String firstForwardMsg = + "Forward reachable vertexes from the first via location: " + + vertexesReachableFromFirstViaForward; + String firstBackwardMsg = + "Backward reachable vertexes from the first via location: " + + vertexesReachableFromFirstViaBackward; + + assertTrue(vertexesReachableFromFirstViaForward.contains("C"), firstForwardMsg); + assertTrue(vertexesReachableFromFirstViaForward.contains("D"), firstForwardMsg); + assertTrue(vertexesReachableFromFirstViaForward.contains("Via1"), firstForwardMsg); + + assertTrue(vertexesReachableFromFirstViaBackward.contains("A"), firstBackwardMsg); + assertTrue(vertexesReachableFromFirstViaBackward.contains("B"), firstBackwardMsg); + assertTrue(vertexesReachableFromFirstViaBackward.contains("C"), firstBackwardMsg); + assertTrue(vertexesReachableFromFirstViaBackward.contains("D"), firstBackwardMsg); + assertTrue(vertexesReachableFromFirstViaBackward.contains("Origin"), firstBackwardMsg); + assertTrue(vertexesReachableFromFirstViaBackward.contains("Via1"), firstBackwardMsg); + assertTrue(vertexesReachableFromFirstViaBackward.contains("Via3"), firstBackwardMsg); + + // And - from the third via location + Collection vertexesReachableFromThirdViaForward = findAllReachableVertexes( + thirdViaVertices.iterator().next(), + true, + new ArrayList<>() + ); + Collection vertexesReachableFromThirdViaBackward = findAllReachableVertexes( + thirdViaVertices.iterator().next(), + false, + new ArrayList<>() + ); + String thirdForwardMsg = + "Forward reachable vertexes from the third via location: " + + vertexesReachableFromThirdViaForward; + String thirdBackwardMsg = + "Backward reachable vertexes from the third via location: " + + vertexesReachableFromThirdViaBackward; + + assertTrue(vertexesReachableFromFirstViaForward.contains("C"), thirdForwardMsg); + assertTrue(vertexesReachableFromFirstViaForward.contains("D"), thirdForwardMsg); + assertTrue(vertexesReachableFromFirstViaForward.contains("Via1"), thirdForwardMsg); + + assertTrue(vertexesReachableFromFirstViaBackward.contains("A"), thirdBackwardMsg); + assertTrue(vertexesReachableFromFirstViaBackward.contains("B"), thirdBackwardMsg); + assertTrue(vertexesReachableFromFirstViaBackward.contains("Origin"), thirdBackwardMsg); + assertTrue(vertexesReachableFromFirstViaBackward.contains("Via3"), thirdBackwardMsg); + } + + private void cleanUpAndValidate(TemporaryVerticesContainer subject) { + // And When: + subject.close(); + + // Then - validate temporary elements are removed + validateCleanup(); + } + + private void validateCleanup() { + // Then - permanent vertexes + for (Vertex v : permanentVertexes) { + // - does not reference the any temporary nodes anymore + for (Edge e : v.getIncoming()) { + assertVertexEdgeIsNotReferencingTemporaryElements(v, e, e.getFromVertex()); + } + for (Edge e : v.getOutgoing()) { + assertVertexEdgeIsNotReferencingTemporaryElements(v, e, e.getToVertex()); + } + } + assertTrue(g.getEdges().stream().noneMatch(e -> e instanceof TemporaryEdge)); + } + + private boolean outgoingEdgeIsTraversableWith(Collection edges, TraverseMode mode) { + return edges + .stream() + .anyMatch(outgoing -> + outgoing + .getToVertex() + .getOutgoingStreetEdges() + .stream() + .anyMatch(edge -> edge.canTraverse(mode)) + ); + } + private void createStreetEdge(StreetVertex v0, StreetVertex v1, String name) { + createStreetEdge(v0, v1, name, StreetTraversalPermission.PEDESTRIAN); + } + + private void createStreetEdge( + StreetVertex v0, + StreetVertex v1, + String name, + StreetTraversalPermission permission + ) { double dist = SphericalDistanceLibrary.distance(v0.getCoordinate(), v1.getCoordinate()); StreetModelForTest.streetEdgeBuilder(v0, v1, dist, StreetTraversalPermission.ALL) .withName(I18NString.of(name)) diff --git a/application/src/test/java/org/opentripplanner/street/integration/BarrierRoutingTest.java b/application/src/test/java/org/opentripplanner/street/integration/BarrierRoutingTest.java index 77cdd38d05e..499688ae29e 100644 --- a/application/src/test/java/org/opentripplanner/street/integration/BarrierRoutingTest.java +++ b/application/src/test/java/org/opentripplanner/street/integration/BarrierRoutingTest.java @@ -32,6 +32,7 @@ import org.opentripplanner.routing.api.request.request.StreetRequest; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.impl.GraphPathFinder; +import org.opentripplanner.street.search.LinkingContext; import org.opentripplanner.street.search.TemporaryVerticesContainer; import org.opentripplanner.street.search.TraverseMode; import org.opentripplanner.test.support.ResourceLoader; @@ -183,17 +184,18 @@ private static String computePolyline( options.accept(builder); - var temporaryVertices = new TemporaryVerticesContainer( + var temporaryVerticesContainer = new TemporaryVerticesContainer(); + var linkingContext = LinkingContext.of( + temporaryVerticesContainer, graph, - TestVertexLinker.of(graph), - id -> List.of(), - from, - to, - streetMode, - streetMode - ); + TestVertexLinker.of(graph) + ) + .withFrom(from, streetMode) + .withTo(to, streetMode) + .build(); var gpf = new GraphPathFinder(null); - var paths = gpf.graphPathFinderEntryPoint(builder.buildRequest(), temporaryVertices); + var fromToViaVertexRequest = linkingContext.createFromToViaVertexRequest(); + var paths = gpf.graphPathFinderEntryPoint(builder.buildRequest(), fromToViaVertexRequest); GraphPathToItineraryMapper graphPathToItineraryMapper = new GraphPathToItineraryMapper( ZoneIds.BERLIN, @@ -206,7 +208,7 @@ private static String computePolyline( assertAll(assertions.apply(itineraries)); Geometry legGeometry = itineraries.get(0).legs().get(0).legGeometry(); - temporaryVertices.close(); + temporaryVerticesContainer.close(); return EncodedPolyline.encode(legGeometry).points(); } diff --git a/application/src/test/java/org/opentripplanner/street/integration/BicycleRoutingTest.java b/application/src/test/java/org/opentripplanner/street/integration/BicycleRoutingTest.java index 063dceeb779..7871fd1ef22 100644 --- a/application/src/test/java/org/opentripplanner/street/integration/BicycleRoutingTest.java +++ b/application/src/test/java/org/opentripplanner/street/integration/BicycleRoutingTest.java @@ -5,7 +5,6 @@ import static org.opentripplanner.test.support.PolylineAssert.assertThatPolylinesAreEqual; import java.time.Instant; -import java.util.List; import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Geometry; import org.opentripplanner.ConstantsForTests; @@ -22,6 +21,7 @@ import org.opentripplanner.routing.core.VehicleRoutingOptimizeType; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.impl.GraphPathFinder; +import org.opentripplanner.street.search.LinkingContext; import org.opentripplanner.street.search.TemporaryVerticesContainer; import org.opentripplanner.street.search.TraverseMode; import org.opentripplanner.test.support.ResourceLoader; @@ -86,17 +86,20 @@ private static String computePolyline(Graph graph, GenericLocation from, Generic }) .buildRequest(); - var temporaryVertices = new TemporaryVerticesContainer( + var temporaryVerticesContainer = new TemporaryVerticesContainer(); + var linkingContext = LinkingContext.of( + temporaryVerticesContainer, graph, - TestVertexLinker.of(graph), - id -> List.of(), - request.from(), - request.to(), - request.journey().direct().mode(), - request.journey().direct().mode() - ); + TestVertexLinker.of(graph) + ) + .withFrom(from, StreetMode.BIKE) + .withTo(to, StreetMode.BIKE) + .build(); var gpf = new GraphPathFinder(null); - var paths = gpf.graphPathFinderEntryPoint(request, temporaryVertices); + var paths = gpf.graphPathFinderEntryPoint( + request, + linkingContext.createFromToViaVertexRequest() + ); GraphPathToItineraryMapper graphPathToItineraryMapper = new GraphPathToItineraryMapper( ZoneIds.BERLIN, @@ -105,7 +108,7 @@ private static String computePolyline(Graph graph, GenericLocation from, Generic ); var itineraries = graphPathToItineraryMapper.mapItineraries(paths); - temporaryVertices.close(); + temporaryVerticesContainer.close(); // make sure that we only get BICYCLE legs itineraries.forEach(i -> diff --git a/application/src/test/java/org/opentripplanner/street/integration/CarRoutingTest.java b/application/src/test/java/org/opentripplanner/street/integration/CarRoutingTest.java index 2c78b6ead97..9e07f282c84 100644 --- a/application/src/test/java/org/opentripplanner/street/integration/CarRoutingTest.java +++ b/application/src/test/java/org/opentripplanner/street/integration/CarRoutingTest.java @@ -5,7 +5,6 @@ import static org.opentripplanner.test.support.PolylineAssert.assertThatPolylinesAreEqual; import java.time.Instant; -import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -23,6 +22,7 @@ import org.opentripplanner.routing.api.request.request.StreetRequest; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.impl.GraphPathFinder; +import org.opentripplanner.street.search.LinkingContext; import org.opentripplanner.street.search.TemporaryVerticesContainer; import org.opentripplanner.street.search.TraverseMode; import org.opentripplanner.test.support.ResourceLoader; @@ -134,17 +134,21 @@ private static String computePolyline(Graph graph, GenericLocation from, Generic .withTo(to) .withJourney(jb -> jb.withDirect(new StreetRequest(StreetMode.CAR))) .buildRequest(); - var temporaryVertices = new TemporaryVerticesContainer( + + var temporaryVerticesContainer = new TemporaryVerticesContainer(); + var linkingContext = LinkingContext.of( + temporaryVerticesContainer, graph, - TestVertexLinker.of(graph), - id -> List.of(), - from, - to, - StreetMode.CAR, - StreetMode.CAR - ); + TestVertexLinker.of(graph) + ) + .withFrom(from, StreetMode.CAR) + .withTo(to, StreetMode.CAR) + .build(); var gpf = new GraphPathFinder(null); - var paths = gpf.graphPathFinderEntryPoint(request, temporaryVertices); + var paths = gpf.graphPathFinderEntryPoint( + request, + linkingContext.createFromToViaVertexRequest() + ); GraphPathToItineraryMapper graphPathToItineraryMapper = new GraphPathToItineraryMapper( ZoneIds.BERLIN, @@ -153,7 +157,7 @@ private static String computePolyline(Graph graph, GenericLocation from, Generic ); var itineraries = graphPathToItineraryMapper.mapItineraries(paths); - temporaryVertices.close(); + temporaryVerticesContainer.close(); // make sure that we only get CAR legs itineraries.forEach(i -> diff --git a/application/src/test/java/org/opentripplanner/street/integration/SplitEdgeTurnRestrictionsTest.java b/application/src/test/java/org/opentripplanner/street/integration/SplitEdgeTurnRestrictionsTest.java index 5a59911ca3f..a8b4528ae8a 100644 --- a/application/src/test/java/org/opentripplanner/street/integration/SplitEdgeTurnRestrictionsTest.java +++ b/application/src/test/java/org/opentripplanner/street/integration/SplitEdgeTurnRestrictionsTest.java @@ -6,7 +6,6 @@ import java.time.Instant; import java.time.LocalDateTime; -import java.util.List; import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Geometry; import org.opentripplanner.ConstantsForTests; @@ -166,17 +165,18 @@ private static String computeCarPolyline(Graph graph, GenericLocation from, Gene .withJourney(jb -> jb.withDirect(new StreetRequest(StreetMode.CAR))) .buildRequest(); - var temporaryVertices = new TemporaryVerticesContainer( + var temporaryVerticesContainer = TemporaryVerticesContainer.of( graph, - TestVertexLinker.of(graph), - id -> List.of(), - from, - to, - StreetMode.CAR, - StreetMode.CAR - ); + TestVertexLinker.of(graph) + ) + .withFrom(from, StreetMode.CAR) + .withTo(to, StreetMode.CAR) + .build(); var gpf = new GraphPathFinder(null); - var paths = gpf.graphPathFinderEntryPoint(request, temporaryVertices); + var paths = gpf.graphPathFinderEntryPoint( + request, + temporaryVerticesContainer.createFromToViaVertexRequest() + ); GraphPathToItineraryMapper graphPathToItineraryMapper = new GraphPathToItineraryMapper( ZoneIds.BERLIN, @@ -185,7 +185,7 @@ private static String computeCarPolyline(Graph graph, GenericLocation from, Gene ); var itineraries = graphPathToItineraryMapper.mapItineraries(paths); - temporaryVertices.close(); + temporaryVerticesContainer.close(); // make sure that we only get CAR legs itineraries.forEach(i -> diff --git a/application/src/test/java/org/opentripplanner/street/integration/WalkRoutingTest.java b/application/src/test/java/org/opentripplanner/street/integration/WalkRoutingTest.java index 3f58fc3635f..ba55f6391b9 100644 --- a/application/src/test/java/org/opentripplanner/street/integration/WalkRoutingTest.java +++ b/application/src/test/java/org/opentripplanner/street/integration/WalkRoutingTest.java @@ -15,10 +15,12 @@ import org.opentripplanner.graph_builder.module.linking.TestVertexLinker; import org.opentripplanner.model.GenericLocation; import org.opentripplanner.routing.api.request.RouteRequest; +import org.opentripplanner.routing.api.request.StreetMode; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.impl.GraphPathFinder; import org.opentripplanner.street.model.edge.Edge; import org.opentripplanner.street.model.vertex.Vertex; +import org.opentripplanner.street.search.LinkingContext; import org.opentripplanner.street.search.TemporaryVerticesContainer; import org.opentripplanner.street.search.state.State; import org.opentripplanner.test.support.ResourceLoader; @@ -93,20 +95,17 @@ private static List> route( .withTo(to) .withArriveBy(arriveBy) .buildRequest(); - - try ( - var temporaryVertices = new TemporaryVerticesContainer( + try (var temporaryVerticesContainer = new TemporaryVerticesContainer()) { + var linkingContext = LinkingContext.of( + temporaryVerticesContainer, graph, - TestVertexLinker.of(graph), - id -> List.of(), - request.from(), - request.to(), - request.journey().direct().mode(), - request.journey().direct().mode() + TestVertexLinker.of(graph) ) - ) { + .withFrom(from, StreetMode.WALK) + .withTo(to, StreetMode.WALK) + .build(); var gpf = new GraphPathFinder(null); - return gpf.graphPathFinderEntryPoint(request, temporaryVertices); + return gpf.graphPathFinderEntryPoint(request, linkingContext.createFromToViaVertexRequest()); } } } diff --git a/application/src/test/java/org/opentripplanner/street/search/TemporaryVerticesContainerTest.java b/application/src/test/java/org/opentripplanner/street/search/TemporaryVerticesContainerTest.java index 096f47bc56b..2e3a29c7027 100644 --- a/application/src/test/java/org/opentripplanner/street/search/TemporaryVerticesContainerTest.java +++ b/application/src/test/java/org/opentripplanner/street/search/TemporaryVerticesContainerTest.java @@ -62,38 +62,28 @@ class TemporaryVerticesContainerTest { @Test void coordinates() { - var container = new TemporaryVerticesContainer( - graph, - TestVertexLinker.of(graph), - Set::of, - GenericLocation.fromCoordinate(stopA.getLat(), stopA.getLon()), - GenericLocation.fromCoordinate(stopD.getLat(), stopD.getLon()), - WALK, - WALK - ); - assertThat(container.getFromVertices()).hasSize(1); - assertThat(container.getToVertices()).hasSize(1); + var container = TemporaryVerticesContainer.of(graph, TestVertexLinker.of(graph)) + .withFrom(GenericLocation.fromCoordinate(stopA.getLat(), stopA.getLon()), WALK) + .withTo(GenericLocation.fromCoordinate(stopD.getLat(), stopD.getLon()), WALK) + .build(); + assertThat(container.fromVertices()).hasSize(1); + assertThat(container.toVertices()).hasSize(1); - assertThat(container.getFromStopVertices()).isEmpty(); - assertThat(container.getToStopVertices()).isEmpty(); + assertThat(container.fromStopVertices()).isEmpty(); + assertThat(container.toStopVertices()).isEmpty(); } @Test void stopId() { - var container = new TemporaryVerticesContainer( - graph, - TestVertexLinker.of(graph), - Set::of, - stopToLocation(stopA), - stopToLocation(stopB), - WALK, - WALK - ); - assertEquals(stopA, toStop(container.getFromVertices())); - assertEquals(stopB, toStop(container.getToVertices())); + var container = TemporaryVerticesContainer.of(graph, TestVertexLinker.of(graph), Set::of) + .withFrom(stopToLocation(stopA), WALK) + .withTo(stopToLocation(stopB), WALK) + .build(); + assertEquals(stopA, toStop(container.fromVertices())); + assertEquals(stopB, toStop(container.toVertices())); - assertEquals(stopA, toStop(container.getFromStopVertices())); - assertEquals(stopB, toStop(container.getToVertices())); + assertEquals(stopA, toStop(container.fromStopVertices())); + assertEquals(stopB, toStop(container.toStopVertices())); } @Test @@ -101,31 +91,21 @@ void stationId() { var mapping = ImmutableMultimap.builder() .putAll(OMEGA_ID, stopC.getId(), stopD.getId()) .build(); - var container = new TemporaryVerticesContainer( - graph, - TestVertexLinker.of(graph), - mapping::get, - GenericLocation.fromStopId("station", OMEGA_ID.getFeedId(), OMEGA_ID.getId()), - stopToLocation(stopB), - WALK, - WALK - ); - assertThat(toStops(container.getFromVertices())).containsExactly(stopC, stopD); - assertThat(toStops(container.getFromStopVertices())).containsExactly(stopC, stopD); + var container = TemporaryVerticesContainer.of(graph, TestVertexLinker.of(graph), mapping::get) + .withFrom(GenericLocation.fromStopId("station", OMEGA_ID.getFeedId(), OMEGA_ID.getId()), WALK) + .withTo(stopToLocation(stopB), WALK) + .build(); + assertThat(toStops(container.fromVertices())).containsExactly(stopC, stopD); + assertThat(toStops(container.fromStopVertices())).containsExactly(stopC, stopD); } @Test void centroid() { - var container = new TemporaryVerticesContainer( - graph, - TestVertexLinker.of(graph), - Set::of, - GenericLocation.fromStopId("station", ALPHA_ID.getFeedId(), ALPHA_ID.getId()), - stopToLocation(stopB), - WALK, - WALK - ); - var fromVertices = List.copyOf(container.getFromVertices()); + var container = TemporaryVerticesContainer.of(graph, TestVertexLinker.of(graph)) + .withFrom(GenericLocation.fromStopId("station", ALPHA_ID.getFeedId(), ALPHA_ID.getId()), WALK) + .withTo(stopToLocation(stopB), WALK) + .build(); + var fromVertices = List.copyOf(container.fromVertices()); assertThat(fromVertices).hasSize(1); var station = ((StationCentroidVertex) fromVertices.getFirst()).getStation(); diff --git a/application/src/test/java/org/opentripplanner/street/search/request/FromToViaVertexRequestTest.java b/application/src/test/java/org/opentripplanner/street/search/request/FromToViaVertexRequestTest.java new file mode 100644 index 00000000000..234167dd99c --- /dev/null +++ b/application/src/test/java/org/opentripplanner/street/search/request/FromToViaVertexRequestTest.java @@ -0,0 +1,103 @@ +package org.opentripplanner.street.search.request; + +import static java.util.Map.entry; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.opentripplanner.framework.geometry.WgsCoordinate; +import org.opentripplanner.model.GenericLocation; +import org.opentripplanner.routing.api.request.via.VisitViaLocation; +import org.opentripplanner.street.model.vertex.LabelledIntersectionVertex; +import org.opentripplanner.street.model.vertex.TransitStopVertex; +import org.opentripplanner.street.model.vertex.Vertex; +import org.opentripplanner.transit.model.framework.FeedScopedId; +import org.opentripplanner.transit.model.site.RegularStop; + +class FromToViaVertexRequestTest { + + private static final GenericLocation FROM = new GenericLocation( + "from", + null, + WgsCoordinate.GREENWICH.latitude(), + WgsCoordinate.GREENWICH.longitude() + ); + private static final Set FROM_VERTICES = Set.of(createVertex("from")); + private static final GenericLocation TO = new GenericLocation( + "to", + null, + WgsCoordinate.GREENWICH.latitude(), + WgsCoordinate.GREENWICH.longitude() + ); + private static final Set TO_VERTICES = Set.of(createVertex("to")); + private static final Set FROM_STOPS = Set.of( + createStopVertexForTest("from-stop") + ); + private static final Set TO_STOPS = Set.of(createStopVertexForTest("to-stop")); + private static final VisitViaLocation VISIT_VIA_LOCATION = new VisitViaLocation( + "Via coordinate", + Duration.ofMinutes(10), + List.of(), + List.of(WgsCoordinate.GREENWICH) + ); + private static final Set VIA_VERTICES = Set.of(createVertex("via")); + private static final FromToViaVertexRequest FROM_TO_VIA_VERTEX_REQUEST = + new FromToViaVertexRequest( + FROM_STOPS, + TO_STOPS, + Map.ofEntries( + entry(FROM, FROM_VERTICES), + entry(TO, TO_VERTICES), + entry(VISIT_VIA_LOCATION.coordinateLocation(), VIA_VERTICES) + ) + ); + + @Test + void fromStops() { + assertEquals(FROM_STOPS, FROM_TO_VIA_VERTEX_REQUEST.fromStops()); + } + + @Test + void toStops() { + assertEquals(TO_STOPS, FROM_TO_VIA_VERTEX_REQUEST.toStops()); + } + + @Test + void findVertices() { + assertEquals(FROM_VERTICES, FROM_TO_VIA_VERTEX_REQUEST.findVertices(FROM)); + assertEquals(TO_VERTICES, FROM_TO_VIA_VERTEX_REQUEST.findVertices(TO)); + assertEquals( + VIA_VERTICES, + FROM_TO_VIA_VERTEX_REQUEST.findVertices(VISIT_VIA_LOCATION.coordinateLocation()) + ); + } + + @Test + void testToString() { + assertEquals( + "FromToViaVertexRequest{fromStops: [{test:from-stop lat,lng=51.48,0.0}], " + + "toStops: [{test:to-stop lat,lng=51.48,0.0}], " + + "verticesByLocation: [to (51.48, 0.0)=[{to lat,lng=1.0,1.0}], " + + "Via coordinate (51.48, 0.0)=[{via lat,lng=1.0,1.0}], " + + "from (51.48, 0.0)=[{from lat,lng=1.0,1.0}]]}", + FROM_TO_VIA_VERTEX_REQUEST.toString() + ); + } + + private static Vertex createVertex(String name) { + return new LabelledIntersectionVertex(name, 1, 1, false, false); + } + + private static TransitStopVertex createStopVertexForTest(String id) { + return TransitStopVertex.of() + .withStop( + RegularStop.of(new FeedScopedId("test", id), () -> 1) + .withCoordinate(WgsCoordinate.GREENWICH) + .build() + ) + .build(); + } +}