diff --git a/src/main/java/SuMoC/backend/h3/H3Service.java b/src/main/java/SuMoC/backend/h3/H3Service.java index 421ac88..e4d2851 100644 --- a/src/main/java/SuMoC/backend/h3/H3Service.java +++ b/src/main/java/SuMoC/backend/h3/H3Service.java @@ -61,7 +61,7 @@ public class H3Service { } /** - * Get all cells within k distance of the given cell (including the cell itself). + * Get all cells within k distance of the given cell (excluding the cell it self). * K-ring distance means cells reachable in k steps on the hexagonal grid. * * @param cellId H3 cell ID as hex string @@ -69,11 +69,12 @@ public class H3Service { * @return List of H3 cell IDs including the origin cell */ public List getKRingNeighbors(String cellId, int k) { - return h3.gridDisk(cellId, k); + return h3.gridRing(cellId, k); } /** * Get K-ring neighbors using the configured route pattern resolution distance. + * Ring means the center cell is not included. * Useful for finding nearby locations when matching trip patterns. * * @param cellId H3 cell ID as hex string diff --git a/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java b/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java new file mode 100644 index 0000000..996042a --- /dev/null +++ b/src/main/java/SuMoC/backend/regulartrip/config/DetectorConfiguration.java @@ -0,0 +1,22 @@ +package SuMoC.backend.regulartrip.config; + +import SuMoC.backend.regulartrip.detectionapproaches.Detector; +import SuMoC.backend.regulartrip.detectionapproaches.IterativeClusterer; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class DetectorConfiguration { + + @Bean + @ConditionalOnProperty( + prefix = "regulartripdetection", + name = "detection-algorithm", + havingValue = "iterative", + matchIfMissing = true + ) + public Detector iterativeClusterer(RegularTripDetectionProperties properties) { + return new IterativeClusterer(properties); + } +} diff --git a/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java b/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java new file mode 100644 index 0000000..a2b238e --- /dev/null +++ b/src/main/java/SuMoC/backend/regulartrip/config/RegularTripDetectionProperties.java @@ -0,0 +1,35 @@ +package SuMoC.backend.regulartrip.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "regulartripdetection") +public class RegularTripDetectionProperties { + + // TODO at end check if this is really right place for these vals + /** + * Minimum number of trips a user must have made between the same start and end locations + * for those trips to be considered regular. + */ + private Integer minTripsForRegularity = 2; + + /** + * Time window in days to look back for detecting regular trips. + */ + private Integer detectionTimeWindowDays = 30; + + /** + * Maximum time difference in minutes between trips to be considered the same regular trip. + */ + private Integer timeWindowSeconds = 90 * 60; + + /** + * Number of times the iterative algorithm is run on randomly shuffled trip lists to pick best results. + */ + private Integer iterativeShuffleAmounts = 5; + + private String detectionAlgorithm = "iterative"; +} diff --git a/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/Detector.java b/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/Detector.java new file mode 100644 index 0000000..0817dfb --- /dev/null +++ b/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/Detector.java @@ -0,0 +1,14 @@ +package SuMoC.backend.regulartrip.detectionapproaches; + +import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO; +import SuMoC.backend.trip.dtos.RegularTripDetectionDTO; + +import java.util.List; + +public interface Detector { + + /** + * Core function to analyze a list of one users trips for regular trips. Assumes all trips have the same modality and user. + */ + List detectRegularTrips(List trips); +} diff --git a/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClusterer.java b/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClusterer.java new file mode 100644 index 0000000..a242c71 --- /dev/null +++ b/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClusterer.java @@ -0,0 +1,192 @@ +package SuMoC.backend.regulartrip.detectionapproaches; + +import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties; +import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO; +import SuMoC.backend.trip.dtos.RegularTripDetectionDTO; + +import java.time.LocalTime; +import java.time.ZoneId; +import java.util.*; + +/** + * This is the first approach of a regular trip detection algorithm. + */ +public class IterativeClusterer implements Detector { + + private final RegularTripDetectionProperties properties; + + public IterativeClusterer(RegularTripDetectionProperties properties) { + this.properties = properties; + } + + @Override + public List detectRegularTrips(List trips) { + // Step 1: Init potential detected trip for all trips + HashMap baseDetectedTripsMap = initDetectedTripsMap(trips); + // Step 2: Find trips supported by min number of supporters + + List> iterationResults = new ArrayList<>(); + for (int i = 0; i < properties.getIterativeShuffleAmounts(); i++) { + // Deep copy the map for each iteration + HashMap iterationMap = deepCopyDetectedTripsMap(baseDetectedTripsMap); + Collections.shuffle(trips); + iterationResults.add(aggregateToSupportedDetections(iterationMap, trips, properties.getMinTripsForRegularity())); + } + + return pickBestIteration(iterationResults); + } + + /** + * Picks the best detection results by picking iteration with the highest total number of supporters. + */ + private List pickBestIteration(List> iterationResults) { + return iterationResults.stream() + .max(Comparator.comparingInt(iteration -> + iteration.stream() + // subtracting 1 to avoid inflation by self supporting -> less detections with more supporters are better + .mapToInt(detection -> detection.getSupportingTrips().size() - 1) + .sum())) + .orElse(List.of()); + } + + /** + * Takes a map with potential detected regular trips and checks against a list of trips which are supported + * If a trip supports another detected regular trips, its own regular trip is removed. + */ + private List aggregateToSupportedDetections( + HashMap potentialDetectedRegularTrips, + List trips, + int necessarySupporters + ) { + // We need to dupe deletions with this list since we cant modify other list entries while iterating over it + Set deletedDetections = new HashSet<>(); + Set deletedTrips = new HashSet<>(); + + for (Map.Entry entry : potentialDetectedRegularTrips.entrySet()) { + if (deletedDetections.contains(entry.getKey())) continue; + + // Check for all other trips if they support this detected regular trip + for (RegularTripDetectionDTO trip : trips) { + if (deletedTrips.contains(trip.getTripId())) continue; + // prevent checking against trip the detected regular trip stems from + if (entry.getKey() == trip.getTripId()) continue; + + if (supportsDetectedRegularTrip(entry.getValue(), trip)) { + entry.getValue().getSupportingTrips().add(trip); + // remove trip's own potential regular trip since its now a supporter + deletedDetections.add(trip.getTripId()); + // block it from supporting more than one trips + deletedTrips.add(trip.getTripId()); + // if a detectedtrip gets its first supporter, it should not be used to support other trips + deletedTrips.add(entry.getKey()); + } + + } + } + + // Generate final results + List detectedTrips = new ArrayList<>(); + for (Map.Entry entry : potentialDetectedRegularTrips.entrySet()) { + if (deletedDetections.contains(entry.getKey())) continue; + if (entry.getValue().getSupportingTrips().size() >= necessarySupporters) { + detectedTrips.add(entry.getValue()); + } + } + return detectedTrips; + } + + /** + * This method holds the core logic to determine if a trip supports a detected regular trip. + */ + private boolean supportsDetectedRegularTrip(DetectedRegularTripDTO regularTrip, RegularTripDetectionDTO trip) { + // Conditions: + // 1. same day of week + if (regularTrip.getDayOfWeek() == trip.getDayOfTheWeek()) { + // 2. Departure and arrival within window + if (isWithinTimeWindow(regularTrip, trip)) { + // 3. Same start and end area + if (sameStartAndEndCellArea(regularTrip, trip)) { + return true; + } + } + } + return false; + } + + /** + * We consider start and end to be the same place when cells match or are direct neighbours. + */ + private boolean sameStartAndEndCellArea(DetectedRegularTripDTO regularTripDTO, RegularTripDetectionDTO trip) { + if (trip.getStartH3Cell().equals(regularTripDTO.getStartH3Center()) || regularTripDTO.getStartH3neighbours().contains(trip.getStartH3Cell())) { + return trip.getEndH3Cell().equals(regularTripDTO.getEndH3Center()) || regularTripDTO.getEndH3Neighbours().contains(trip.getEndH3Cell()); + } + return false; + } + + private boolean isWithinTimeWindow(DetectedRegularTripDTO regularTrip, RegularTripDetectionDTO trip) { + LocalTime departure = LocalTime.ofInstant(trip.getStartTime(), ZoneId.systemDefault()); + LocalTime arrival = LocalTime.ofInstant(trip.getEndTime(), ZoneId.systemDefault()); + if (departure.isAfter(regularTrip.getDepartureWindowStart()) && departure.isBefore(regularTrip.getDepartureWindowEnd())) { + return arrival.isAfter(regularTrip.getArrivalWindowStart()) && arrival.isBefore(regularTrip.getArrivalWindowEnd()); + } + return false; + } + + /** + * Converts all trips to a detected regular trip, using original tripId as map key + */ + private HashMap initDetectedTripsMap(List trips) { + HashMap potentialDetectedTrips = new HashMap<>(); + + for (RegularTripDetectionDTO trip : trips) { + LocalTime departure = LocalTime.ofInstant(trip.getStartTime(), ZoneId.systemDefault()); + LocalTime arrival = LocalTime.ofInstant(trip.getEndTime(), ZoneId.systemDefault()); + + potentialDetectedTrips.put(trip.getTripId(), DetectedRegularTripDTO.builder() + .modality(trip.getMainModality()) + .userId(trip.getUserId()) + .dayOfWeek(trip.getDayOfTheWeek()) + .departureWindowStart(departure.minusSeconds(properties.getTimeWindowSeconds() / 2)) + .departureWindowEnd(departure.plusSeconds(properties.getTimeWindowSeconds() / 2)) + .arrivalWindowStart(arrival.minusSeconds(properties.getTimeWindowSeconds() / 2)) + .arrivalWindowEnd(arrival.plusSeconds(properties.getTimeWindowSeconds() / 2)) + .startH3Center(trip.getStartH3Cell()) + .endH3Center(trip.getEndH3Cell()) + .startH3neighbours(trip.getStartH3CellKRingNeighboors()) + .endH3Neighbours(trip.getEndH3CellKRingNeighboors()) + .supportingTrips(new ArrayList(List.of(trip))) + .build()); + } + return potentialDetectedTrips; + } + + private HashMap deepCopyDetectedTripsMap( + HashMap original) { + + HashMap copy = new HashMap<>(); + + for (Map.Entry entry : original.entrySet()) { + DetectedRegularTripDTO originalDto = entry.getValue(); + + // Create new DTO with copied supporting trips list + DetectedRegularTripDTO copiedDto = DetectedRegularTripDTO.builder() + .modality(originalDto.getModality()) + .userId(originalDto.getUserId()) + .dayOfWeek(originalDto.getDayOfWeek()) + .departureWindowStart(originalDto.getDepartureWindowStart()) + .departureWindowEnd(originalDto.getDepartureWindowEnd()) + .arrivalWindowStart(originalDto.getArrivalWindowStart()) + .arrivalWindowEnd(originalDto.getArrivalWindowEnd()) + .startH3Center(originalDto.getStartH3Center()) + .endH3Center(originalDto.getEndH3Center()) + .startH3neighbours(originalDto.getStartH3neighbours()) + .endH3Neighbours(originalDto.getEndH3Neighbours()) + .supportingTrips(new ArrayList<>(originalDto.getSupportingTrips())) // New list + .build(); + + copy.put(entry.getKey(), copiedDto); + } + + return copy; + } +} diff --git a/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java b/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java new file mode 100644 index 0000000..d3c9091 --- /dev/null +++ b/src/main/java/SuMoC/backend/regulartrip/dtos/DetectedRegularTripDTO.java @@ -0,0 +1,31 @@ +package SuMoC.backend.regulartrip.dtos; + +import SuMoC.backend.trip.Modality; +import SuMoC.backend.trip.dtos.RegularTripDetectionDTO; +import lombok.*; + +import java.time.LocalTime; +import java.util.List; + +/** + * A DTO representing the details of a detected regular trip. + */ +@Builder +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class DetectedRegularTripDTO { + private long userId; + private Modality modality; + private int dayOfWeek; + private LocalTime departureWindowStart; + private LocalTime departureWindowEnd; + private LocalTime arrivalWindowStart; + private LocalTime arrivalWindowEnd; + private String startH3Center; + private String endH3Center; + private List startH3neighbours; + private List endH3Neighbours; + private List supportingTrips; +} diff --git a/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java b/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java new file mode 100644 index 0000000..3890f1a --- /dev/null +++ b/src/main/java/SuMoC/backend/regulartrip/services/RegularTripDetectionService.java @@ -0,0 +1,55 @@ +package SuMoC.backend.regulartrip.services; + +import SuMoC.backend.regulartrip.config.RegularTripDetectionProperties; +import SuMoC.backend.regulartrip.detectionapproaches.Detector; +import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO; +import SuMoC.backend.trip.Modality; +import SuMoC.backend.trip.TripMapper; +import SuMoC.backend.trip.TripRepository; +import SuMoC.backend.trip.dtos.RegularTripDetectionDTO; +import org.springframework.stereotype.Service; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +@Service +public class RegularTripDetectionService { + + RegularTripDetectionProperties properties; + + TripRepository tripRepository; + + TripMapper tripMapper; + + Detector tripDetector; + + /** + * Detects regular trips for all users based on saved trip data and RegularTripDetectionProperties. + * This is the main method that orchestrates the detection process and should be used to detect trips + * we want to suggest alternatives for. + */ + public HashMap> detectRegularCarTrips() { + var tripsByUser = getTripsByUser(Modality.CAR); + + // TODO this could be parallelized in the future + HashMap> results = new HashMap<>(); + for (Long userId : tripsByUser.keySet()) { + results.put(userId, tripDetector.detectRegularTrips(tripsByUser.get(userId))); + } + + return results; + } + + private HashMap> getTripsByUser(Modality modality) { + Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60); + List dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModality(fromDate, modality)); + + HashMap> tripsByUser = new HashMap<>(); + for (RegularTripDetectionDTO dto : dtoList) { + tripsByUser.computeIfAbsent(dto.getUserId(), k -> new ArrayList<>()).add(dto); + } + return tripsByUser; + } +} diff --git a/src/main/java/SuMoC/backend/trip/TripMapper.java b/src/main/java/SuMoC/backend/trip/TripMapper.java index 6f223aa..3f6f94d 100644 --- a/src/main/java/SuMoC/backend/trip/TripMapper.java +++ b/src/main/java/SuMoC/backend/trip/TripMapper.java @@ -2,13 +2,19 @@ package SuMoC.backend.trip; import SuMoC.backend.h3.H3Service; import SuMoC.backend.trip.dtos.NewTripDTO; +import SuMoC.backend.trip.dtos.NewTripSegmentDTO; +import SuMoC.backend.trip.dtos.RegularTripDetectionDTO; import SuMoC.backend.trip.dtos.TripDTO; import SuMoC.backend.trip.models.Trip; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.springframework.beans.factory.annotation.Autowired; +import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; @Mapper(componentModel = "spring", uses = {TripSegmentMapper.class, H3Service.class}) public abstract class TripMapper { @@ -25,8 +31,17 @@ public abstract class TripMapper { @Mapping(source = "tripSegments", target = "tripSegments") @Mapping(target = "startH3Cell", expression = "java(calculateH3CellStart(newTripDTO))") @Mapping(target = "endH3Cell", expression = "java(calculateH3CellEnd(newTripDTO))") + @Mapping(target = "mainModality", expression = "java(mainModalityByDistance(newTripDTO))") public abstract Trip toTrip(NewTripDTO newTripDTO); + @Mapping(source = "id", target = "tripId") + @Mapping(source = "user.id", target = "userId") + @Mapping(target = "startH3CellKRingNeighboors", expression = "java(calculateStartH3KRingNeighboords(trip))") + @Mapping(target = "endH3CellKRingNeighboors", expression = "java(calculateEndtH3KRingNeighboords(trip))") + public abstract RegularTripDetectionDTO toRegularTripDetectionDTO(Trip trip); + + public abstract List toRegularTripDetectionDTOS(List trips); + protected String calculateH3CellStart(NewTripDTO newTripDTO) { return h3service.latLngToCellForRoute(newTripDTO.getStartLatitude(), newTripDTO.getStartLongitude()); } @@ -34,4 +49,33 @@ public abstract class TripMapper { protected String calculateH3CellEnd(NewTripDTO newTripDTO) { return h3service.latLngToCellForRoute(newTripDTO.getEndLatitude(), newTripDTO.getEndLongitude()); } + + protected List calculateStartH3KRingNeighboords(Trip trip) { + return h3service.getRoutePatternNeighbors(trip.getStartH3Cell()); + } + + protected List calculateEndtH3KRingNeighboords(Trip trip) { + return h3service.getRoutePatternNeighbors(trip.getEndH3Cell()); + } + + protected Modality mainModalityByDistance(NewTripDTO newTripDTO) { + HashMap map = Arrays.stream(Modality.values()) + .collect(Collectors.toMap( + modality -> modality, + modality -> 0f, + (a, b) -> a, + HashMap::new + )); + + for (NewTripSegmentDTO segmentDTO : newTripDTO.getTripSegments()) { + Modality modality = segmentDTO.getModality(); + map.put(modality, map.get(modality) + segmentDTO.getDistanceMeters()); + } + + return map.entrySet().stream() + .max(Map.Entry.comparingByValue()) + .map(Map.Entry::getKey) + .orElse(Modality.IDLE); + + } } diff --git a/src/main/java/SuMoC/backend/trip/TripRepository.java b/src/main/java/SuMoC/backend/trip/TripRepository.java index a9247ba..4b8c96a 100644 --- a/src/main/java/SuMoC/backend/trip/TripRepository.java +++ b/src/main/java/SuMoC/backend/trip/TripRepository.java @@ -1,23 +1,30 @@ package SuMoC.backend.trip; -import SuMoC.backend.user.models.User; import SuMoC.backend.trip.models.Trip; +import SuMoC.backend.user.models.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import java.time.LocalDate; +import java.time.Instant; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; -public interface TripRepository extends JpaRepository { +public interface TripRepository extends JpaRepository { Optional findTripById(Long id); + Optional> findAllByUser(User user); @Query("SELECT trip FROM Trip trip " + "JOIN FETCH trip.user " + "JOIN FETCH trip.tripSegments " + "WHERE trip.invalidated = false AND trip.startTime >= :start AND trip.startTime < :end") - List findValidTripsInWeek(@Param("start") LocalDateTime start, @Param("end")LocalDateTime end); + List findValidTripsInWeek(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end); + + @Query("SELECT trip FROM Trip trip " + + "JOIN FETCH trip.user " + + "JOIN FETCH trip.tripSegments " + + "WHERE trip.invalidated = false AND trip.startTime >= :fromDate AND trip.mainModality = :modality") + List findAllValidFromDateWithMainModality(Instant fromDate, Modality modality); } diff --git a/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java b/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java new file mode 100644 index 0000000..0ce1ada --- /dev/null +++ b/src/main/java/SuMoC/backend/trip/dtos/RegularTripDetectionDTO.java @@ -0,0 +1,31 @@ +package SuMoC.backend.trip.dtos; + +import SuMoC.backend.trip.Modality; +import lombok.*; + +import java.time.Instant; +import java.util.List; + +/** + * A DTO representing the details of a saved trip in a format suitable for regular trip detection. + */ +@Builder +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class RegularTripDetectionDTO { + private long tripId; + private long userId; + private String startH3Cell; + private String endH3Cell; + private Instant startTime; + private Instant endTime; + private Modality mainModality; + private List startH3CellKRingNeighboors; + private List endH3CellKRingNeighboors; + + public int getDayOfTheWeek() { + return startTime.atZone(java.time.ZoneId.systemDefault()).getDayOfWeek().getValue(); + } +} diff --git a/src/main/java/SuMoC/backend/trip/models/Trip.java b/src/main/java/SuMoC/backend/trip/models/Trip.java index 2542de9..02ebb88 100644 --- a/src/main/java/SuMoC/backend/trip/models/Trip.java +++ b/src/main/java/SuMoC/backend/trip/models/Trip.java @@ -1,7 +1,9 @@ package SuMoC.backend.trip.models; +import SuMoC.backend.trip.Modality; import SuMoC.backend.user.models.User; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Getter; @@ -72,6 +74,11 @@ public class Trip { @Column(nullable = false) private boolean invalidated = false; + @Column(nullable = false) + @Enumerated(EnumType.STRING) + @Schema(description = "Main modality by distance.") + private Modality mainModality; + @OneToMany(mappedBy = "trip", cascade = CascadeType.ALL, orphanRemoval = true) private Set tripSegments = new HashSet<>(); } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 557b6dc..e018100 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -16,6 +16,8 @@ sumoc.scheduling.calculate-trend-table-cron=- # Trend detection settings trenddetection.negative-threshold=-25.0 trenddetection.positive-threshold=25.0 +# Regular trip detection settings +#regulartripdetection.detection-algorithm=iterative # FireBase firebase.config.service-account=classpath:firebase-private-key.json # Base URL to external services