package SuMoC.backend.routing.services; import SuMoC.backend.carta.CartaClient; import SuMoC.backend.geocoding.AddressDTO; import SuMoC.backend.geocoding.GeoCodingService; import SuMoC.backend.routing.config.AdHocRoutingProperties; import SuMoC.backend.routing.config.OnCallRoutingProperties; import SuMoC.backend.routing.dtos.RouteDTO; import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; import SuMoC.backend.routing.dtos.StepDTO; import SuMoC.backend.routing.exceptions.NoCarRouteFoundException; import SuMoC.backend.routing.exceptions.NoCarbonEmissionFoundException; import SuMoC.backend.trip.Modality; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; import sumoc.backend.carta.client.model.Direction; import sumoc.backend.carta.client.model.Route; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; @Service @RequiredArgsConstructor public class RoutingService { private final GeoCodingService geoCodingService; private final CartaClient cartaClient; private final AlternativeFilterService alternativeFilterService; private final OnCallRoutingProperties onCallRoutingProperties; private final AdHocRoutingProperties adHocRoutingProperties; /** * Makes an individual call to the CARTA API and returns a direction future. */ private CompletableFuture getCartaFuture( RoutingAlternativeRequestDTO requestDTO, String mode, String types, int alternatives ) { return cartaClient.asyncGetRoute( requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(), requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(), mode, requestDTO.getArrivalTime(), null, alternatives, // alternatives null, // walkingSpeed null, // transferTime TODO what is default? adapt? types, null, // range requestDTO.getOriginLat() + "," + requestDTO.getOriginLon() ); } /** * Makes concurrent direction calls to CARTA for all modes requested + car as baseline. * Possible keys of the returned Map: * - car (always) * - walk (optional) * - bike (optional) * - transit (optional) */ private HashMap getPossibleDirectionsFromCarta(RoutingAlternativeRequestDTO requestDTO) { Map> futuresByMode = new HashMap<>(); assert requestDTO.getRoutingPreferencesDTO() != null; // serves as baseline futuresByMode.put("car", getCartaFuture(requestDTO, "driving", "", 1)); // type string for carta api List typeList = new ArrayList<>(); // add request futures for all modes request by user + assemble type string for a possible transit directions request for (Modality modality : requestDTO.getRoutingPreferencesDTO().getModalitiesToConsider()) { switch (modality) { case WALKING -> futuresByMode.put("walk", getCartaFuture(requestDTO, "walking", "", 1)); case BICYCLE -> futuresByMode.put("bike", getCartaFuture(requestDTO, "cycling", "", 1)); case BUS -> { typeList.add("3"); // bus typeList.add("8"); // trolleybus } // case ESCOOTER -> typeList.add("X"); TODO - check if this and bike should be included in transit or separate case TRAM -> typeList.add("0"); case TRAIN -> { typeList.add("1"); // subway typeList.add("2"); // rail typeList.add("9"); // monorail } } } if (!typeList.isEmpty()) { // if any public transit the app allows toggling is selcted we add the funny transit types and make the transit request typeList.add("4"); // Ferry typeList.add("5"); // cablecar typeList.add("6"); // gondola typeList.add("7"); // funicular String types = String.join(",", typeList); futuresByMode.put("transit", getCartaFuture(requestDTO, "transit", types, 3)); } // return all future results as list when resvoled HashMap directions = new HashMap<>(); for (Map.Entry> entry : futuresByMode.entrySet()) { directions.put(entry.getKey(), entry.getValue().join()); } return directions; } /** * Gets possible routes from CARTA, converts them to our format and applies filter to only provide acceptable solutions without excessive additional travel time. * This is the public method for alternatives explicitly asked for by the client. */ public List determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) { List routes = getPossibleAlternativeRoutes(requestDTO); routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties); return routes; } /** * Public alternative retrieval method which is used to check for alternatives we suggest to user via notification * right after user finished the trip. * Similar to determineAlternativeRoutesOnUserRequest but here we apply stricter thresholds for alternatives * and also apply weather filtering (if enabled) to not suggest routes the user definitly would not have consideres. */ public List determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) { assert requestDTO.getRoutingPreferencesDTO() != null; List routes = getPossibleAlternativeRoutes(requestDTO); routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties); if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) { routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties); } return routes; } /** * Returns possible alternative routes for the request - no sanity filtering regarding travel times etc. is applied. */ private List getPossibleAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) { assert requestDTO.getRoutingPreferencesDTO() != null; HashMap directionMap = getPossibleDirectionsFromCarta(requestDTO); ArrayList suggestedAlternatives = new ArrayList<>(); // Fetch origin and destination addresses concurrently var addressesMono = Mono.zip( geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()), geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon()) ); var addressesTuple = addressesMono.block(); AddressDTO originAddress = addressesTuple.getT1(); AddressDTO destinationAddress = addressesTuple.getT2(); // Setting up car data for baseline Route carRoute; try { carRoute = directionMap.get("car").getRoutes().getFirst(); } catch (NullPointerException e) { throw new NoCarRouteFoundException("No car route to compare to was found."); } double carCarbondDioxide; try { carCarbondDioxide = carRoute.getEmission().getCarbonDioxide(); } catch (NullPointerException e) { throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route."); } if (directionMap.containsKey("bike")) { Direction bikeDirection = directionMap.get("bike"); if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) { Route bikeRoute = bikeDirection.getRoutes().getFirst(); ArrayList steps = new ArrayList<>(); steps.add(new StepDTO( Modality.BICYCLE, null, bikeRoute.getDistance() ) ); RouteDTO routeDTO = new RouteDTO( originAddress, null, bikeRoute.getSourceCoordinate().getLatitude(), bikeRoute.getSourceCoordinate().getLongitude(), destinationAddress, null, bikeRoute.getTargetCoordinate().getLatitude(), bikeRoute.getTargetCoordinate().getLongitude(), requestDTO.getArrivalTime().minusSeconds(bikeRoute.getDuration()), requestDTO.getArrivalTime(), steps, carCarbondDioxide, bikeRoute.getDuration() - carRoute.getDuration(), 0.0 ); suggestedAlternatives.add(routeDTO); } } if (directionMap.containsKey("walk")) { Direction walkDirection = directionMap.get("walk"); if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) { Route walkRoute = walkDirection.getRoutes().getFirst(); ArrayList steps = new ArrayList<>(); steps.add(new StepDTO( Modality.WALKING, null, walkRoute.getDistance() )); RouteDTO routeDTO = new RouteDTO( originAddress, null, walkRoute.getSourceCoordinate().getLatitude(), walkRoute.getSourceCoordinate().getLongitude(), destinationAddress, null, walkRoute.getTargetCoordinate().getLatitude(), walkRoute.getTargetCoordinate().getLongitude(), requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()), requestDTO.getArrivalTime(), steps, carCarbondDioxide, walkRoute.getDuration() - carRoute.getDuration(), 0.0 ); suggestedAlternatives.add(routeDTO); } } if (directionMap.containsKey("transit")) { Direction transitDirection = directionMap.get("transit"); if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) { for (Route route : transitDirection.getRoutes()) { CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route); RouteDTO routeDTO = new RouteDTO( originAddress, routeProcessor.getFirstStopName(), route.getSourceCoordinate().getLatitude(), route.getSourceCoordinate().getLongitude(), destinationAddress, routeProcessor.getLastStopName(), route.getTargetCoordinate().getLatitude(), route.getTargetCoordinate().getLongitude(), requestDTO.getArrivalTime().minusSeconds(route.getDuration()), requestDTO.getArrivalTime(), routeProcessor.getSteps(), carCarbondDioxide - route.getEmission().getCarbonDioxide(), route.getDuration() - carRoute.getDuration(), route.getEmission().getCarbonDioxide() ); suggestedAlternatives.add(routeDTO); } } } return suggestedAlternatives; } }