From 6e458edd5c247e0aec11fcfbd5c0f53cb560a94d Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Wed, 7 Jan 2026 15:28:35 +0100 Subject: [PATCH] implement trend detection logic - for now aimed to detect weekly trends in car distances, easily extendable to all other attributes of the statsm model - including test --- .../trenddetection/TrendDetection.java | 36 ++++ .../WeeklyMobilityStatsRepository.java | 8 + .../config/TrendDetectionProperties.java | 21 +++ .../trenddetection/enums/DeltaType.java | 6 + .../trenddetection/enums/StatAttribute.java | 8 + .../enums/TrendConnotation.java | 7 + .../trenddetection/enums/TrendTimespan.java | 5 + .../trenddetection/enums/TrendType.java | 7 + .../models/WeeklyMobilityStats.java | 7 + .../services/TrendDetectorService.java | 84 +++++++++ src/main/resources/application.properties | 8 +- .../services/TrendDetectorServiceTest.java | 165 ++++++++++++++++++ .../backend/user/service/UserServiceTest.java | 37 ++-- 13 files changed, 376 insertions(+), 23 deletions(-) create mode 100644 src/main/java/SuMoC/backend/trenddetection/TrendDetection.java create mode 100644 src/main/java/SuMoC/backend/trenddetection/config/TrendDetectionProperties.java create mode 100644 src/main/java/SuMoC/backend/trenddetection/enums/DeltaType.java create mode 100644 src/main/java/SuMoC/backend/trenddetection/enums/StatAttribute.java create mode 100644 src/main/java/SuMoC/backend/trenddetection/enums/TrendConnotation.java create mode 100644 src/main/java/SuMoC/backend/trenddetection/enums/TrendTimespan.java create mode 100644 src/main/java/SuMoC/backend/trenddetection/enums/TrendType.java create mode 100644 src/main/java/SuMoC/backend/trenddetection/services/TrendDetectorService.java create mode 100644 src/test/java/SuMoC/backend/trenddetection/services/TrendDetectorServiceTest.java diff --git a/src/main/java/SuMoC/backend/trenddetection/TrendDetection.java b/src/main/java/SuMoC/backend/trenddetection/TrendDetection.java new file mode 100644 index 0000000..d1023e7 --- /dev/null +++ b/src/main/java/SuMoC/backend/trenddetection/TrendDetection.java @@ -0,0 +1,36 @@ +package SuMoC.backend.trenddetection; + +import SuMoC.backend.trenddetection.enums.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +@AllArgsConstructor +public class TrendDetection { + private Long userId; + private TrendTimespan timespan; + private TrendType type; + private StatAttribute attribute; + private DeltaType deltaType; + private double changeValue; + + public TrendConnotation getTrendConnotation() { + if (this.type == TrendType.INCREASING) { + return switch (attribute) { + case CAR_DISTANCE -> TrendConnotation.NEGATIVE; + default -> TrendConnotation.NEUTRAL; + }; + } else if (type == TrendType.DECREASING) { + return switch (attribute) { + case CAR_DISTANCE -> TrendConnotation.POSITIVE; + default -> TrendConnotation.NEUTRAL; + }; + } else { + return TrendConnotation.NEUTRAL; + } + } +} + + diff --git a/src/main/java/SuMoC/backend/trenddetection/WeeklyMobilityStatsRepository.java b/src/main/java/SuMoC/backend/trenddetection/WeeklyMobilityStatsRepository.java index 5170ab8..5bdabff 100644 --- a/src/main/java/SuMoC/backend/trenddetection/WeeklyMobilityStatsRepository.java +++ b/src/main/java/SuMoC/backend/trenddetection/WeeklyMobilityStatsRepository.java @@ -3,6 +3,14 @@ package SuMoC.backend.trenddetection; import SuMoC.backend.trenddetection.models.WeeklyMobilityStats; import SuMoC.backend.trenddetection.models.WeeklyMobilityStatsId; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; public interface WeeklyMobilityStatsRepository extends JpaRepository { + + @Query("SELECT wms FROM WeeklyMobilityStats wms JOIN FETCH wms.user WHERE wms.year = :year AND wms.weekNumber = :weekNumber") + List findAllByYearAndWeekNumberWithUser(@Param("year") Integer year, @Param("weekNumber") Integer weekNumber); + } diff --git a/src/main/java/SuMoC/backend/trenddetection/config/TrendDetectionProperties.java b/src/main/java/SuMoC/backend/trenddetection/config/TrendDetectionProperties.java new file mode 100644 index 0000000..09106c6 --- /dev/null +++ b/src/main/java/SuMoC/backend/trenddetection/config/TrendDetectionProperties.java @@ -0,0 +1,21 @@ +package SuMoC.backend.trenddetection.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "trenddetection") +public class TrendDetectionProperties { + + /** + * Minimum percentage change to detect a positive trend (e.g., 25.0 for 25%) + */ + private double positiveThreshold = 25.0; + + /** + * Minimum percentage change to detect a negative trend (e.g., -25.0 for -25%) + */ + private double negativeThreshold = -25.0; +} diff --git a/src/main/java/SuMoC/backend/trenddetection/enums/DeltaType.java b/src/main/java/SuMoC/backend/trenddetection/enums/DeltaType.java new file mode 100644 index 0000000..93e2483 --- /dev/null +++ b/src/main/java/SuMoC/backend/trenddetection/enums/DeltaType.java @@ -0,0 +1,6 @@ +package SuMoC.backend.trenddetection.enums; + +public enum DeltaType { + ABSOLUTE, + PERCENTAGE +} diff --git a/src/main/java/SuMoC/backend/trenddetection/enums/StatAttribute.java b/src/main/java/SuMoC/backend/trenddetection/enums/StatAttribute.java new file mode 100644 index 0000000..c8f1fa9 --- /dev/null +++ b/src/main/java/SuMoC/backend/trenddetection/enums/StatAttribute.java @@ -0,0 +1,8 @@ +package SuMoC.backend.trenddetection.enums; + +/** + * Represents statistical attributes a detected trend can pertain to. + */ +public enum StatAttribute { + CAR_DISTANCE, +} diff --git a/src/main/java/SuMoC/backend/trenddetection/enums/TrendConnotation.java b/src/main/java/SuMoC/backend/trenddetection/enums/TrendConnotation.java new file mode 100644 index 0000000..f08c176 --- /dev/null +++ b/src/main/java/SuMoC/backend/trenddetection/enums/TrendConnotation.java @@ -0,0 +1,7 @@ +package SuMoC.backend.trenddetection.enums; + +public enum TrendConnotation { + POSITIVE, + NEGATIVE, + NEUTRAL +} diff --git a/src/main/java/SuMoC/backend/trenddetection/enums/TrendTimespan.java b/src/main/java/SuMoC/backend/trenddetection/enums/TrendTimespan.java new file mode 100644 index 0000000..3a54656 --- /dev/null +++ b/src/main/java/SuMoC/backend/trenddetection/enums/TrendTimespan.java @@ -0,0 +1,5 @@ +package SuMoC.backend.trenddetection.enums; + +public enum TrendTimespan { + WEEKLY, +} diff --git a/src/main/java/SuMoC/backend/trenddetection/enums/TrendType.java b/src/main/java/SuMoC/backend/trenddetection/enums/TrendType.java new file mode 100644 index 0000000..06e56ac --- /dev/null +++ b/src/main/java/SuMoC/backend/trenddetection/enums/TrendType.java @@ -0,0 +1,7 @@ +package SuMoC.backend.trenddetection.enums; + +public enum TrendType { + INCREASING, + DECREASING, + STABLE +} diff --git a/src/main/java/SuMoC/backend/trenddetection/models/WeeklyMobilityStats.java b/src/main/java/SuMoC/backend/trenddetection/models/WeeklyMobilityStats.java index d408d71..2db6d3a 100644 --- a/src/main/java/SuMoC/backend/trenddetection/models/WeeklyMobilityStats.java +++ b/src/main/java/SuMoC/backend/trenddetection/models/WeeklyMobilityStats.java @@ -1,5 +1,6 @@ package SuMoC.backend.trenddetection.models; +import SuMoC.backend.trenddetection.enums.StatAttribute; import SuMoC.backend.user.models.User; import jakarta.persistence.*; import lombok.*; @@ -77,4 +78,10 @@ public class WeeklyMobilityStats { @Column(nullable = false) private Long sumMetersTaxi = 0L; + + public Long getValueFor(StatAttribute attribute) { + return switch (attribute) { + case CAR_DISTANCE -> sumMetersCar; + }; + } } diff --git a/src/main/java/SuMoC/backend/trenddetection/services/TrendDetectorService.java b/src/main/java/SuMoC/backend/trenddetection/services/TrendDetectorService.java new file mode 100644 index 0000000..034376f --- /dev/null +++ b/src/main/java/SuMoC/backend/trenddetection/services/TrendDetectorService.java @@ -0,0 +1,84 @@ +package SuMoC.backend.trenddetection.services; + +import SuMoC.backend.trenddetection.TrendDetection; +import SuMoC.backend.trenddetection.WeeklyMobilityStatsRepository; +import SuMoC.backend.trenddetection.config.TrendDetectionProperties; +import SuMoC.backend.trenddetection.enums.DeltaType; +import SuMoC.backend.trenddetection.enums.StatAttribute; +import SuMoC.backend.trenddetection.enums.TrendTimespan; +import SuMoC.backend.trenddetection.enums.TrendType; +import SuMoC.backend.trenddetection.models.WeeklyMobilityStats; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class TrendDetectorService { + + private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository; + + private final TrendDetectionProperties trendDetectionProperties; + + public List detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) { + // Fetch stats for current and previous week + List previousWeekStatsList; + if (weekNumber > 1) { + previousWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1); + } else { + // we are forgetting about week 53 here, but it's rare enough to ignore for now + previousWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year - 1, 52); + } + List currentWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber); + + // Convert to maps for easy userId-based lookup + Map previousWeekStats = previousWeekStatsList.stream() + .collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats)); + + Map currentWeekStats = currentWeekStatsList.stream() + .collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats)); + + // Detect trends for provided attribute + List detectedTrends = new ArrayList<>(); + for (Map.Entry entry : currentWeekStats.entrySet()) { + Long userId = entry.getKey(); + WeeklyMobilityStats currentStats = entry.getValue(); + WeeklyMobilityStats previousStats = previousWeekStats.get(userId); + + if (previousStats != null) { + double currentValue = currentStats.getValueFor(attribute); + double previousValue = previousStats.getValueFor(attribute); + + if (previousValue != 0) { + double percentageChange = ((currentValue - previousValue) / previousValue) * 100.0; + + if (percentageChange >= trendDetectionProperties.getPositiveThreshold()) { + detectedTrends.add(new TrendDetection( + userId, + TrendTimespan.WEEKLY, + TrendType.INCREASING, + StatAttribute.CAR_DISTANCE, + DeltaType.PERCENTAGE, + percentageChange + )); + } else if (percentageChange <= trendDetectionProperties.getNegativeThreshold()) { + detectedTrends.add(new TrendDetection( + userId, + TrendTimespan.WEEKLY, + TrendType.DECREASING, + StatAttribute.CAR_DISTANCE, + DeltaType.PERCENTAGE, + percentageChange + )); + } + } + } + } + + return detectedTrends; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 5a6f78b..468c53a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -9,11 +9,11 @@ spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect logging.level.org.springframework.security=Trace springdoc.api-docs.path=/v3/api-docs springdoc.swagger-ui.path=/swagger-ui.html - spring.profiles.active=dev - carta.base-url=https://mobydex.locoslab.com/carta nominatim.base-url=http://localhost:6666 - # Disable for development -sumoc.scheduling.calculate-trend-table-cron=- \ No newline at end of file +sumoc.scheduling.calculate-trend-table-cron=- +# Trend detection settings +trenddetection.negative-threshold=-25.0 +trenddetection.positive-threshold=25.0 \ No newline at end of file diff --git a/src/test/java/SuMoC/backend/trenddetection/services/TrendDetectorServiceTest.java b/src/test/java/SuMoC/backend/trenddetection/services/TrendDetectorServiceTest.java new file mode 100644 index 0000000..b5481b1 --- /dev/null +++ b/src/test/java/SuMoC/backend/trenddetection/services/TrendDetectorServiceTest.java @@ -0,0 +1,165 @@ +package SuMoC.backend.trenddetection.services; + +import SuMoC.backend.trenddetection.TrendDetection; +import SuMoC.backend.trenddetection.WeeklyMobilityStatsRepository; +import SuMoC.backend.trenddetection.config.TrendDetectionProperties; +import SuMoC.backend.trenddetection.enums.DeltaType; +import SuMoC.backend.trenddetection.enums.StatAttribute; +import SuMoC.backend.trenddetection.enums.TrendTimespan; +import SuMoC.backend.trenddetection.enums.TrendType; +import SuMoC.backend.trenddetection.models.WeeklyMobilityStats; +import SuMoC.backend.user.models.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class TrendDetectorServiceTest { + + @Mock + private WeeklyMobilityStatsRepository weeklyMobilityStatsRepository; + + @Mock + private TrendDetectionProperties trendDetectionProperties; + + @InjectMocks + private TrendDetectorService trendDetectorService; + + private User user1; + private User user2; + private User user3; + + @BeforeEach + void setUp() { + user1 = new User("Private1", "Public1", "user1@example.com", "pass1"); + user1.setId(1L); + + user2 = new User("Private2", "Public2", "user2@example.com", "pass2"); + user2.setId(2L); + + user3 = new User("Private3", "Public3", "user3@example.com", "pass3"); + user3.setId(3L); + } + + @Test + void detectWeeklyTrends_WithSignificantChanges_DetectsTrends() { + // Arrange + int year = 2026; + int weekNumber = 2; + + // Set threshold values for this test + when(trendDetectionProperties.getPositiveThreshold()).thenReturn(25.0); + when(trendDetectionProperties.getNegativeThreshold()).thenReturn(-25.0); + + // User 1: Significant increase (100m -> 400m = +300%) + WeeklyMobilityStats user1Previous = createWeeklyStats(user1, year, weekNumber - 1, 100L); + WeeklyMobilityStats user1Current = createWeeklyStats(user1, year, weekNumber, 400L); + + // User 2: Significant decrease (1000m -> 200m = -80%) + WeeklyMobilityStats user2Previous = createWeeklyStats(user2, year, weekNumber - 1, 1000L); + WeeklyMobilityStats user2Current = createWeeklyStats(user2, year, weekNumber, 200L); + + // User 3: No significant change (500m -> 550m = +10%) + WeeklyMobilityStats user3Previous = createWeeklyStats(user3, year, weekNumber - 1, 500L); + WeeklyMobilityStats user3Current = createWeeklyStats(user3, year, weekNumber, 550L); + + when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1)) + .thenReturn(List.of(user1Previous, user2Previous, user3Previous)); + when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber)) + .thenReturn(List.of(user1Current, user2Current, user3Current)); + + // Act + List detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE); + + // Assert + assertEquals(2, detectedTrends.size(), "Should detect 2 trends (1 increase, 1 decrease)"); + + // Verify increasing trend for user1 + TrendDetection user1Trend = detectedTrends.stream() + .filter(t -> t.getUserId().equals(user1.getId())) + .findFirst() + .orElse(null); + assertNotNull(user1Trend, "User 1 should have a detected trend"); + assertEquals(TrendType.INCREASING, user1Trend.getType()); + assertEquals(StatAttribute.CAR_DISTANCE, user1Trend.getAttribute()); + assertEquals(TrendTimespan.WEEKLY, user1Trend.getTimespan()); + assertEquals(DeltaType.PERCENTAGE, user1Trend.getDeltaType()); + assertEquals(300.0, user1Trend.getChangeValue(), 0.01); + + // Verify decreasing trend for user2 + TrendDetection user2Trend = detectedTrends.stream() + .filter(t -> t.getUserId().equals(user2.getId())) + .findFirst() + .orElse(null); + assertNotNull(user2Trend, "User 2 should have a detected trend"); + assertEquals(TrendType.DECREASING, user2Trend.getType()); + assertEquals(StatAttribute.CAR_DISTANCE, user2Trend.getAttribute()); + assertEquals(TrendTimespan.WEEKLY, user2Trend.getTimespan()); + assertEquals(DeltaType.PERCENTAGE, user2Trend.getDeltaType()); + assertEquals(-80.0, user2Trend.getChangeValue(), 0.01); + + // Verify no trend detected for user3 + boolean user3HasTrend = detectedTrends.stream() + .anyMatch(t -> t.getUserId().equals(user3.getId())); + assertFalse(user3HasTrend, "User 3 should not have a detected trend (change below threshold)"); + } + + @Test + void detectWeeklyTrends_WithMissingData_HandlesGracefully() { + // Arrange + int year = 2026; + int weekNumber = 2; + + // User 1: Has current week data but no previous week data + WeeklyMobilityStats user1Current = createWeeklyStats(user1, year, weekNumber, 500L); + + // User 2: Has previous week data but no current week data + WeeklyMobilityStats user2Previous = createWeeklyStats(user2, year, weekNumber - 1, 800L); + + when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber - 1)) + .thenReturn(List.of(user2Previous)); + when(weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber)) + .thenReturn(List.of(user1Current)); + + // Act & Assert - should not throw any exception + assertDoesNotThrow(() -> { + List detectedTrends = trendDetectorService.detectWeeklyTrends(year, weekNumber, StatAttribute.CAR_DISTANCE); + assertEquals(0, detectedTrends.size(), "Should not detect any trends when matching data is missing"); + }); + } + + /** + * Helper method to create WeeklyMobilityStats with specified car distance + */ + private WeeklyMobilityStats createWeeklyStats(User user, int year, int weekNumber, Long carDistance) { + return WeeklyMobilityStats.builder() + .user(user) + .year(year) + .weekNumber(weekNumber) + .totalDistance(carDistance.doubleValue()) + .tripCount(10) + .sumMobilityScore(50.0) + .averageMobilityScore(5.0) + .sumMetersTraveled(carDistance) + .sumMetersWalkingAndCycling(0L) + .sumMetersPublicTransport(0L) + .sumMetersWalking(0L) + .sumMetersBicycle(0L) + .sumMetersEscooter(0L) + .sumMetersBus(0L) + .sumMetersTram(0L) + .sumMetersTrain(0L) + .sumMetersCar(carDistance) + .sumMetersMotorcycle(0L) + .sumMetersTaxi(0L) + .build(); + } +} diff --git a/src/test/java/SuMoC/backend/user/service/UserServiceTest.java b/src/test/java/SuMoC/backend/user/service/UserServiceTest.java index cfb4ead..55ec007 100644 --- a/src/test/java/SuMoC/backend/user/service/UserServiceTest.java +++ b/src/test/java/SuMoC/backend/user/service/UserServiceTest.java @@ -38,6 +38,7 @@ public class UserServiceTest { @BeforeEach void setUp() { + userRepository.deleteAll(); sender = userRepository.save(uniqueUser(1)); differentUser = userRepository.save(uniqueUser(2)); } @@ -67,7 +68,7 @@ public class UserServiceTest { assertEquals(differentUser.getPublicName(), publicSetting.getDisplayName()); - } + } @Test @@ -86,7 +87,6 @@ public class UserServiceTest { assertTrue(userRepository.findById(differentUser.getId()).isPresent()); - } @@ -101,14 +101,14 @@ public class UserServiceTest { // Check if user can change his own password - // Too short password - assertThrows(RuntimeException.class, () -> userService.setPassword(sender.getId(), "test")); - // TODO: check why this assertion fails (most likely because of password encoding internals) - // assertTrue(passwordEncoder.matches("password1", userRepository.findById(sender.getId()).get().getPassword())); + // Too short password + assertThrows(RuntimeException.class, () -> userService.setPassword(sender.getId(), "test")); + // TODO: check why this assertion fails (most likely because of password encoding internals) + // assertTrue(passwordEncoder.matches("password1", userRepository.findById(sender.getId()).get().getPassword())); - // Valid password - userService.setPassword(sender.getId(), newPassword); - assertTrue(passwordEncoder.matches(newPassword, userRepository.findById(sender.getId()).get().getPassword())); + // Valid password + userService.setPassword(sender.getId(), newPassword); + assertTrue(passwordEncoder.matches(newPassword, userRepository.findById(sender.getId()).get().getPassword())); } @@ -125,17 +125,17 @@ public class UserServiceTest { // Check if user can change his own email - // Other user's email - assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), differentUser.getEmail())); - assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail()); + // Other user's email + assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), differentUser.getEmail())); + assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail()); - // Invalid email format - assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), invalidEmail)); - assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail()); + // Invalid email format + assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), invalidEmail)); + assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail()); - // Valid email - userService.setEmail(sender.getId(), newEmail); - assertEquals(newEmail, userRepository.findById(sender.getId()).get().getEmail()); + // Valid email + userService.setEmail(sender.getId(), newEmail); + assertEquals(newEmail, userRepository.findById(sender.getId()).get().getEmail()); } @@ -178,5 +178,4 @@ public class UserServiceTest { } - }