implement trend detection logic
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good

- for now aimed to detect weekly trends in car distances, easily extendable to all other attributes of the statsm model
- including test
This commit is contained in:
2026-01-07 15:28:35 +01:00
parent ec0615f6df
commit 6e458edd5c
13 changed files with 376 additions and 23 deletions
@@ -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;
}
}
}
@@ -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<WeeklyMobilityStats, WeeklyMobilityStatsId> {
@Query("SELECT wms FROM WeeklyMobilityStats wms JOIN FETCH wms.user WHERE wms.year = :year AND wms.weekNumber = :weekNumber")
List<WeeklyMobilityStats> findAllByYearAndWeekNumberWithUser(@Param("year") Integer year, @Param("weekNumber") Integer weekNumber);
}
@@ -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;
}
@@ -0,0 +1,6 @@
package SuMoC.backend.trenddetection.enums;
public enum DeltaType {
ABSOLUTE,
PERCENTAGE
}
@@ -0,0 +1,8 @@
package SuMoC.backend.trenddetection.enums;
/**
* Represents statistical attributes a detected trend can pertain to.
*/
public enum StatAttribute {
CAR_DISTANCE,
}
@@ -0,0 +1,7 @@
package SuMoC.backend.trenddetection.enums;
public enum TrendConnotation {
POSITIVE,
NEGATIVE,
NEUTRAL
}
@@ -0,0 +1,5 @@
package SuMoC.backend.trenddetection.enums;
public enum TrendTimespan {
WEEKLY,
}
@@ -0,0 +1,7 @@
package SuMoC.backend.trenddetection.enums;
public enum TrendType {
INCREASING,
DECREASING,
STABLE
}
@@ -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;
};
}
}
@@ -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<TrendDetection> detectWeeklyTrends(Integer year, Integer weekNumber, StatAttribute attribute) {
// Fetch stats for current and previous week
List<WeeklyMobilityStats> 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<WeeklyMobilityStats> currentWeekStatsList = weeklyMobilityStatsRepository.findAllByYearAndWeekNumberWithUser(year, weekNumber);
// Convert to maps for easy userId-based lookup
Map<Long, WeeklyMobilityStats> previousWeekStats = previousWeekStatsList.stream()
.collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats));
Map<Long, WeeklyMobilityStats> currentWeekStats = currentWeekStatsList.stream()
.collect(Collectors.toMap(stats -> stats.getUser().getId(), stats -> stats));
// Detect trends for provided attribute
List<TrendDetection> detectedTrends = new ArrayList<>();
for (Map.Entry<Long, WeeklyMobilityStats> 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;
}
}
+4 -4
View File
@@ -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=-
sumoc.scheduling.calculate-trend-table-cron=-
# Trend detection settings
trenddetection.negative-threshold=-25.0
trenddetection.positive-threshold=25.0
@@ -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<TrendDetection> 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<TrendDetection> 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();
}
}
@@ -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 {
}
}