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())); } List bestIteration = pickBestIteration(iterationResults); return deduplicateOverlappingDetections(bestIteration); } /** * 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()); } /** * Removes overlapping detections by greedily selecting the best non-overlapping set. * Detections with more supporters are prioritized. */ private List deduplicateOverlappingDetections(List detections) { // Sort by supporter count (descending) List sorted = new ArrayList<>(detections); sorted.sort(Comparator.comparingInt(d -> -d.getSupportingTrips().size())); List result = new ArrayList<>(); Set usedTripIds = new HashSet<>(); for (DetectedRegularTripDTO detection : sorted) { // Get all trip IDs involved in this detection Set detectionTripIds = new HashSet<>(); for (RegularTripDetectionDTO trip : detection.getSupportingTrips()) { detectionTripIds.add(trip.getTripId()); } // Check if any trips are already used boolean hasOverlap = detectionTripIds.stream().anyMatch(usedTripIds::contains); if (!hasOverlap) { result.add(detection); usedTripIds.addAll(detectionTripIds); } } return result; } /** * 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<>(); 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) { // 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()); } } } // 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; } }