using Schaad.OpenData.Traffic.Models; using Schaad.OpenData.Traffic.Storage; namespace Schaad.OpenData.Traffic.Analysis; public static class TrafficAnalysis { private const int HoursPerDay = 24; public static DayView? BuildDay(TrafficSnapshot snapshot, DateOnly date) { if (!snapshot.CountsByDate.TryGetValue(date, out var counts)) { return null; } var byStation = counts.ToLookup(c => c.StationCode); var stations = snapshot.Stations.Values .OrderBy(s => s.Code) .Where(s => byStation.Contains(s.Code)) .Select(s => new StationDayView( s.Code, s.Directions .Select(direction => { var hours = new int[]?[HoursPerDay]; foreach (var count in byStation[s.Code].Where(c => c.Direction == direction)) { hours[count.Hour] = count.Counts.ToArray(); } return new DirectionDayView(direction, hours); }) .ToList())) .ToList(); return new DayView(date, stations); } public static StationSummary? BuildStationSummary(TrafficSnapshot snapshot, int code, DateOnly? from, DateOnly? to) { if (!snapshot.Stations.TryGetValue(code, out var station) || snapshot.Dates.IsEmpty) { return null; } var start = from ?? snapshot.Dates[0]; var end = to ?? snapshot.Dates[^1]; var counts = snapshot.Dates .Where(d => d >= start && d <= end) .SelectMany(d => snapshot.CountsByDate[d]) .Where(c => c.StationCode == code) .ToList(); var directions = station.Directions .Select(direction => BuildDirectionSummary(direction, counts.Where(c => c.Direction == direction).ToList())) .ToList(); var classTotals = counts.Aggregate(default(VehicleCounts), (sum, c) => sum + c.Counts).ToArray(); return new StationSummary(code, start, end, directions, classTotals); } private static DirectionSummary BuildDirectionSummary(string direction, List counts) { var hourly = counts .OrderBy(c => c.Date) .ThenBy(c => c.Hour) .Select(c => new HourlyTotal(c.Date.ToDateTime(new TimeOnly(c.Hour, 0)), c.Counts.Total)) .ToList(); var daily = counts .GroupBy(c => c.Date) .OrderBy(g => g.Key) .Select(g => new DailyTotal(g.Key, g.Sum(c => c.Counts.Total))) .ToList(); return new DirectionSummary( direction, hourly, daily, AverageByHour(counts.Where(c => !IsWeekend(c.Date))), AverageByHour(counts.Where(c => IsWeekend(c.Date)))); } private static double[] AverageByHour(IEnumerable counts) { var byHour = counts.ToLookup(c => c.Hour); return Enumerable.Range(0, HoursPerDay) .Select(hour => byHour[hour].Select(c => (double)c.Counts.Total).DefaultIfEmpty(0).Average()) .Select(average => Math.Round(average, 1)) .ToArray(); } private static bool IsWeekend(DateOnly date) => date.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday; }