first implementation of iterative greedy algorithm to detect regular trips

This commit is contained in:
2026-01-12 16:19:28 +01:00
parent 160b883bfc
commit 474813b2b9
12 changed files with 447 additions and 6 deletions
@@ -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<String> 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
@@ -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);
}
}
@@ -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";
}
@@ -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<DetectedRegularTripDTO> detectRegularTrips(List<RegularTripDetectionDTO> trips);
}
@@ -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<DetectedRegularTripDTO> detectRegularTrips(List<RegularTripDetectionDTO> trips) {
// Step 1: Init potential detected trip for all trips
HashMap<Long, DetectedRegularTripDTO> baseDetectedTripsMap = initDetectedTripsMap(trips);
// Step 2: Find trips supported by min number of supporters
List<List<DetectedRegularTripDTO>> iterationResults = new ArrayList<>();
for (int i = 0; i < properties.getIterativeShuffleAmounts(); i++) {
// Deep copy the map for each iteration
HashMap<Long, DetectedRegularTripDTO> 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<DetectedRegularTripDTO> pickBestIteration(List<List<DetectedRegularTripDTO>> 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<DetectedRegularTripDTO> aggregateToSupportedDetections(
HashMap<Long, DetectedRegularTripDTO> potentialDetectedRegularTrips,
List<RegularTripDetectionDTO> trips,
int necessarySupporters
) {
// We need to dupe deletions with this list since we cant modify other list entries while iterating over it
Set<Long> deletedDetections = new HashSet<>();
Set<Long> deletedTrips = new HashSet<>();
for (Map.Entry<Long, DetectedRegularTripDTO> 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<DetectedRegularTripDTO> detectedTrips = new ArrayList<>();
for (Map.Entry<Long, DetectedRegularTripDTO> 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<Long, DetectedRegularTripDTO> initDetectedTripsMap(List<RegularTripDetectionDTO> trips) {
HashMap<Long, DetectedRegularTripDTO> 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<RegularTripDetectionDTO>(List.of(trip)))
.build());
}
return potentialDetectedTrips;
}
private HashMap<Long, DetectedRegularTripDTO> deepCopyDetectedTripsMap(
HashMap<Long, DetectedRegularTripDTO> original) {
HashMap<Long, DetectedRegularTripDTO> copy = new HashMap<>();
for (Map.Entry<Long, DetectedRegularTripDTO> 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;
}
}
@@ -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<String> startH3neighbours;
private List<String> endH3Neighbours;
private List<RegularTripDetectionDTO> supportingTrips;
}
@@ -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<Long, List<DetectedRegularTripDTO>> detectRegularCarTrips() {
var tripsByUser = getTripsByUser(Modality.CAR);
// TODO this could be parallelized in the future
HashMap<Long, List<DetectedRegularTripDTO>> results = new HashMap<>();
for (Long userId : tripsByUser.keySet()) {
results.put(userId, tripDetector.detectRegularTrips(tripsByUser.get(userId)));
}
return results;
}
private HashMap<Long, List<RegularTripDetectionDTO>> getTripsByUser(Modality modality) {
Instant fromDate = Instant.now().minusSeconds(properties.getDetectionTimeWindowDays() * 24 * 60 * 60);
List<RegularTripDetectionDTO> dtoList = tripMapper.toRegularTripDetectionDTOS(tripRepository.findAllValidFromDateWithMainModality(fromDate, modality));
HashMap<Long, List<RegularTripDetectionDTO>> tripsByUser = new HashMap<>();
for (RegularTripDetectionDTO dto : dtoList) {
tripsByUser.computeIfAbsent(dto.getUserId(), k -> new ArrayList<>()).add(dto);
}
return tripsByUser;
}
}
@@ -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<RegularTripDetectionDTO> toRegularTripDetectionDTOS(List<Trip> 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<String> calculateStartH3KRingNeighboords(Trip trip) {
return h3service.getRoutePatternNeighbors(trip.getStartH3Cell());
}
protected List<String> calculateEndtH3KRingNeighboords(Trip trip) {
return h3service.getRoutePatternNeighbors(trip.getEndH3Cell());
}
protected Modality mainModalityByDistance(NewTripDTO newTripDTO) {
HashMap<Modality, Float> 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);
}
}
@@ -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<Trip,Long> {
public interface TripRepository extends JpaRepository<Trip, Long> {
Optional<Trip> findTripById(Long id);
Optional<List<Trip>> 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<Trip> findValidTripsInWeek(@Param("start") LocalDateTime start, @Param("end")LocalDateTime end);
List<Trip> 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<Trip> findAllValidFromDateWithMainModality(Instant fromDate, Modality modality);
}
@@ -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<String> startH3CellKRingNeighboors;
private List<String> endH3CellKRingNeighboors;
public int getDayOfTheWeek() {
return startTime.atZone(java.time.ZoneId.systemDefault()).getDayOfWeek().getValue();
}
}
@@ -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<TripSegment> tripSegments = new HashSet<>();
}