Merge branch 'route_alternatives' into trend_notifications
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good

# Conflicts:
#	src/main/resources/application.properties
This commit is contained in:
2026-01-09 15:25:59 +01:00
12 changed files with 405 additions and 102 deletions
@@ -54,7 +54,7 @@ public class CartaClient {
destination,
mode.toLowerCase(), // possible values: walking, driving, cycling
arrivalTime.getEpochSecond(),
departureTime.getEpochSecond(),
departureTime != null ? departureTime.getEpochSecond() : null,
alternatives,
walkingSpeed,
transferTime,
@@ -3,8 +3,9 @@ package SuMoC.backend.routing;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
import SuMoC.backend.routing.services.RoutingService;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import org.apache.commons.lang3.NotImplementedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
@@ -12,14 +13,17 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import sumoc.backend.carta.client.model.Route;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
@RestController
@RequestMapping("/routing/alternative")
public class RoutingController {
private final Logger logger = Logger.getLogger(RoutingController.class.getName());
private final RoutingService routingService;
@Autowired
@@ -27,8 +31,8 @@ public class RoutingController {
this.routingService = routingService;
}
// TODO operation description + how to handle preferences (optional, if not provided use saved users prefs or default
@PostMapping("/request")
@Schema(description = "Calculates alternative, sustainable routes for the request. The delta of departure and arrival in the requestdto is used as baseline to determine if alternatives are acceptable.")
public ResponseEntity<List<RouteDTO>> requestAlternativeRoutes(@Valid @RequestBody RoutingAlternativeRequestDTO routingAlternativeRequestDTO) {
try {
if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) { // Use default preferences if none are provided
@@ -37,10 +41,11 @@ public class RoutingController {
routingAlternativeRequestDTO.setRoutingPreferencesDTO(preferences);
}
var routeDTOs = routingService.getAlternativeRoute(routingAlternativeRequestDTO);
var routeDTOs = routingService.determineAlternativeRoutes(routingAlternativeRequestDTO);
return ResponseEntity.ok(routeDTOs);
} catch (WebClientRequestException e) {
// nominatim container is not up yet, we return mock
logger.warning("Nominatim service is not available. Returning mock route data. Error: " + e.getMessage());
ArrayList<RouteDTO> mockDTOs = new ArrayList<>();
mockDTOs.add(RouteDTO.getMockRouteDTO());
mockDTOs.add(RouteDTO.getMockRouteDTO());
@@ -8,6 +8,20 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
public class RoutingProperties {
private int toleratedAdditionalTravelSeconds = 15 * 60;
private int toleratedAdditionalPhysicalActivitiesSeconds = 45 * 60;
/**
* Multiplier of how much more travel time is tolerated for alternative routing.
*/
private double acceptableAdditionalMultiplierRegular = 1.30;
/**
* Multiplier of accepted additional travel time for users that wish more physical activity.
*/
private double acceptableAdditionalMultiplierPrefersPhysical = 1.50;
/**
* Minimum of accepted additional travel time for regular users which is always accepted.
*/
private Integer minimumAcceptedAdditionalSecondsRegular = 10 * 60;
/**
* Minimum of accepted additional travel time for users that wish more physical activity.
*/
private Integer minimumAcceptedAdditionalSecondsPrefersPhysicalActivity = 15 * 60;
}
@@ -44,10 +44,12 @@ public class RouteDTO {
private List<StepDTO> steps;
@Schema(description = "Amount of CO2e savings in gramm compared to a car trip for the same route.")
private double co2Savings;
@Schema(description = "CO2e emission of this route.")
private double co2Emissions;
@Schema(description = "The temporal difference in minutes compared to the original route the user requested alternatives for.")
private double timeDifferenceSeconds;
public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, Instant startDateTime, Instant endDateTime, List<StepDTO> steps, double co2Savings, double timeDifferenceSeconds) {
public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, Instant startDateTime, Instant endDateTime, List<StepDTO> steps, double co2Savings, double timeDifferenceSeconds, double co2Emissions) {
this.startAddress = startAddress;
this.firstStopName = firstStopName;
this.startLat = startLat;
@@ -60,6 +62,7 @@ public class RouteDTO {
this.endDateTime = endDateTime;
this.steps = steps;
this.co2Savings = co2Savings;
this.co2Emissions = co2Emissions;
this.timeDifferenceSeconds = timeDifferenceSeconds;
}
@@ -106,7 +109,8 @@ public class RouteDTO {
Instant.now(),
new ArrayList<StepDTO>(),
120.5f,
+16.3f
+16.3f,
20
);
dto.steps.add(new StepDTO(
Modality.WALKING,
@@ -125,4 +129,15 @@ public class RouteDTO {
));
return dto;
}
public long getDurationSeconds() {
return endDateTime.getEpochSecond() - startDateTime.getEpochSecond();
}
/**
* We consider routes that only consist of walking and cycling steps as physical activity.
*/
private boolean isPhysicalActivity() {
return steps.stream().allMatch(step -> step.getModality() == Modality.WALKING || step.getModality() == Modality.BICYCLE);
}
}
@@ -0,0 +1,58 @@
package SuMoC.backend.routing.services;
import SuMoC.backend.routing.config.RoutingProperties;
import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* This services bundles functionality to filter suggested alternative routes to prevent us from suggesting
* routes with unacceptable additional travel time etc.
*/
@Service
@RequiredArgsConstructor
public class AlternativeFilterService {
private final RoutingProperties routingProperties;
/**
* We apply the following logic to filter out trips:
* Regular:
* - A minimum of X minutes extra is acceptable
* - Y% more travel time is acceptable
* If user wants more phyiscal activity, for cycling and walking:
* - A minimum of Z minutes extra is acceptable
* - W% more travel time is acceptable
*/
public List<RouteDTO> filterForAdditionalTravelTime(RoutingAlternativeRequestDTO alternativeRequestDTO, List<RouteDTO> alternatives) {
List<RouteDTO> filteredAlternatives = new ArrayList<>();
long originalTravelTimeSeconds = alternativeRequestDTO.getArrivalTime().getEpochSecond() - alternativeRequestDTO.getDepartureTime().getEpochSecond();
double toleratedMaximumRegular = originalTravelTimeSeconds * routingProperties.getAcceptableAdditionalMultiplierRegular();
double toleratedMaximumPhysical = originalTravelTimeSeconds * routingProperties.getAcceptableAdditionalMultiplierPrefersPhysical();
for (RouteDTO routeDTO : alternatives) {
long travelTimeDeltaSeconds = routeDTO.getDurationSeconds() - originalTravelTimeSeconds;
if (alternativeRequestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity()
|| (long) travelTimeDeltaSeconds < toleratedMaximumPhysical) {
filteredAlternatives.add(routeDTO);
}
} else {
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsRegular()
|| (long) travelTimeDeltaSeconds < toleratedMaximumRegular) {
filteredAlternatives.add(routeDTO);
}
}
}
return filteredAlternatives;
}
}
@@ -0,0 +1,81 @@
package SuMoC.backend.routing.services;
import SuMoC.backend.routing.dtos.StepDTO;
import SuMoC.backend.trip.Modality;
import sumoc.backend.carta.client.model.Route;
import sumoc.backend.carta.client.model.Step;
import java.util.ArrayList;
import java.util.List;
/**
* Processes a Carta Route and extracts StepDTOs and first , last stop name.
*/
public class CartaTransitRouteProcessor {
private final Route cartaRoute;
private List<StepDTO> steps = null;
private String firstStopName = null;
private String lastStopName = null;
public CartaTransitRouteProcessor(Route cartaRoute) {
this.cartaRoute = cartaRoute;
this.process();
}
/**
* Extracts information from the route.
*/
public void process() {
ArrayList<StepDTO> steps = new ArrayList<>();
assert cartaRoute.getSteps() != null;
for (Step step : cartaRoute.getSteps()) {
// Get first stop name
if (this.firstStopName == null && step.getType().equals("TransitStep")) {
this.firstStopName = step.getStops().getFirst().getName();
}
// always set last stop as lastStopName so it will match in the end
if (step.getType().equals("TransitStep")) {
this.lastStopName = step.getStops().getLast().getName();
}
Modality stepModality = step.getType().equals("TransitStep")
? Modality.fromCartaString(step.getLine().getType().toString())
: Modality.fromCartaString(step.getType());
steps.add(new StepDTO(
stepModality,
step.getType().equals("TransitStep") ? step.getLine().getCode() : null,
step.getDistance()
));
}
this.steps = steps;
}
public List<StepDTO> getSteps() {
if (this.steps == null) {
throw new IllegalStateException("Getter called before processing");
}
return this.steps;
}
public String getFirstStopName() {
if (this.firstStopName == null) {
throw new IllegalStateException("Getter called before processing");
}
return this.firstStopName;
}
public String getLastStopName() {
if (this.lastStopName == null) {
throw new IllegalStateException("Getter called before processing");
}
return this.lastStopName;
}
}
@@ -1,16 +1,15 @@
package SuMoC.backend.routing;
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.RoutingProperties;
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 org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import sumoc.backend.carta.client.model.Direction;
@@ -23,20 +22,14 @@ import java.util.Map;
import java.util.concurrent.CompletableFuture;
@Service
@RequiredArgsConstructor
public class RoutingService {
private final GeoCodingService geoCodingService;
private final CartaClient cartaClient;
private final RoutingProperties routingProperties;
@Autowired
public RoutingService(CartaClient cartaClient, RoutingProperties routingProperties, GeoCodingService geoCodingService) {
this.cartaClient = cartaClient;
this.routingProperties = routingProperties;
this.geoCodingService = geoCodingService;
}
private final AlternativeFilterService alternativeFilterService;
/**
* Makes an individual call to the CARTA API and returns a direction future.
@@ -52,7 +45,7 @@ public class RoutingService {
requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(),
mode,
requestDTO.getArrivalTime(),
requestDTO.getDepartureTime(),
null,
alternatives, // alternatives
null, // walkingSpeed
null, // transferTime TODO what is default? adapt?
@@ -113,7 +106,20 @@ public class RoutingService {
return directions;
}
public List<RouteDTO> getAlternativeRoute(RoutingAlternativeRequestDTO requestDTO) {
/**
* Gets possible routes from CARTA, converts them to our format and applies filter to only provide acceptable solutions without excessive additional travel time.
*
* @param requestDTO
* @return
*/
public List<RouteDTO> determineAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) {
List<RouteDTO> routes = fetchAndConvertRoutes(requestDTO);
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes);
return routes;
}
private List<RouteDTO> fetchAndConvertRoutes(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap<String, Direction> directionMap = getPossibleDirectionsFromCarta(requestDTO);
ArrayList<RouteDTO> suggestedAlternatives = new ArrayList<>();
@@ -127,12 +133,6 @@ public class RoutingService {
AddressDTO originAddress = addressesTuple.getT1();
AddressDTO destinationAddress = addressesTuple.getT2();
// Define max additional time for sustainable alternatives
int maxAdditionalTimeNonPhysical = routingProperties.getToleratedAdditionalTravelSeconds();
int maxAdditionalTimePhysical = requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity() ?
routingProperties.getToleratedAdditionalPhysicalActivitiesSeconds() :
routingProperties.getToleratedAdditionalTravelSeconds();
// Setting up car data for baseline
Route carRoute;
try {
@@ -151,33 +151,31 @@ public class RoutingService {
Direction bikeDirection = directionMap.get("bike");
if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) {
Route bikeRoute = bikeDirection.getRoutes().getFirst();
int durationDifferenceCar = bikeRoute.getDuration() - carRoute.getDuration();
if (durationDifferenceCar < maxAdditionalTimePhysical) {
ArrayList<StepDTO> steps = new ArrayList<>();
steps.add(new StepDTO(
Modality.BICYCLE,
null,
bikeRoute.getDistance()
)
);
ArrayList<StepDTO> 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()
);
suggestedAlternatives.add(routeDTO);
}
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);
}
}
@@ -185,40 +183,60 @@ public class RoutingService {
Direction walkDirection = directionMap.get("walk");
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
Route walkRoute = walkDirection.getRoutes().getFirst();
int durationDifferenceCar = walkRoute.getDuration() - carRoute.getDuration();
if (durationDifferenceCar < maxAdditionalTimePhysical) {
ArrayList<StepDTO> steps = new ArrayList<>();
steps.add(new StepDTO(
Modality.WALKING,
null,
walkRoute.getDistance()
));
ArrayList<StepDTO> 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,
null,
walkRoute.getSourceCoordinate().getLatitude(),
walkRoute.getSourceCoordinate().getLongitude(),
routeProcessor.getFirstStopName(),
route.getSourceCoordinate().getLatitude(),
route.getSourceCoordinate().getLongitude(),
destinationAddress,
null,
walkRoute.getTargetCoordinate().getLatitude(),
walkRoute.getTargetCoordinate().getLongitude(),
requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()),
routeProcessor.getLastStopName(),
route.getTargetCoordinate().getLatitude(),
route.getTargetCoordinate().getLongitude(),
requestDTO.getArrivalTime().minusSeconds(route.getDuration()),
requestDTO.getArrivalTime(),
steps,
carCarbondDioxide,
walkRoute.getDuration() - carRoute.getDuration()
routeProcessor.getSteps(),
carCarbondDioxide - route.getEmission().getCarbonDioxide(),
route.getDuration() - carRoute.getDuration(),
route.getEmission().getCarbonDioxide()
);
suggestedAlternatives.add(routeDTO);
}
}
}
// TODO public transit
// TODO if consider weather
// get weather for origin
// if bad, remove walking and biking options
return suggestedAlternatives;
}
}
+15 -1
View File
@@ -10,5 +10,19 @@ public enum Modality {
TRAIN,
CAR,
MOTORCYCLE,
TAXI
TAXI;
public static Modality fromCartaString(String cartaType) {
return switch (cartaType.toLowerCase()) {
case "tram", "subway" -> TRAM;
case "rail", "monorail" -> TRAIN;
case "bus", "trolleybus" -> BUS;
case "ferry", "cablecar", "gondola", "funicular" ->
throw new UnsupportedOperationException("Transport type needs to be added to backend: " + cartaType);
// these are to dervive modality from carta step type
case "walkingstep" -> WALKING;
case "cyclingstep" -> BICYCLE;
default -> throw new IllegalArgumentException("Unknown CARTA modality: " + cartaType);
};
}
}