Files
sumoc-backend/src/main/java/SuMoC/backend/regulartrip/detectionapproaches/IterativeClusterer.java
T
2026-01-12 16:32:14 +01:00

219 lines
10 KiB
Java

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()));
}
List<DetectedRegularTripDTO> bestIteration = pickBestIteration(iterationResults);
return deduplicateOverlappingDetections(bestIteration);
}
/**
* 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());
}
/**
* Removes overlapping detections by greedily selecting the best non-overlapping set.
* Detections with more supporters are prioritized.
*/
private List<DetectedRegularTripDTO> deduplicateOverlappingDetections(List<DetectedRegularTripDTO> detections) {
// Sort by supporter count (descending)
List<DetectedRegularTripDTO> sorted = new ArrayList<>(detections);
sorted.sort(Comparator.comparingInt(d -> -d.getSupportingTrips().size()));
List<DetectedRegularTripDTO> result = new ArrayList<>();
Set<Long> usedTripIds = new HashSet<>();
for (DetectedRegularTripDTO detection : sorted) {
// Get all trip IDs involved in this detection
Set<Long> 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<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<>();
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) {
// 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<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;
}
}