From e729ea340331e2b0a5c77b407a021af17f550b00 Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Fri, 6 Nov 2026 20:33:58 +0100 Subject: [PATCH 1/3] Add Thurgau traffic visualizer with animated map ASP.NET Core 10 API and React client that visualize the canton of Thurgau's hourly traffic counts by vehicle class (data.tg.ch, CC0). - Background refresh from data.tg.ch every 6 h into a per-day JSON cache, so history grows beyond the source's two-week window - Road geometry per station direction from swisstopo swissTLM3D, oriented by geocoding the direction's target town; roundabout arms follow the road outward only - Leaflet map with canvas animation: dots drive along the road in both directions, density by hourly count, colour by vehicle class, right-hand traffic; play/pause, time slider and day selection - Station panel with per-class counts and Chart.js charts (hourly, weekday/weekend profile, daily totals, class mix) - swisstopo base map switcher (grey, colour, aerial) - Dockerfile and docker-compose with a data volume - xUnit tests for mapping, cache, geometry, geocoding and analysis Co-Authored-By: Claude Opus 5.5 --- .claude/launch.json | 11 + .dockerignore | 10 + .gitignore | 492 +++++ CLAUDE.md | 78 + Directory.Build.props | 7 + Directory.Packages.props | 18 + Dockerfile | 31 + OpenDataVisualizer.sln | 62 + README.md | 23 +- Schaad.OpenData.Server/Program.cs | 17 + .../Properties/launchSettings.json | 14 + .../Schaad.OpenData.Server.csproj | 7 + .../Traffic/DirectionResponse.cs | 3 + .../Traffic/MetaResponse.cs | 10 + .../Traffic/StationResponse.cs | 30 + .../Traffic/TrafficEndpoints.cs | 43 + Schaad.OpenData.Server/appsettings.json | 14 + .../DirectionTargetTestShould.cs | 24 + .../RoadPathBuilderTestShould.cs | 190 ++ .../Schaad.OpenData.Tests.csproj | 25 + .../StationGeometryServiceTestShould.cs | 40 + .../SwisstopoClientTestShould.cs | 124 ++ Schaad.OpenData.Tests/TestData.cs | 45 + .../ThurgauTrafficMapperTestShould.cs | 62 + .../TrafficAnalysisTestShould.cs | 75 + .../TrafficCacheStorageTestShould.cs | 68 + .../TrafficSnapshotTestShould.cs | 61 + .../Analysis/DailyTotal.cs | 3 + Schaad.OpenData.Traffic/Analysis/DayView.cs | 3 + .../Analysis/DirectionDayView.cs | 3 + .../Analysis/DirectionSummary.cs | 8 + .../Analysis/HourlyTotal.cs | 3 + .../Analysis/StationDayView.cs | 3 + .../Analysis/StationSummary.cs | 8 + .../Analysis/TrafficAnalysis.cs | 94 + .../Geometry/DirectionTarget.cs | 20 + .../Geometry/LocalProjection.cs | 19 + .../Geometry/ResolvedDirection.cs | 5 + .../Geometry/RoadPathBuilder.cs | 285 +++ .../Geometry/RoadSegment.cs | 5 + .../Geometry/StationGeometryService.cs | 45 + .../Geometry/SwisstopoClient.cs | 140 ++ .../Models/DirectionGeometry.cs | 3 + Schaad.OpenData.Traffic/Models/GeoPoint.cs | 3 + Schaad.OpenData.Traffic/Models/HourlyCount.cs | 3 + Schaad.OpenData.Traffic/Models/Station.cs | 10 + .../Models/StationGeometry.cs | 3 + .../Models/TrafficImport.cs | 3 + .../Models/VehicleClass.cs | 15 + .../Models/VehicleCounts.cs | 31 + .../Schaad.OpenData.Traffic.csproj | 15 + .../Source/ThurgauCoordinates.cs | 12 + .../Source/ThurgauTrafficClient.cs | 32 + .../Source/ThurgauTrafficMapper.cs | 77 + .../Source/ThurgauTrafficRecord.cs | 63 + .../Storage/TrafficCacheMeta.cs | 3 + .../Storage/TrafficCacheStorage.cs | 74 + .../Storage/TrafficDataStore.cs | 10 + .../Storage/TrafficSnapshot.cs | 58 + Schaad.OpenData.Traffic/TrafficOptions.cs | 14 + .../TrafficRefreshService.cs | 44 + Schaad.OpenData.Traffic/TrafficRefresher.cs | 73 + .../TrafficServiceCollectionExtensions.cs | 38 + client/.prettierrc.json | 6 + client/index.html | 13 + client/package-lock.json | 1839 +++++++++++++++++ client/package.json | 30 + client/public/favicon.svg | 1 + client/src/App.tsx | 174 ++ client/src/api/traffic.ts | 86 + client/src/components/Legend.tsx | 21 + client/src/components/StationPanel.tsx | 290 +++ client/src/components/TimeControls.tsx | 99 + client/src/components/TrafficMap.tsx | 192 ++ client/src/main.tsx | 17 + client/src/styles.css | 360 ++++ client/src/traffic/flowAnimator.ts | 294 +++ client/src/traffic/format.ts | 20 + client/src/traffic/vehicleClasses.ts | 41 + client/tsconfig.json | 19 + client/vite.config.ts | 16 + docker-compose.yml | 15 + 82 files changed, 6344 insertions(+), 1 deletion(-) create mode 100644 .claude/launch.json create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100644 Directory.Build.props create mode 100644 Directory.Packages.props create mode 100644 Dockerfile create mode 100644 OpenDataVisualizer.sln create mode 100644 Schaad.OpenData.Server/Program.cs create mode 100644 Schaad.OpenData.Server/Properties/launchSettings.json create mode 100644 Schaad.OpenData.Server/Schaad.OpenData.Server.csproj create mode 100644 Schaad.OpenData.Server/Traffic/DirectionResponse.cs create mode 100644 Schaad.OpenData.Server/Traffic/MetaResponse.cs create mode 100644 Schaad.OpenData.Server/Traffic/StationResponse.cs create mode 100644 Schaad.OpenData.Server/Traffic/TrafficEndpoints.cs create mode 100644 Schaad.OpenData.Server/appsettings.json create mode 100644 Schaad.OpenData.Tests/DirectionTargetTestShould.cs create mode 100644 Schaad.OpenData.Tests/RoadPathBuilderTestShould.cs create mode 100644 Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj create mode 100644 Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs create mode 100644 Schaad.OpenData.Tests/SwisstopoClientTestShould.cs create mode 100644 Schaad.OpenData.Tests/TestData.cs create mode 100644 Schaad.OpenData.Tests/ThurgauTrafficMapperTestShould.cs create mode 100644 Schaad.OpenData.Tests/TrafficAnalysisTestShould.cs create mode 100644 Schaad.OpenData.Tests/TrafficCacheStorageTestShould.cs create mode 100644 Schaad.OpenData.Tests/TrafficSnapshotTestShould.cs create mode 100644 Schaad.OpenData.Traffic/Analysis/DailyTotal.cs create mode 100644 Schaad.OpenData.Traffic/Analysis/DayView.cs create mode 100644 Schaad.OpenData.Traffic/Analysis/DirectionDayView.cs create mode 100644 Schaad.OpenData.Traffic/Analysis/DirectionSummary.cs create mode 100644 Schaad.OpenData.Traffic/Analysis/HourlyTotal.cs create mode 100644 Schaad.OpenData.Traffic/Analysis/StationDayView.cs create mode 100644 Schaad.OpenData.Traffic/Analysis/StationSummary.cs create mode 100644 Schaad.OpenData.Traffic/Analysis/TrafficAnalysis.cs create mode 100644 Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs create mode 100644 Schaad.OpenData.Traffic/Geometry/LocalProjection.cs create mode 100644 Schaad.OpenData.Traffic/Geometry/ResolvedDirection.cs create mode 100644 Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs create mode 100644 Schaad.OpenData.Traffic/Geometry/RoadSegment.cs create mode 100644 Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs create mode 100644 Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs create mode 100644 Schaad.OpenData.Traffic/Models/DirectionGeometry.cs create mode 100644 Schaad.OpenData.Traffic/Models/GeoPoint.cs create mode 100644 Schaad.OpenData.Traffic/Models/HourlyCount.cs create mode 100644 Schaad.OpenData.Traffic/Models/Station.cs create mode 100644 Schaad.OpenData.Traffic/Models/StationGeometry.cs create mode 100644 Schaad.OpenData.Traffic/Models/TrafficImport.cs create mode 100644 Schaad.OpenData.Traffic/Models/VehicleClass.cs create mode 100644 Schaad.OpenData.Traffic/Models/VehicleCounts.cs create mode 100644 Schaad.OpenData.Traffic/Schaad.OpenData.Traffic.csproj create mode 100644 Schaad.OpenData.Traffic/Source/ThurgauCoordinates.cs create mode 100644 Schaad.OpenData.Traffic/Source/ThurgauTrafficClient.cs create mode 100644 Schaad.OpenData.Traffic/Source/ThurgauTrafficMapper.cs create mode 100644 Schaad.OpenData.Traffic/Source/ThurgauTrafficRecord.cs create mode 100644 Schaad.OpenData.Traffic/Storage/TrafficCacheMeta.cs create mode 100644 Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs create mode 100644 Schaad.OpenData.Traffic/Storage/TrafficDataStore.cs create mode 100644 Schaad.OpenData.Traffic/Storage/TrafficSnapshot.cs create mode 100644 Schaad.OpenData.Traffic/TrafficOptions.cs create mode 100644 Schaad.OpenData.Traffic/TrafficRefreshService.cs create mode 100644 Schaad.OpenData.Traffic/TrafficRefresher.cs create mode 100644 Schaad.OpenData.Traffic/TrafficServiceCollectionExtensions.cs create mode 100644 client/.prettierrc.json create mode 100644 client/index.html create mode 100644 client/package-lock.json create mode 100644 client/package.json create mode 100644 client/public/favicon.svg create mode 100644 client/src/App.tsx create mode 100644 client/src/api/traffic.ts create mode 100644 client/src/components/Legend.tsx create mode 100644 client/src/components/StationPanel.tsx create mode 100644 client/src/components/TimeControls.tsx create mode 100644 client/src/components/TrafficMap.tsx create mode 100644 client/src/main.tsx create mode 100644 client/src/styles.css create mode 100644 client/src/traffic/flowAnimator.ts create mode 100644 client/src/traffic/format.ts create mode 100644 client/src/traffic/vehicleClasses.ts create mode 100644 client/tsconfig.json create mode 100644 client/vite.config.ts create mode 100644 docker-compose.yml diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..e6a1e1d --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "server", + "runtimeExecutable": "dotnet", + "runtimeArgs": ["run", "--project", "Schaad.OpenData.Server", "--launch-profile", "http"], + "port": 5080 + } + ] +} diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..97cf8f4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +**/bin/ +**/obj/ +**/node_modules/ +client/dist/ +Schaad.OpenData.Server/wwwroot/ +data/ +.git/ +.idea/ +.vs/ +.claude/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..819d969 --- /dev/null +++ b/.gitignore @@ -0,0 +1,492 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp + +# Node / client +node_modules/ +client/dist/ + +# Local data cache +data/ +Schaad.OpenData.Server/wwwroot/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..bfa245f --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,78 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Commands + +```bash +# Backend (ASP.NET Core 10) — API + static client at http://localhost:5080 +dotnet build +dotnet run --project Schaad.OpenData.Server --launch-profile http + +# Tests (xUnit + NSubstitute + Shouldly) +dotnet test +dotnet test --filter "FullyQualifiedName~RoadPathBuilderTestShould" + +# Client (Vite + React + TypeScript), run from client/ +npm install +npm run dev # http://localhost:5173, proxies /api to :5080 +npm run build # tsc + vite build into Schaad.OpenData.Server/wwwroot +npm run typecheck +npm run format # prettier + +# Docker +docker compose up --build # http://localhost:8080, data in volume opendatavisualizer-data +``` + +There is no lint step besides `tsc` (strict, no unused locals/parameters). `dotnet build` with the server running fails on locked DLLs; build or test only `Schaad.OpenData.Tests` in that case. + +## Architecture + +Visualizes open data from opendata.swiss. The first (and so far only) dataset is the canton of Thurgau's hourly traffic counts by vehicle class (`dbu-tba-1` on data.tg.ch, CC0): 64 counting stations, each with exactly two directions, 10 vehicle classes (SWISS10). + +| Project | Role | +|---|---| +| `Schaad.OpenData.Traffic` | Fetching, JSON cache, road geometry, analysis — everything except HTTP hosting | +| `Schaad.OpenData.Server` | Minimal API (`/api/traffic/*` in `Traffic/TrafficEndpoints.cs`), serves the built client from `wwwroot` with SPA fallback | +| `Schaad.OpenData.Tests` | Tests for the Traffic library | +| `client/` | React SPA: Leaflet map with animated traffic, Chart.js station charts | + +### Data flow + +``` +TrafficRefreshService (BackgroundService, checks every 15 min) + → TrafficRefresher + → ThurgauTrafficClient data.tg.ch JSON export (only the last ~14 days are available there) + → TrafficSnapshot.Merge imported days replace cached days, older days are kept + → TrafficCacheStorage {DataPath}/traffic/thurgau/{stations.json, meta.json, counts/yyyy-MM-dd.json, geometry-vN.json} + → StationGeometryService road path per station direction (once per station) + → TrafficDataStore immutable TrafficSnapshot swapped atomically, read by the endpoints + → TrafficAnalysis shapes the snapshot for the API (DayView for the map, StationSummary for charts) +``` + +The cache accumulates history beyond the source's two-week window; refreshes only fetch from the last cached day minus one (`where=datum >= …`). `RefreshInterval` and `DataPath` are configured under `Traffic` in `appsettings.json` (`Traffic__DataPath=/app/data` in Docker). Yearly archives back to 2011 exist as `https://ogdtg.ch/verkehrsdaten/fahrzeugklassen/{year}_fzkl_data.csv.gz` but are not imported yet. + +### Road geometry (for the direction animation) + +The source has one point per station and directions as text (`nach X`, `von X`, or just `X`). `StationGeometryService` turns that into a road polyline per direction, oriented in driving direction: + +1. `SwisstopoClient.GetRoadSegmentsAsync` loads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200). `verkehrsbedeutung != 999998` marks main roads, `objektart <= 11` drivable roads (higher values are paths and lane markings). +2. `RoadPathBuilder.BuildRoadPath` snaps to a main road within 60 m (else the nearest drivable road), stitches connected segments (≤ 60° turn, penalty for changing road class) and trims to ±300 m. +3. Stations named `… Kreisel …` sit on a roundabout arm: `BuildArmPath` follows every road segment within 80 m outward (600 m) and keeps the one that gets furthest toward the target town (a roundabout ring loops back and loses); it falls back to `BuildRoadPath`. +4. `SwisstopoClient.FindPlaceAsync` geocodes the target town (SearchServer, municipalities + gazetteer, label must contain the name with ä→ae etc., nearest candidate wins — "Landquart" is also a place in Arbon). Names with `/` are split, since the SearchServer returns 503 for slashes. +5. `RoadPathBuilder.Orient` points each direction toward (`nach`) or away from (`von`) its target; the two directions of a station are always opposite. + +When the geometry algorithm changes, bump `GeometryFileName` in `TrafficCacheStorage` so all stations are rebuilt. + +### Client + +- `traffic/flowAnimator.ts` owns the animation clock (time of day in hours, play/pause, speed) and draws on a canvas above Leaflet's overlay pane. Dots spawn per direction at a rate proportional to the interpolated hourly count, colored and sized by vehicle group, offset to the right of the driving direction. It reports the time to React at ~10 Hz via `onTick`; React components only get the integer hour, so markers and charts don't re-render every frame. +- The vehicle class order in `traffic/vehicleClasses.ts` must match the `VehicleClass` enum / `VehicleCounts.ToArray()` order; count arrays in the API are positional. +- UI language is German (de-CH). Base maps are swisstopo WMTS layers (grey `pixelkarte-grau` as default, colour `pixelkarte-farbe`, aerial `swissimage`), switchable via Leaflet's layer control; the choice is stored in localStorage (`odv.baseMap`). + +## Conventions + +- C#: `var`, primary constructors, file-scoped namespaces, one type per file, no comments, `DateOnly` for dates, central package versions in `Directory.Packages.props`, shared settings in `Directory.Build.props`. +- Classes that tests need to mock (`SwisstopoClient`, `StationGeometryService`, `ThurgauTrafficClient`, `TrafficCacheStorage`) use `virtual` methods instead of single-implementation interfaces. +- Tests: one `TestShould` class per subject, method names `DoThisWhenThat`, Shouldly assertions (no `Assert.*`). HTTP clients are tested with a stub `HttpMessageHandler`, storage with a temp directory cleaned up in `Dispose`. +- TypeScript: Prettier config in `client/.prettierrc.json` (single quotes, width 100). diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..e3aac5e --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,7 @@ + + + net10.0 + enable + enable + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..0ad9fec --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,18 @@ + + + true + + + + + + + + + + + + + + + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e519964 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,31 @@ +# ---- Stage 1: build the React client into Schaad.OpenData.Server/wwwroot ---- +FROM node:20-bookworm-slim AS build-client +WORKDIR /src/client +COPY client/package.json client/package-lock.json ./ +RUN npm ci +COPY client/ ./ +RUN npm run build + +# ---- Stage 2: publish the ASP.NET Core server ---- +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build-server +WORKDIR /src +COPY Directory.Build.props Directory.Packages.props ./ +COPY Schaad.OpenData.Server/Schaad.OpenData.Server.csproj Schaad.OpenData.Server/ +COPY Schaad.OpenData.Traffic/Schaad.OpenData.Traffic.csproj Schaad.OpenData.Traffic/ +RUN dotnet restore Schaad.OpenData.Server/Schaad.OpenData.Server.csproj +COPY Schaad.OpenData.Server/ Schaad.OpenData.Server/ +COPY Schaad.OpenData.Traffic/ Schaad.OpenData.Traffic/ +COPY --from=build-client /src/Schaad.OpenData.Server/wwwroot Schaad.OpenData.Server/wwwroot +RUN dotnet publish Schaad.OpenData.Server/Schaad.OpenData.Server.csproj -c Release -o /app --no-restore + +# ---- Stage 3: runtime ---- +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime +WORKDIR /app +COPY --from=build-server /app . +RUN mkdir -p /app/data && chown $APP_UID /app/data +USER $APP_UID +ENV ASPNETCORE_HTTP_PORTS=8080 \ + Traffic__DataPath=/app/data +VOLUME /app/data +EXPOSE 8080 +ENTRYPOINT ["dotnet", "Schaad.OpenData.Server.dll"] diff --git a/OpenDataVisualizer.sln b/OpenDataVisualizer.sln new file mode 100644 index 0000000..5afcf5e --- /dev/null +++ b/OpenDataVisualizer.sln @@ -0,0 +1,62 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Server", "Schaad.OpenData.Server\Schaad.OpenData.Server.csproj", "{1FA0941D-C852-4C39-BE2C-83BAEE0E8455}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Traffic", "Schaad.OpenData.Traffic\Schaad.OpenData.Traffic.csproj", "{CFF994E7-F580-4622-9870-43AE1984C703}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Tests", "Schaad.OpenData.Tests\Schaad.OpenData.Tests.csproj", "{9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Debug|x64.ActiveCfg = Debug|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Debug|x64.Build.0 = Debug|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Debug|x86.ActiveCfg = Debug|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Debug|x86.Build.0 = Debug|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Release|Any CPU.Build.0 = Release|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Release|x64.ActiveCfg = Release|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Release|x64.Build.0 = Release|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Release|x86.ActiveCfg = Release|Any CPU + {1FA0941D-C852-4C39-BE2C-83BAEE0E8455}.Release|x86.Build.0 = Release|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Debug|x64.ActiveCfg = Debug|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Debug|x64.Build.0 = Debug|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Debug|x86.ActiveCfg = Debug|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Debug|x86.Build.0 = Debug|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Release|Any CPU.Build.0 = Release|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Release|x64.ActiveCfg = Release|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Release|x64.Build.0 = Release|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Release|x86.ActiveCfg = Release|Any CPU + {CFF994E7-F580-4622-9870-43AE1984C703}.Release|x86.Build.0 = Release|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Debug|x64.ActiveCfg = Debug|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Debug|x64.Build.0 = Debug|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Debug|x86.ActiveCfg = Debug|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Debug|x86.Build.0 = Debug|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Release|Any CPU.Build.0 = Release|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Release|x64.ActiveCfg = Release|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Release|x64.Build.0 = Release|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Release|x86.ActiveCfg = Release|Any CPU + {9B7A4811-ADD2-4317-99FC-8A385F9E0B8E}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md index 37983b6..64ca545 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,24 @@ # OpenDataVisualizer -Visualization for opendata.swiss \ No newline at end of file +Visualization for [opendata.swiss](https://opendata.swiss). + +## Traffic in the canton of Thurgau + +The first visualization shows the hourly traffic counts of the canton of Thurgau +([Verkehrszähldaten motorisierter Individualverkehr nach Fahrzeugklassen](https://opendata.swiss/de/dataset/verkehrszahldaten-motorisierter-individualverkehr-nach-fahrzeugklassen), CC0): + +- animated map: vehicles drive along the real road in both directions of each counting station, the dot density follows the hourly count and the colour the vehicle class +- time controls to play through a day or jump to any hour +- station panel with the counts per vehicle class, hourly values, average weekday/weekend profile, daily totals and class distribution + +Road geometry comes from swisstopo (swissTLM3D), the base map from swisstopo as well. + +## Run + +```bash +docker compose up --build +``` + +Then open http://localhost:8080. On the first start the app downloads the data from data.tg.ch and builds the road geometry (one to two minutes); it is cached in the `opendatavisualizer-data` volume and refreshed every six hours. Since data.tg.ch only serves the last two weeks, the cache keeps growing over time. + +For development see [CLAUDE.md](CLAUDE.md). diff --git a/Schaad.OpenData.Server/Program.cs b/Schaad.OpenData.Server/Program.cs new file mode 100644 index 0000000..957d714 --- /dev/null +++ b/Schaad.OpenData.Server/Program.cs @@ -0,0 +1,17 @@ +using Schaad.OpenData.Server.Traffic; +using Schaad.OpenData.Traffic; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddTraffic(builder.Configuration); +builder.Services.AddResponseCompression(options => options.EnableForHttps = true); + +var app = builder.Build(); + +app.UseResponseCompression(); +app.UseDefaultFiles(); +app.UseStaticFiles(); +app.MapTrafficEndpoints(); +app.MapFallbackToFile("index.html"); + +app.Run(); diff --git a/Schaad.OpenData.Server/Properties/launchSettings.json b/Schaad.OpenData.Server/Properties/launchSettings.json new file mode 100644 index 0000000..543069b --- /dev/null +++ b/Schaad.OpenData.Server/Properties/launchSettings.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5080", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj b/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj new file mode 100644 index 0000000..be7eac3 --- /dev/null +++ b/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Schaad.OpenData.Server/Traffic/DirectionResponse.cs b/Schaad.OpenData.Server/Traffic/DirectionResponse.cs new file mode 100644 index 0000000..c9f92b0 --- /dev/null +++ b/Schaad.OpenData.Server/Traffic/DirectionResponse.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Server.Traffic; + +public sealed record DirectionResponse(string Name, IReadOnlyList Path); diff --git a/Schaad.OpenData.Server/Traffic/MetaResponse.cs b/Schaad.OpenData.Server/Traffic/MetaResponse.cs new file mode 100644 index 0000000..a8174a3 --- /dev/null +++ b/Schaad.OpenData.Server/Traffic/MetaResponse.cs @@ -0,0 +1,10 @@ +namespace Schaad.OpenData.Server.Traffic; + +public sealed record MetaResponse( + string Title, + string Publisher, + string SourceUrl, + string License, + IReadOnlyList VehicleClasses, + IReadOnlyList Dates, + DateTimeOffset? LastRefresh); diff --git a/Schaad.OpenData.Server/Traffic/StationResponse.cs b/Schaad.OpenData.Server/Traffic/StationResponse.cs new file mode 100644 index 0000000..cbddc87 --- /dev/null +++ b/Schaad.OpenData.Server/Traffic/StationResponse.cs @@ -0,0 +1,30 @@ +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Server.Traffic; + +public sealed record StationResponse( + int Code, + string Name, + string Municipality, + string Address, + string Road, + double Lat, + double Lon, + bool FollowsRoad, + IReadOnlyList Directions) +{ + public static StationResponse From(Station station, StationGeometry? geometry) => new( + station.Code, + station.Name, + station.Municipality, + station.Address, + station.Road, + station.Location.Lat, + station.Location.Lon, + geometry?.FollowsRoad ?? false, + station.Directions + .Select(direction => new DirectionResponse( + direction, + geometry?.Directions.FirstOrDefault(d => d.Direction == direction)?.Path.Select(p => new[] { p.Lat, p.Lon }).ToList() ?? [])) + .ToList()); +} diff --git a/Schaad.OpenData.Server/Traffic/TrafficEndpoints.cs b/Schaad.OpenData.Server/Traffic/TrafficEndpoints.cs new file mode 100644 index 0000000..42f7122 --- /dev/null +++ b/Schaad.OpenData.Server/Traffic/TrafficEndpoints.cs @@ -0,0 +1,43 @@ +using Schaad.OpenData.Traffic.Analysis; +using Schaad.OpenData.Traffic.Models; +using Schaad.OpenData.Traffic.Storage; + +namespace Schaad.OpenData.Server.Traffic; + +public static class TrafficEndpoints +{ + public static IEndpointRouteBuilder MapTrafficEndpoints(this IEndpointRouteBuilder endpoints) + { + var group = endpoints.MapGroup("/api/traffic"); + + group.MapGet("/meta", (TrafficDataStore store) => + { + var snapshot = store.Current; + return new MetaResponse( + "Verkehrszähldaten motorisierter Individualverkehr nach Fahrzeugklassen", + "Kanton Thurgau, Tiefbauamt (data.tg.ch / opendata.swiss)", + "https://opendata.swiss/de/dataset/verkehrszahldaten-motorisierter-individualverkehr-nach-fahrzeugklassen", + "CC0 1.0", + Enum.GetNames().Select(n => char.ToLowerInvariant(n[0]) + n[1..]).ToList(), + snapshot.Dates, + snapshot.LastRefresh); + }); + + group.MapGet("/stations", (TrafficDataStore store) => + { + var snapshot = store.Current; + return snapshot.Stations.Values + .OrderBy(s => s.Code) + .Select(s => StationResponse.From(s, snapshot.Geometry.GetValueOrDefault(s.Code))) + .ToList(); + }); + + group.MapGet("/days/{date}", (DateOnly date, TrafficDataStore store) => + TrafficAnalysis.BuildDay(store.Current, date) is { } day ? Results.Ok(day) : Results.NotFound()); + + group.MapGet("/stations/{code:int}/summary", (int code, DateOnly? from, DateOnly? to, TrafficDataStore store) => + TrafficAnalysis.BuildStationSummary(store.Current, code, from, to) is { } summary ? Results.Ok(summary) : Results.NotFound()); + + return endpoints; + } +} diff --git a/Schaad.OpenData.Server/appsettings.json b/Schaad.OpenData.Server/appsettings.json new file mode 100644 index 0000000..99fac96 --- /dev/null +++ b/Schaad.OpenData.Server/appsettings.json @@ -0,0 +1,14 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "System.Net.Http.HttpClient": "Warning" + } + }, + "AllowedHosts": "*", + "Traffic": { + "DataPath": "../data", + "RefreshInterval": "06:00:00" + } +} diff --git a/Schaad.OpenData.Tests/DirectionTargetTestShould.cs b/Schaad.OpenData.Tests/DirectionTargetTestShould.cs new file mode 100644 index 0000000..b2d9891 --- /dev/null +++ b/Schaad.OpenData.Tests/DirectionTargetTestShould.cs @@ -0,0 +1,24 @@ +using Schaad.OpenData.Traffic.Geometry; + +namespace Schaad.OpenData.Tests; + +public class DirectionTargetTestShould +{ + [Fact] + public void ParseDestinationWhenDirectionStartsWithNach() + { + DirectionTarget.Parse("nach Kreuzlingen").ShouldBe(new DirectionTarget("Kreuzlingen", true)); + } + + [Fact] + public void ParseOriginWhenDirectionStartsWithVon() + { + DirectionTarget.Parse("von Frauenfeld").ShouldBe(new DirectionTarget("Frauenfeld", false)); + } + + [Fact] + public void TreatPlainNameAsDestinationWhenDirectionHasNoPrefix() + { + DirectionTarget.Parse("Diessenhofen").ShouldBe(new DirectionTarget("Diessenhofen", true)); + } +} diff --git a/Schaad.OpenData.Tests/RoadPathBuilderTestShould.cs b/Schaad.OpenData.Tests/RoadPathBuilderTestShould.cs new file mode 100644 index 0000000..ad0b8d1 --- /dev/null +++ b/Schaad.OpenData.Tests/RoadPathBuilderTestShould.cs @@ -0,0 +1,190 @@ +using Schaad.OpenData.Traffic.Geometry; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Tests; + +public class RoadPathBuilderTestShould +{ + private static RoadSegment Segment(bool isMainRoad, params (double East, double North)[] points) => + new(points.Select(p => TestData.Meters(p.East, p.North)).ToList(), isMainRoad); + + private static RoadSegment FootPath(params (double East, double North)[] points) => + new(points.Select(p => TestData.Meters(p.East, p.North)).ToList(), false, false); + + private static double East(GeoPoint point) => + (point.Lon - TestData.Origin.Lon) * 111_320 * Math.Cos(TestData.Origin.Lat * Math.PI / 180); + + [Fact] + public void StitchConnectedSegmentsWhenBuildingRoadPath() + { + var segments = new[] + { + Segment(true, (-50, 0), (50, 0)), + Segment(true, (50, 0), (200, 0)), + Segment(true, (-200, 0), (-50, 0)), + }; + + var path = RoadPathBuilder.BuildRoadPath(TestData.Origin, segments, 150)!; + + East(path[0]).ShouldBe(-150, 0.5); + East(path[^1]).ShouldBe(150, 0.5); + } + + [Fact] + public void StopAtSharpTurnWhenStitchingSegments() + { + var segments = new[] + { + Segment(true, (-100, 0), (50, 0)), + Segment(true, (50, 0), (50, 200)), + }; + + var path = RoadPathBuilder.BuildRoadPath(TestData.Origin, segments, 150)!; + + East(path[^1]).ShouldBe(50, 0.5); + } + + [Fact] + public void IgnoreFootpathWhenItIsCloserThanTheRoad() + { + var segments = new[] + { + FootPath((-100, 1), (100, 1)), + Segment(false, (-100, 20), (100, 20)), + }; + + var path = RoadPathBuilder.BuildRoadPath(TestData.Origin, segments, 50)!; + + path.ShouldAllBe(p => Math.Abs(p.Lat - TestData.Meters(0, 20).Lat) < 1e-6); + } + + [Fact] + public void PreferMainRoadWhenItIsWithinSnapDistance() + { + var segments = new[] + { + Segment(false, (-100, 2), (100, 2)), + Segment(true, (-100, 40), (100, 40)), + }; + + var path = RoadPathBuilder.BuildRoadPath(TestData.Origin, segments, 50)!; + + path.ShouldAllBe(p => Math.Abs(p.Lat - TestData.Meters(0, 40).Lat) < 1e-6); + } + + [Fact] + public void UseNearestDrivableRoadWhenMainRoadIsFarAway() + { + var segments = new[] + { + Segment(false, (-100, 2), (100, 2)), + Segment(true, (-100, 300), (100, 300)), + }; + + var path = RoadPathBuilder.BuildRoadPath(TestData.Origin, segments, 50)!; + + path.ShouldAllBe(p => Math.Abs(p.Lat - TestData.Meters(0, 2).Lat) < 1e-6); + } + + [Fact] + public void ContinueOnSameRoadClassWhenRoadForks() + { + var segments = new[] + { + Segment(true, (-100, 0), (50, 0)), + Segment(false, (50, 0), (200, 5)), + Segment(true, (50, 0), (200, -40)), + }; + + var path = RoadPathBuilder.BuildRoadPath(TestData.Origin, segments, 150)!; + + path[^1].Lat.ShouldBeLessThan(TestData.Origin.Lat); + } + + [Fact] + public void ReturnNullWhenNoSegmentsAreFound() + { + RoadPathBuilder.BuildRoadPath(TestData.Origin, [], 100).ShouldBeNull(); + } + + [Fact] + public void OrientDestinationTowardTargetWhenOrienting() + { + var path = new[] { TestData.Meters(-100, 0), TestData.Meters(100, 0) }; + var directions = new[] + { + new ResolvedDirection("nach West", new DirectionTarget("West", true), TestData.Meters(-5000, 0)), + new ResolvedDirection("nach Ost", new DirectionTarget("Ost", true), TestData.Meters(5000, 0)), + }; + + var oriented = RoadPathBuilder.Orient(TestData.Origin, path, directions); + + East(oriented[0].Path[^1]).ShouldBeLessThan(0); + East(oriented[1].Path[^1]).ShouldBeGreaterThan(0); + } + + [Fact] + public void OrientOriginAwayFromTargetWhenOrienting() + { + var path = new[] { TestData.Meters(-100, 0), TestData.Meters(100, 0) }; + var directions = new[] + { + new ResolvedDirection("von Ost", new DirectionTarget("Ost", false), TestData.Meters(5000, 0)), + new ResolvedDirection("nach Ost", new DirectionTarget("Ost", true), TestData.Meters(5000, 0)), + }; + + var oriented = RoadPathBuilder.Orient(TestData.Origin, path, directions); + + East(oriented[0].Path[^1]).ShouldBeLessThan(0); + East(oriented[1].Path[^1]).ShouldBeGreaterThan(0); + } + + [Fact] + public void MakeDirectionsOppositeWhenNoTargetIsResolved() + { + var path = new[] { TestData.Meters(-100, 0), TestData.Meters(100, 0) }; + var directions = new[] + { + new ResolvedDirection("nach A", new DirectionTarget("A", true), null), + new ResolvedDirection("nach B", new DirectionTarget("B", true), null), + }; + + var oriented = RoadPathBuilder.Orient(TestData.Origin, path, directions); + + oriented[0].Path[0].ShouldBe(oriented[1].Path[^1]); + } + + [Fact] + public void FollowArmTowardTargetWhenStationIsAtRoundabout() + { + var segments = new[] + { + Segment(false, (5, -15), (20, 0), (5, 15)), + Segment(true, (0, 0), (-150, 10)), + Segment(true, (-150, 10), (-400, 20)), + Segment(true, (30, 0), (300, 0)), + }; + + var arm = RoadPathBuilder.BuildArmPath(TestData.Origin, segments, TestData.Meters(-4000, 300), 300)!; + + East(arm[0]).ShouldBe(0, 0.5); + East(arm[^1]).ShouldBeLessThan(-290); + } + + [Fact] + public void ReturnNullWhenNoArmIsNearRoundabout() + { + var segments = new[] { Segment(true, (-300, 200), (300, 200)) }; + + RoadPathBuilder.BuildArmPath(TestData.Origin, segments, TestData.Meters(-4000, 0), 300).ShouldBeNull(); + } + + [Fact] + public void PointStraightPathTowardTargetWhenNoRoadIsFound() + { + var path = RoadPathBuilder.BuildStraightPath(TestData.Origin, TestData.Meters(1000, 0), 100); + + East(path[0]).ShouldBe(-100, 0.5); + East(path[^1]).ShouldBe(100, 0.5); + } +} diff --git a/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj b/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj new file mode 100644 index 0000000..835d962 --- /dev/null +++ b/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj @@ -0,0 +1,25 @@ + + + + false + + + + + + + + + + + + + + + + + + + + + diff --git a/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs b/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs new file mode 100644 index 0000000..c7ce702 --- /dev/null +++ b/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs @@ -0,0 +1,40 @@ +using NSubstitute; +using Schaad.OpenData.Traffic.Geometry; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Tests; + +public class StationGeometryServiceTestShould +{ + private readonly SwisstopoClient swisstopoClient = Substitute.For(new HttpClient()); + private readonly StationGeometryService service; + + public StationGeometryServiceTestShould() + { + service = new StationGeometryService(swisstopoClient); + swisstopoClient.GetRoadSegmentsAsync(default, default, default).ReturnsForAnyArgs([]); + } + + [Fact] + public async Task LookUpEachPartWhenPlaceNameContainsSlash() + { + swisstopoClient.FindPlaceAsync("Wilen", Arg.Any(), Arg.Any()).Returns((GeoPoint?)null); + swisstopoClient.FindPlaceAsync("Busswil", Arg.Any(), Arg.Any()).Returns(TestData.Meters(0, 2000)); + + var geometry = await service.BuildAsync(TestData.Station(413, "Wilen/Busswil", "Gloten"), CancellationToken.None); + + await swisstopoClient.DidNotReceive().FindPlaceAsync("Wilen/Busswil", Arg.Any(), Arg.Any()); + geometry.Directions[0].Path[^1].Lat.ShouldBeGreaterThan(TestData.Origin.Lat); + } + + [Fact] + public async Task UseStraightPathWhenNoRoadIsFound() + { + swisstopoClient.FindPlaceAsync(default!, default, default).ReturnsForAnyArgs(TestData.Meters(1000, 0)); + + var geometry = await service.BuildAsync(TestData.Station(1, "nach A", "von A"), CancellationToken.None); + + geometry.FollowsRoad.ShouldBeFalse(); + geometry.Directions.Count.ShouldBe(2); + } +} diff --git a/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs b/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs new file mode 100644 index 0000000..5c3ea47 --- /dev/null +++ b/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs @@ -0,0 +1,124 @@ +using System.Net; +using System.Text; +using Schaad.OpenData.Traffic.Geometry; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Tests; + +public class SwisstopoClientTestShould +{ + private sealed class StubHandler(params (HttpStatusCode Status, string Body)[] responses) : HttpMessageHandler + { + private int index; + + public List Requests { get; } = []; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request.RequestUri!); + var (status, body) = responses[Math.Min(index++, responses.Length - 1)]; + return Task.FromResult(new HttpResponseMessage(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }); + } + } + + private static SwisstopoClient Client(StubHandler handler) => + new(new HttpClient(handler) { BaseAddress = new Uri("https://api3.geo.admin.ch/rest/services/api/") }); + + private const string LandquartResults = """ + {"results":[ + {"attrs":{"label":"Landquart (GR)","lat":46.956,"lon":9.578}}, + {"attrs":{"label":"Landquart [district]","lat":46.961,"lon":9.560}}, + {"attrs":{"label":"Populated Place Landquart (TG) - Arbon","lat":47.501,"lon":9.423}}, + {"attrs":{"label":"Landstrasse","lat":47.502,"lon":9.425}} + ]} + """; + + [Fact] + public async Task PickNearestMatchingPlaceWhenNameIsAmbiguous() + { + var client = Client(new StubHandler((HttpStatusCode.OK, LandquartResults))); + + var place = await client.FindPlaceAsync("Landquart", new GeoPoint(47.502, 9.425), CancellationToken.None); + + place.ShouldBe(new GeoPoint(47.501, 9.423)); + } + + [Fact] + public async Task MatchTransliteratedNameWhenLabelHasUmlaut() + { + var body = """{"results":[{"attrs":{"label":"Tägerwilen (TG)","lat":47.645,"lon":9.129}}]}"""; + var client = Client(new StubHandler((HttpStatusCode.OK, body))); + + var place = await client.FindPlaceAsync("Taegerwilen", new GeoPoint(47.62, 9.1), CancellationToken.None); + + place.ShouldBe(new GeoPoint(47.645, 9.129)); + } + + [Fact] + public async Task ReturnNullWhenNoLabelMatches() + { + var body = """{"results":[{"attrs":{"label":"Somewhere Else","lat":47,"lon":9}}]}"""; + var client = Client(new StubHandler((HttpStatusCode.OK, body))); + + (await client.FindPlaceAsync("Nowhere", new GeoPoint(47, 9), CancellationToken.None)).ShouldBeNull(); + } + + [Fact] + public async Task RetryWhenServiceIsTemporarilyUnavailable() + { + var handler = new StubHandler((HttpStatusCode.ServiceUnavailable, ""), (HttpStatusCode.OK, LandquartResults)); + var client = Client(handler); + + var place = await client.FindPlaceAsync("Landquart", new GeoPoint(47.5, 9.42), CancellationToken.None); + + place.ShouldNotBeNull(); + handler.Requests.Count.ShouldBe(2); + } + + [Fact] + public async Task FlagRoadsWithTrafficImportanceAsMainRoadsWhenLoadingSegments() + { + var body = """ + {"results":[ + {"geometry":{"type":"MultiLineString","coordinates":[[[9.1,47.5],[9.2,47.5]]]},"properties":{"verkehrsbedeutung":200}}, + {"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"verkehrsbedeutung":999998}} + ]} + """; + var client = Client(new StubHandler((HttpStatusCode.OK, body))); + + var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None); + + segments.Select(s => s.IsMainRoad).ShouldBe([true, false]); + segments[0].Points[0].ShouldBe(new GeoPoint(47.5, 9.1)); + } + + [Fact] + public async Task FlagPathsAsNotDrivableWhenLoadingSegments() + { + var body = """ + {"results":[ + {"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{"objektart":9}}, + {"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"objektart":15}} + ]} + """; + var client = Client(new StubHandler((HttpStatusCode.OK, body))); + + var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None); + + segments.Select(s => s.IsDrivable).ShouldBe([true, false]); + } + + [Fact] + public async Task RequestNextPageWhenPageIsFull() + { + var feature = """{"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{}}"""; + var fullPage = $$"""{"results":[{{string.Join(',', Enumerable.Repeat(feature, 200))}}]}"""; + var handler = new StubHandler((HttpStatusCode.OK, fullPage), (HttpStatusCode.OK, $$"""{"results":[{{feature}}]}""")); + var client = Client(handler); + + var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None); + + segments.Count.ShouldBe(201); + handler.Requests.Select(r => r.Query.Contains("offset=200")).ShouldBe([false, true]); + } +} diff --git a/Schaad.OpenData.Tests/TestData.cs b/Schaad.OpenData.Tests/TestData.cs new file mode 100644 index 0000000..ff1cf33 --- /dev/null +++ b/Schaad.OpenData.Tests/TestData.cs @@ -0,0 +1,45 @@ +using Schaad.OpenData.Traffic.Models; +using Schaad.OpenData.Traffic.Source; + +namespace Schaad.OpenData.Tests; + +internal static class TestData +{ + public static readonly GeoPoint Origin = new(47.5, 9.0); + + public static GeoPoint Meters(double east, double north) => new( + Origin.Lat + north / 111_320, + Origin.Lon + east / (111_320 * Math.Cos(Origin.Lat * Math.PI / 180))); + + public static VehicleCounts Cars(int cars, int trucks = 0) => new(0, 0, cars, 0, 0, 0, 0, trucks, 0, 0); + + public static HourlyCount Count(int station, string direction, DateOnly date, int hour, int cars, int trucks = 0) => + new(station, direction, date, hour, Cars(cars, trucks)); + + public static Station Station(int code, params string[] directions) => + new(code, $"Station {code}", "Gemeinde", "Strasse", "H1", Origin, directions); + + public static ThurgauTrafficRecord Record( + int code = 49, + string direction = "nach Diessenhofen", + string date = "2026-10-27", + int hour = 13, + int? cars = 220, + ThurgauCoordinates? coordinates = null) => new() + { + Code = code, + Name = "WAGENHAUSEN Wagenhausen - Diessenhofen", + Municipality = "Wagenhausen", + Address = "Hauptstrasse", + Road = "H13", + Direction = direction, + Date = date, + Hour = hour, + Bus = 1, + Motorcycle = 12, + Car = cars, + Truck = 6, + SemiTrailerTruck = 5, + Coordinates = coordinates ?? new ThurgauCoordinates { Lat = 47.66, Lon = 8.84 }, + }; +} diff --git a/Schaad.OpenData.Tests/ThurgauTrafficMapperTestShould.cs b/Schaad.OpenData.Tests/ThurgauTrafficMapperTestShould.cs new file mode 100644 index 0000000..7e8bb83 --- /dev/null +++ b/Schaad.OpenData.Tests/ThurgauTrafficMapperTestShould.cs @@ -0,0 +1,62 @@ +using Schaad.OpenData.Traffic.Source; + +namespace Schaad.OpenData.Tests; + +public class ThurgauTrafficMapperTestShould +{ + [Fact] + public void CreateOneStationWithAllDirectionsWhenRecordsShareTheStationCode() + { + var import = ThurgauTrafficMapper.Map([ + TestData.Record(direction: "nach Diessenhofen"), + TestData.Record(direction: "nach Wagenhausen"), + TestData.Record(direction: "nach Diessenhofen", hour: 14), + ]); + + import.Stations.Count.ShouldBe(1); + import.Stations[0].Directions.ShouldBe(["nach Diessenhofen", "nach Wagenhausen"]); + import.Counts.Count.ShouldBe(3); + } + + [Fact] + public void MapVehicleClassesWhenRecordIsValid() + { + var count = ThurgauTrafficMapper.Map([TestData.Record()]).Counts.Single(); + + count.Date.ShouldBe(new DateOnly(2026, 10, 27)); + count.Hour.ShouldBe(13); + count.Counts.Car.ShouldBe(220); + count.Counts.Truck.ShouldBe(6); + count.Counts.Total.ShouldBe(1 + 12 + 220 + 6 + 5); + } + + [Fact] + public void TreatMissingClassCountsAsZeroWhenMapping() + { + var count = ThurgauTrafficMapper.Map([TestData.Record(cars: null)]).Counts.Single(); + + count.Counts.Car.ShouldBe(0); + } + + [Fact] + public void SkipRecordWhenDateIsInvalid() + { + ThurgauTrafficMapper.Map([TestData.Record(date: "unknown")]).Counts.ShouldBeEmpty(); + } + + [Fact] + public void CollapseWhitespaceWhenMappingStationName() + { + var station = ThurgauTrafficMapper.Map([TestData.Record()]).Stations.Single(); + + station.Name.ShouldBe("WAGENHAUSEN Wagenhausen - Diessenhofen"); + } + + [Fact] + public void AcceptTimestampWhenDateContainsTime() + { + var count = ThurgauTrafficMapper.Map([TestData.Record(date: "2026-10-27T00:00:00+00:00")]).Counts.Single(); + + count.Date.ShouldBe(new DateOnly(2026, 10, 27)); + } +} diff --git a/Schaad.OpenData.Tests/TrafficAnalysisTestShould.cs b/Schaad.OpenData.Tests/TrafficAnalysisTestShould.cs new file mode 100644 index 0000000..38edb83 --- /dev/null +++ b/Schaad.OpenData.Tests/TrafficAnalysisTestShould.cs @@ -0,0 +1,75 @@ +using Schaad.OpenData.Traffic.Analysis; +using Schaad.OpenData.Traffic.Storage; + +namespace Schaad.OpenData.Tests; + +public class TrafficAnalysisTestShould +{ + private static readonly DateOnly Friday = new(2026, 10, 30); + private static readonly DateOnly Saturday = new(2026, 10, 31); + private static readonly DateOnly Sunday = new(2026, 11, 1); + + private static TrafficSnapshot Snapshot() => new( + [TestData.Station(7, "nach A", "nach B")], + [ + TestData.Count(7, "nach A", Friday, 8, 100, 10), + TestData.Count(7, "nach B", Friday, 8, 50), + TestData.Count(7, "nach A", Saturday, 8, 40), + TestData.Count(7, "nach A", Sunday, 8, 20), + ], + [], + null); + + [Fact] + public void ReturnTwentyFourHoursPerDirectionWhenBuildingDay() + { + var day = TrafficAnalysis.BuildDay(Snapshot(), Friday)!; + + var directions = day.Stations.ShouldHaveSingleItem().Directions; + directions.Count.ShouldBe(2); + directions[0].Hours.Count.ShouldBe(24); + directions[0].Hours[8]![2].ShouldBe(100); + directions[0].Hours[9].ShouldBeNull(); + } + + [Fact] + public void ReturnNullWhenBuildingDayWithoutData() + { + TrafficAnalysis.BuildDay(Snapshot(), new DateOnly(2020, 1, 1)).ShouldBeNull(); + } + + [Fact] + public void SeparateWeekdayAndWeekendWhenBuildingProfiles() + { + var summary = TrafficAnalysis.BuildStationSummary(Snapshot(), 7, null, null)!; + + var directionA = summary.Directions[0]; + directionA.WeekdayProfile[8].ShouldBe(110); + directionA.WeekendProfile[8].ShouldBe(30); + directionA.WeekdayProfile[3].ShouldBe(0); + } + + [Fact] + public void SumAllClassesAndDirectionsWhenBuildingClassTotals() + { + var summary = TrafficAnalysis.BuildStationSummary(Snapshot(), 7, null, null)!; + + summary.ClassTotals[2].ShouldBe(210); + summary.ClassTotals[7].ShouldBe(10); + } + + [Fact] + public void LimitToDateRangeWhenBuildingSummary() + { + var summary = TrafficAnalysis.BuildStationSummary(Snapshot(), 7, Saturday, Sunday)!; + + summary.Directions[0].Daily.Select(d => d.Date).ShouldBe([Saturday, Sunday]); + summary.Directions[1].Hourly.ShouldBeEmpty(); + } + + [Fact] + public void ReturnNullWhenStationIsUnknown() + { + TrafficAnalysis.BuildStationSummary(Snapshot(), 999, null, null).ShouldBeNull(); + } +} diff --git a/Schaad.OpenData.Tests/TrafficCacheStorageTestShould.cs b/Schaad.OpenData.Tests/TrafficCacheStorageTestShould.cs new file mode 100644 index 0000000..ca3d81d --- /dev/null +++ b/Schaad.OpenData.Tests/TrafficCacheStorageTestShould.cs @@ -0,0 +1,68 @@ +using Microsoft.Extensions.Options; +using Schaad.OpenData.Traffic; +using Schaad.OpenData.Traffic.Models; +using Schaad.OpenData.Traffic.Storage; + +namespace Schaad.OpenData.Tests; + +public sealed class TrafficCacheStorageTestShould : IDisposable +{ + private static readonly DateOnly Day = new(2026, 10, 27); + + private readonly string dataPath = Path.Combine(Path.GetTempPath(), "odv-tests-" + Guid.NewGuid().ToString("N")); + private readonly TrafficCacheStorage storage; + + public TrafficCacheStorageTestShould() + { + storage = new TrafficCacheStorage(Options.Create(new TrafficOptions { DataPath = dataPath })); + } + + public void Dispose() + { + if (Directory.Exists(dataPath)) + { + Directory.Delete(dataPath, true); + } + } + + [Fact] + public async Task ReturnEmptySnapshotWhenCacheDoesNotExist() + { + var snapshot = await storage.LoadAsync(CancellationToken.None); + + snapshot.Stations.ShouldBeEmpty(); + snapshot.Dates.ShouldBeEmpty(); + snapshot.LastRefresh.ShouldBeNull(); + } + + [Fact] + public async Task RestoreSavedDataWhenLoading() + { + var refreshedAt = new DateTimeOffset(2026, 11, 6, 12, 0, 0, TimeSpan.Zero); + var geometry = new StationGeometry(1, true, [new DirectionGeometry("nach A", [TestData.Origin, TestData.Meters(10, 0)])]); + var snapshot = new TrafficSnapshot( + [TestData.Station(1, "nach A")], + [TestData.Count(1, "nach A", Day, 8, 42, 3)], + [geometry], + refreshedAt); + + await storage.SaveAsync(snapshot, [Day], CancellationToken.None); + await storage.SaveGeometryAsync(snapshot, CancellationToken.None); + var loaded = await storage.LoadAsync(CancellationToken.None); + + loaded.Stations[1].Directions.ShouldBe(["nach A"]); + loaded.CountsByDate[Day].ShouldHaveSingleItem().Counts.ShouldBe(TestData.Cars(42, 3)); + loaded.Geometry[1].Directions.ShouldHaveSingleItem().Path.Count.ShouldBe(2); + loaded.LastRefresh.ShouldBe(refreshedAt); + } + + [Fact] + public async Task WriteOneFilePerDayWhenSaving() + { + var snapshot = new TrafficSnapshot([], [TestData.Count(1, "nach A", Day, 8, 1)], [], null); + + await storage.SaveAsync(snapshot, [Day], CancellationToken.None); + + File.Exists(Path.Combine(dataPath, "traffic", "thurgau", "counts", "2026-10-27.json")).ShouldBeTrue(); + } +} diff --git a/Schaad.OpenData.Tests/TrafficSnapshotTestShould.cs b/Schaad.OpenData.Tests/TrafficSnapshotTestShould.cs new file mode 100644 index 0000000..6e85f00 --- /dev/null +++ b/Schaad.OpenData.Tests/TrafficSnapshotTestShould.cs @@ -0,0 +1,61 @@ +using Schaad.OpenData.Traffic.Models; +using Schaad.OpenData.Traffic.Storage; + +namespace Schaad.OpenData.Tests; + +public class TrafficSnapshotTestShould +{ + private static readonly DateOnly Monday = new(2026, 10, 26); + private static readonly DateOnly Tuesday = new(2026, 10, 27); + private static readonly DateTimeOffset RefreshedAt = new(2026, 11, 6, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public void ReplaceImportedDaysWhenMerging() + { + var snapshot = new TrafficSnapshot( + [TestData.Station(1, "nach A")], + [TestData.Count(1, "nach A", Tuesday, 8, 10), TestData.Count(1, "nach A", Tuesday, 9, 20)], + [], + null); + var import = new TrafficImport([TestData.Station(1, "nach A")], [TestData.Count(1, "nach A", Tuesday, 8, 99)]); + + var merged = snapshot.Merge(import, RefreshedAt, out var changedDays); + + merged.CountsByDate[Tuesday].ShouldHaveSingleItem().Counts.Car.ShouldBe(99); + changedDays.ShouldBe([Tuesday]); + merged.LastRefresh.ShouldBe(RefreshedAt); + } + + [Fact] + public void KeepDaysMissingInImportWhenMerging() + { + var snapshot = new TrafficSnapshot([TestData.Station(1, "nach A")], [TestData.Count(1, "nach A", Monday, 8, 10)], [], null); + var import = new TrafficImport([], [TestData.Count(1, "nach A", Tuesday, 8, 20)]); + + var merged = snapshot.Merge(import, RefreshedAt, out _); + + merged.Dates.ShouldBe([Monday, Tuesday]); + merged.Stations.Keys.ShouldContain(1); + } + + [Fact] + public void KeepGeometryWhenMerging() + { + var geometry = new StationGeometry(1, true, []); + var snapshot = new TrafficSnapshot([TestData.Station(1, "nach A")], [], [geometry], null); + + var merged = snapshot.Merge(new TrafficImport([TestData.Station(1, "nach A")], []), RefreshedAt, out _); + + merged.Geometry[1].ShouldBeSameAs(geometry); + } + + [Fact] + public void ReplaceStationGeometryWhenAddingGeometry() + { + var snapshot = new TrafficSnapshot([TestData.Station(1, "nach A")], [], [new StationGeometry(1, false, [])], null); + + var updated = snapshot.WithGeometry([new StationGeometry(1, true, [])]); + + updated.Geometry[1].FollowsRoad.ShouldBeTrue(); + } +} diff --git a/Schaad.OpenData.Traffic/Analysis/DailyTotal.cs b/Schaad.OpenData.Traffic/Analysis/DailyTotal.cs new file mode 100644 index 0000000..692745e --- /dev/null +++ b/Schaad.OpenData.Traffic/Analysis/DailyTotal.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Analysis; + +public sealed record DailyTotal(DateOnly Date, int Total); diff --git a/Schaad.OpenData.Traffic/Analysis/DayView.cs b/Schaad.OpenData.Traffic/Analysis/DayView.cs new file mode 100644 index 0000000..66a76bd --- /dev/null +++ b/Schaad.OpenData.Traffic/Analysis/DayView.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Analysis; + +public sealed record DayView(DateOnly Date, IReadOnlyList Stations); diff --git a/Schaad.OpenData.Traffic/Analysis/DirectionDayView.cs b/Schaad.OpenData.Traffic/Analysis/DirectionDayView.cs new file mode 100644 index 0000000..099fc01 --- /dev/null +++ b/Schaad.OpenData.Traffic/Analysis/DirectionDayView.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Analysis; + +public sealed record DirectionDayView(string Direction, IReadOnlyList Hours); diff --git a/Schaad.OpenData.Traffic/Analysis/DirectionSummary.cs b/Schaad.OpenData.Traffic/Analysis/DirectionSummary.cs new file mode 100644 index 0000000..ed0e1e3 --- /dev/null +++ b/Schaad.OpenData.Traffic/Analysis/DirectionSummary.cs @@ -0,0 +1,8 @@ +namespace Schaad.OpenData.Traffic.Analysis; + +public sealed record DirectionSummary( + string Direction, + IReadOnlyList Hourly, + IReadOnlyList Daily, + double[] WeekdayProfile, + double[] WeekendProfile); diff --git a/Schaad.OpenData.Traffic/Analysis/HourlyTotal.cs b/Schaad.OpenData.Traffic/Analysis/HourlyTotal.cs new file mode 100644 index 0000000..c05f43e --- /dev/null +++ b/Schaad.OpenData.Traffic/Analysis/HourlyTotal.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Analysis; + +public sealed record HourlyTotal(DateTime Time, int Total); diff --git a/Schaad.OpenData.Traffic/Analysis/StationDayView.cs b/Schaad.OpenData.Traffic/Analysis/StationDayView.cs new file mode 100644 index 0000000..d176a57 --- /dev/null +++ b/Schaad.OpenData.Traffic/Analysis/StationDayView.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Analysis; + +public sealed record StationDayView(int Code, IReadOnlyList Directions); diff --git a/Schaad.OpenData.Traffic/Analysis/StationSummary.cs b/Schaad.OpenData.Traffic/Analysis/StationSummary.cs new file mode 100644 index 0000000..60edfbb --- /dev/null +++ b/Schaad.OpenData.Traffic/Analysis/StationSummary.cs @@ -0,0 +1,8 @@ +namespace Schaad.OpenData.Traffic.Analysis; + +public sealed record StationSummary( + int Code, + DateOnly From, + DateOnly To, + IReadOnlyList Directions, + int[] ClassTotals); diff --git a/Schaad.OpenData.Traffic/Analysis/TrafficAnalysis.cs b/Schaad.OpenData.Traffic/Analysis/TrafficAnalysis.cs new file mode 100644 index 0000000..4b9ce80 --- /dev/null +++ b/Schaad.OpenData.Traffic/Analysis/TrafficAnalysis.cs @@ -0,0 +1,94 @@ +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; +} diff --git a/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs b/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs new file mode 100644 index 0000000..99a33a2 --- /dev/null +++ b/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs @@ -0,0 +1,20 @@ +namespace Schaad.OpenData.Traffic.Geometry; + +public sealed record DirectionTarget(string Place, bool IsDestination) +{ + public static DirectionTarget Parse(string direction) + { + var text = direction.Trim(); + if (text.StartsWith("nach ", StringComparison.OrdinalIgnoreCase)) + { + return new DirectionTarget(text[5..].Trim(), true); + } + + if (text.StartsWith("von ", StringComparison.OrdinalIgnoreCase)) + { + return new DirectionTarget(text[4..].Trim(), false); + } + + return new DirectionTarget(text, true); + } +} diff --git a/Schaad.OpenData.Traffic/Geometry/LocalProjection.cs b/Schaad.OpenData.Traffic/Geometry/LocalProjection.cs new file mode 100644 index 0000000..8a18e68 --- /dev/null +++ b/Schaad.OpenData.Traffic/Geometry/LocalProjection.cs @@ -0,0 +1,19 @@ +using System.Numerics; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Geometry; + +internal readonly struct LocalProjection(GeoPoint origin) +{ + private const double MetersPerDegreeLat = 111_320; + + private double MetersPerDegreeLon => MetersPerDegreeLat * Math.Cos(origin.Lat * Math.PI / 180); + + public Vector2 ToLocal(GeoPoint point) => new( + (float)((point.Lon - origin.Lon) * MetersPerDegreeLon), + (float)((point.Lat - origin.Lat) * MetersPerDegreeLat)); + + public GeoPoint ToGeo(Vector2 point) => new( + Math.Round(origin.Lat + point.Y / MetersPerDegreeLat, 7), + Math.Round(origin.Lon + point.X / MetersPerDegreeLon, 7)); +} diff --git a/Schaad.OpenData.Traffic/Geometry/ResolvedDirection.cs b/Schaad.OpenData.Traffic/Geometry/ResolvedDirection.cs new file mode 100644 index 0000000..5d24077 --- /dev/null +++ b/Schaad.OpenData.Traffic/Geometry/ResolvedDirection.cs @@ -0,0 +1,5 @@ +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Geometry; + +public sealed record ResolvedDirection(string Direction, DirectionTarget Target, GeoPoint? TargetLocation); diff --git a/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs b/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs new file mode 100644 index 0000000..cd8ec1d --- /dev/null +++ b/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs @@ -0,0 +1,285 @@ +using System.Numerics; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Geometry; + +public static class RoadPathBuilder +{ + private const float JoinToleranceMeters = 2f; + private const double MaxTurnDegrees = 60; + private const double MinimumSideLengthMeters = 60; + private const double MainRoadSnapMeters = 60; + private const double RoadClassChangePenaltyDegrees = 25; + + private const double ArmSearchMeters = 80; + private const float ArmDistancePenalty = 2f; + + private sealed record RoadLine(List Points, bool IsMainRoad); + + private static List ToLines(IReadOnlyList segments, LocalProjection projection) + { + var usable = segments.Where(s => s.Points.Count >= 2).ToList(); + var drivable = usable.Where(s => s.IsDrivable).ToList(); + return (drivable.Count > 0 ? drivable : usable) + .Select(s => new RoadLine(s.Points.Select(projection.ToLocal).ToList(), s.IsMainRoad)) + .ToList(); + } + + public static IReadOnlyList? BuildRoadPath(GeoPoint station, IReadOnlyList segments, double halfLengthMeters) + { + var projection = new LocalProjection(station); + var lines = ToLines(segments, projection); + if (lines.Count == 0) + { + return null; + } + + var distances = lines.Select(l => DistanceToPolyline(Vector2.Zero, l.Points)).ToList(); + var nearestMain = Enumerable.Range(0, lines.Count) + .Where(i => lines[i].IsMainRoad && distances[i] <= MainRoadSnapMeters) + .OrderBy(i => distances[i]) + .Select(i => (int?)i) + .FirstOrDefault(); + var start = nearestMain ?? Enumerable.Range(0, lines.Count).MinBy(i => distances[i]); + + var chain = new List(lines[start].Points); + var used = new HashSet { start }; + var preferMain = lines[start].IsMainRoad; + ExtendAtEnd(chain, lines, used, preferMain, halfLengthMeters); + chain.Reverse(); + ExtendAtEnd(chain, lines, used, preferMain, halfLengthMeters); + chain.Reverse(); + + var trimmed = Trim(chain, ArcPositionOf(Vector2.Zero, chain), halfLengthMeters); + return trimmed.Count >= 2 ? trimmed.Select(projection.ToGeo).ToList() : null; + } + + public static IReadOnlyList? BuildArmPath(GeoPoint station, IReadOnlyList segments, GeoPoint target, double lengthMeters) + { + var projection = new LocalProjection(station); + var toward = projection.ToLocal(target); + if (toward.LengthSquared() < 1e-6f) + { + return null; + } + + toward = Vector2.Normalize(toward); + var lines = ToLines(segments, projection); + var best = lines + .Select((line, index) => (Index: index, Distance: DistanceToPolyline(Vector2.Zero, line.Points))) + .Where(c => c.Distance <= ArmSearchMeters) + .Select(c => + { + var arm = FollowArm(lines, c.Index, toward, lengthMeters); + var progress = arm.Count >= 2 && Length(arm) >= MinimumSideLengthMeters ? Vector2.Dot(arm[^1], toward) : float.MinValue; + return (Arm: arm, Score: progress - ArmDistancePenalty * c.Distance); + }) + .Where(c => c.Score > float.MinValue / 2) + .OrderByDescending(c => c.Score) + .FirstOrDefault(); + + return best.Arm?.Select(projection.ToGeo).ToList(); + } + + private static List FollowArm(List lines, int start, Vector2 toward, double lengthMeters) + { + var chain = new List(lines[start].Points); + if (Vector2.Dot(chain[^1] - chain[0], toward) < 0) + { + chain.Reverse(); + } + + ExtendAtEnd(chain, lines, [start], lines[start].IsMainRoad, lengthMeters); + var position = ArcPositionOf(Vector2.Zero, chain); + return Trim(chain, position + lengthMeters / 2, lengthMeters / 2); + } + + public static IReadOnlyList BuildStraightPath(GeoPoint station, GeoPoint? toward, double halfLengthMeters) + { + var projection = new LocalProjection(station); + var direction = toward is { } target ? projection.ToLocal(target) : Vector2.UnitX; + direction = direction.LengthSquared() < 1e-6 ? Vector2.UnitX : Vector2.Normalize(direction); + var offset = direction * (float)halfLengthMeters; + return [projection.ToGeo(-offset), projection.ToGeo(offset)]; + } + + public static IReadOnlyList Orient(GeoPoint station, IReadOnlyList path, IReadOnlyList directions) + { + var projection = new LocalProjection(station); + var pathVector = projection.ToLocal(path[^1]) - projection.ToLocal(path[0]); + + var forward = directions + .Select(d => d.TargetLocation is { } location + ? (bool?)((Vector2.Dot(pathVector, projection.ToLocal(location)) > 0) == d.Target.IsDestination) + : null) + .ToList(); + + if (forward.Count == 2) + { + forward = (forward[0], forward[1]) switch + { + (null, null) => [true, false], + ({ } first, null) => [first, !first], + (null, { } second) => [!second, second], + ({ } first, { } second) when first == second => [first, !first], + _ => forward, + }; + } + + var reversed = path.Reverse().ToList(); + return directions + .Select((d, i) => new DirectionGeometry(d.Direction, (forward[i] ?? i % 2 == 0) ? path : reversed)) + .ToList(); + } + + private static void ExtendAtEnd(List chain, List lines, HashSet used, bool preferMain, double halfLengthMeters) + { + while (Length(chain) - ArcPositionOf(Vector2.Zero, chain) < halfLengthMeters) + { + var end = chain[^1]; + var heading = Heading(chain[^2], end); + var best = -1; + var bestAngle = double.MaxValue; + List? bestLine = null; + + for (var i = 0; i < lines.Count; i++) + { + if (used.Contains(i)) + { + continue; + } + + var line = lines[i].Points; + List? oriented = null; + if (Vector2.Distance(line[0], end) <= JoinToleranceMeters) + { + oriented = line; + } + else if (Vector2.Distance(line[^1], end) <= JoinToleranceMeters) + { + oriented = Enumerable.Reverse(line).ToList(); + } + + if (oriented is null) + { + continue; + } + + var next = oriented.FirstOrDefault(p => Vector2.Distance(p, oriented[0]) > 0.5f, oriented[^1]); + var angle = Math.Acos(Math.Clamp(Vector2.Dot(heading, Heading(oriented[0], next)), -1f, 1f)) * 180 / Math.PI; + var score = angle + (lines[i].IsMainRoad == preferMain ? 0 : RoadClassChangePenaltyDegrees); + if (angle <= MaxTurnDegrees && score < bestAngle) + { + best = i; + bestAngle = score; + bestLine = oriented; + } + } + + if (bestLine is null) + { + return; + } + + used.Add(best); + chain.AddRange(bestLine.Skip(1)); + } + } + + private static List Trim(List chain, double center, double halfLengthMeters) + { + var from = center - halfLengthMeters; + var to = center + halfLengthMeters; + var result = new List(); + var position = 0d; + + for (var i = 0; i < chain.Count - 1; i++) + { + var a = chain[i]; + var b = chain[i + 1]; + var length = Vector2.Distance(a, b); + var start = position; + var end = position + length; + position = end; + + if (end < from || start > to || length <= 0) + { + continue; + } + + if (result.Count == 0) + { + result.Add(start >= from ? a : Vector2.Lerp(a, b, (float)((from - start) / length))); + } + + if (end <= to) + { + result.Add(b); + } + else + { + result.Add(Vector2.Lerp(a, b, (float)((to - start) / length))); + break; + } + } + + return result; + } + + private static double ArcPositionOf(Vector2 point, List chain) + { + var bestDistance = double.MaxValue; + var bestPosition = 0d; + var position = 0d; + + for (var i = 0; i < chain.Count - 1; i++) + { + var a = chain[i]; + var b = chain[i + 1]; + var length = Vector2.Distance(a, b); + var t = length > 0 ? Math.Clamp(Vector2.Dot(point - a, b - a) / (length * length), 0, 1) : 0; + var distance = Vector2.Distance(point, Vector2.Lerp(a, b, t)); + if (distance < bestDistance) + { + bestDistance = distance; + bestPosition = position + t * length; + } + + position += length; + } + + return bestPosition; + } + + private static double DistanceToPolyline(Vector2 point, List line) + { + var best = double.MaxValue; + for (var i = 0; i < line.Count - 1; i++) + { + var a = line[i]; + var b = line[i + 1]; + var lengthSquared = Vector2.DistanceSquared(a, b); + var t = lengthSquared > 0 ? Math.Clamp(Vector2.Dot(point - a, b - a) / lengthSquared, 0, 1) : 0; + best = Math.Min(best, Vector2.Distance(point, Vector2.Lerp(a, b, t))); + } + + return best; + } + + private static double Length(List chain) + { + var length = 0d; + for (var i = 0; i < chain.Count - 1; i++) + { + length += Vector2.Distance(chain[i], chain[i + 1]); + } + + return length; + } + + private static Vector2 Heading(Vector2 from, Vector2 to) + { + var delta = to - from; + return delta.LengthSquared() < 1e-6f ? Vector2.UnitX : Vector2.Normalize(delta); + } +} diff --git a/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs b/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs new file mode 100644 index 0000000..f00f3c5 --- /dev/null +++ b/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs @@ -0,0 +1,5 @@ +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Geometry; + +public sealed record RoadSegment(IReadOnlyList Points, bool IsMainRoad, bool IsDrivable = true); diff --git a/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs b/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs new file mode 100644 index 0000000..38b7394 --- /dev/null +++ b/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs @@ -0,0 +1,45 @@ +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Geometry; + +public class StationGeometryService(SwisstopoClient swisstopoClient) +{ + private const double HalfPathLengthMeters = 300; + private const double SearchRadiusMeters = 650; + + public virtual async Task BuildAsync(Station station, CancellationToken cancellationToken) + { + var directions = new List(); + foreach (var direction in station.Directions) + { + var target = DirectionTarget.Parse(direction); + directions.Add(new ResolvedDirection(direction, target, await FindPlaceAsync(target.Place, station.Location, cancellationToken))); + } + + var targetLocation = directions.Select(d => d.TargetLocation).FirstOrDefault(l => l is not null); + var isRoundaboutArm = station.Name.Contains("Kreisel", StringComparison.OrdinalIgnoreCase) && targetLocation is not null; + + var segments = await swisstopoClient.GetRoadSegmentsAsync(station.Location, SearchRadiusMeters, cancellationToken); + var roadPath = (isRoundaboutArm + ? RoadPathBuilder.BuildArmPath(station.Location, segments, targetLocation!.Value, 2 * HalfPathLengthMeters) + : null) + ?? RoadPathBuilder.BuildRoadPath(station.Location, segments, HalfPathLengthMeters); + + var path = roadPath ?? RoadPathBuilder.BuildStraightPath(station.Location, targetLocation, HalfPathLengthMeters); + + return new StationGeometry(station.Code, roadPath is not null, RoadPathBuilder.Orient(station.Location, path, directions)); + } + + private async Task FindPlaceAsync(string place, GeoPoint near, CancellationToken cancellationToken) + { + foreach (var part in place.Split('/', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + { + if (await swisstopoClient.FindPlaceAsync(part, near, cancellationToken) is { } location) + { + return location; + } + } + + return null; + } +} diff --git a/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs b/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs new file mode 100644 index 0000000..327abb0 --- /dev/null +++ b/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs @@ -0,0 +1,140 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using System.Text.RegularExpressions; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Geometry; + +public partial class SwisstopoClient(HttpClient httpClient) +{ + private const double MetersPerDegreeLat = 111_320; + private const int NoTrafficImportance = 999998; + private const int MaxRetries = 2; + private const int PageSize = 200; + private const int MaxPages = 5; + private const int MaxDrivableObjectKind = 11; + + public virtual async Task> GetRoadSegmentsAsync(GeoPoint center, double radiusMeters, CancellationToken cancellationToken) + { + var deltaLat = radiusMeters / MetersPerDegreeLat; + var deltaLon = radiusMeters / (MetersPerDegreeLat * Math.Cos(center.Lat * Math.PI / 180)); + var envelope = string.Join(',', new[] + { + center.Lon - deltaLon, + center.Lat - deltaLat, + center.Lon + deltaLon, + center.Lat + deltaLat, + }.Select(v => v.ToString("F6", CultureInfo.InvariantCulture))); + + var baseUrl = "MapServer/identify?geometryType=esriGeometryEnvelope" + + $"&geometry={envelope}&mapExtent={envelope}&sr=4326&imageDisplay=1000,1000,96&tolerance=0" + + $"&layers=all:ch.swisstopo.swisstlm3d-strassen&returnGeometry=true&geometryFormat=geojson&limit={PageSize}"; + + var segments = new List(); + for (var page = 0; page < MaxPages; page++) + { + using var document = await GetJsonAsync($"{baseUrl}&offset={page * PageSize}", cancellationToken); + var features = document.RootElement.GetProperty("results").EnumerateArray().ToList(); + segments.AddRange(features.SelectMany(ToSegments)); + if (features.Count < PageSize) + { + break; + } + } + + return segments; + } + + private static IEnumerable ToSegments(JsonElement feature) + { + if (!feature.TryGetProperty("geometry", out var geometry)) + { + return []; + } + + var hasProperties = feature.TryGetProperty("properties", out var properties); + var isMainRoad = hasProperties + && properties.TryGetProperty("verkehrsbedeutung", out var importance) + && importance.ValueKind == JsonValueKind.Number + && importance.GetInt32() != NoTrafficImportance; + var isDrivable = !hasProperties + || !properties.TryGetProperty("objektart", out var kind) + || kind.ValueKind != JsonValueKind.Number + || kind.GetInt32() <= MaxDrivableObjectKind; + + var coordinates = geometry.GetProperty("coordinates"); + var parts = geometry.GetProperty("type").GetString() switch + { + "LineString" => [coordinates], + "MultiLineString" => coordinates.EnumerateArray().ToList(), + _ => new List(), + }; + + return parts.Select(part => new RoadSegment( + part.EnumerateArray().Select(p => new GeoPoint(p[1].GetDouble(), p[0].GetDouble())).ToList(), + isMainRoad, + isDrivable)); + } + + public virtual async Task FindPlaceAsync(string name, GeoPoint near, CancellationToken cancellationToken) + { + var url = $"SearchServer?type=locations&origins=gg25,gazetteer&limit=15&searchText={Uri.EscapeDataString(name)}"; + using var document = await GetJsonAsync(url, cancellationToken); + var normalizedName = Normalize(name); + var candidates = document.RootElement.GetProperty("results").EnumerateArray() + .Select(r => r.GetProperty("attrs")) + .Where(a => a.TryGetProperty("lat", out _) && a.TryGetProperty("lon", out _)) + .Select(a => ( + Label: HtmlTags().Replace(a.GetProperty("label").GetString() ?? "", ""), + Location: new GeoPoint(a.GetProperty("lat").GetDouble(), a.GetProperty("lon").GetDouble()))) + .Where(c => Normalize(c.Label).Contains(normalizedName, StringComparison.Ordinal)) + .ToList(); + + if (candidates.Count == 0) + { + return null; + } + + return candidates.MinBy(c => DistanceSquared(c.Location, near)).Location; + } + + private async Task GetJsonAsync(string url, CancellationToken cancellationToken) + { + var response = await httpClient.GetAsync(url, cancellationToken); + for (var attempt = 1; attempt <= MaxRetries && IsTransient(response.StatusCode); attempt++) + { + response.Dispose(); + await Task.Delay(TimeSpan.FromSeconds(2 * attempt), cancellationToken); + response = await httpClient.GetAsync(url, cancellationToken); + } + + using var _ = response; + response.EnsureSuccessStatusCode(); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + return await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken); + } + + private static bool IsTransient(HttpStatusCode statusCode) => + statusCode is HttpStatusCode.TooManyRequests || (int)statusCode >= 500; + + private static double DistanceSquared(GeoPoint a, GeoPoint b) + { + var dLat = a.Lat - b.Lat; + var dLon = (a.Lon - b.Lon) * Math.Cos(a.Lat * Math.PI / 180); + return dLat * dLat + dLon * dLon; + } + + internal static string Normalize(string value) => value + .ToLowerInvariant() + .Replace("ä", "ae", StringComparison.Ordinal) + .Replace("ö", "oe", StringComparison.Ordinal) + .Replace("ü", "ue", StringComparison.Ordinal) + .Replace("é", "e", StringComparison.Ordinal) + .Replace("è", "e", StringComparison.Ordinal) + .Replace(".", "", StringComparison.Ordinal) + .Replace(" ", "", StringComparison.Ordinal); + + [GeneratedRegex("<[^>]+>")] + private static partial Regex HtmlTags(); +} diff --git a/Schaad.OpenData.Traffic/Models/DirectionGeometry.cs b/Schaad.OpenData.Traffic/Models/DirectionGeometry.cs new file mode 100644 index 0000000..a77ed90 --- /dev/null +++ b/Schaad.OpenData.Traffic/Models/DirectionGeometry.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Models; + +public sealed record DirectionGeometry(string Direction, IReadOnlyList Path); diff --git a/Schaad.OpenData.Traffic/Models/GeoPoint.cs b/Schaad.OpenData.Traffic/Models/GeoPoint.cs new file mode 100644 index 0000000..7d83f5f --- /dev/null +++ b/Schaad.OpenData.Traffic/Models/GeoPoint.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Models; + +public readonly record struct GeoPoint(double Lat, double Lon); diff --git a/Schaad.OpenData.Traffic/Models/HourlyCount.cs b/Schaad.OpenData.Traffic/Models/HourlyCount.cs new file mode 100644 index 0000000..02a79cd --- /dev/null +++ b/Schaad.OpenData.Traffic/Models/HourlyCount.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Models; + +public sealed record HourlyCount(int StationCode, string Direction, DateOnly Date, int Hour, VehicleCounts Counts); diff --git a/Schaad.OpenData.Traffic/Models/Station.cs b/Schaad.OpenData.Traffic/Models/Station.cs new file mode 100644 index 0000000..ee384e8 --- /dev/null +++ b/Schaad.OpenData.Traffic/Models/Station.cs @@ -0,0 +1,10 @@ +namespace Schaad.OpenData.Traffic.Models; + +public sealed record Station( + int Code, + string Name, + string Municipality, + string Address, + string Road, + GeoPoint Location, + IReadOnlyList Directions); diff --git a/Schaad.OpenData.Traffic/Models/StationGeometry.cs b/Schaad.OpenData.Traffic/Models/StationGeometry.cs new file mode 100644 index 0000000..aa88ab4 --- /dev/null +++ b/Schaad.OpenData.Traffic/Models/StationGeometry.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Models; + +public sealed record StationGeometry(int StationCode, bool FollowsRoad, IReadOnlyList Directions); diff --git a/Schaad.OpenData.Traffic/Models/TrafficImport.cs b/Schaad.OpenData.Traffic/Models/TrafficImport.cs new file mode 100644 index 0000000..45896a3 --- /dev/null +++ b/Schaad.OpenData.Traffic/Models/TrafficImport.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Models; + +public sealed record TrafficImport(IReadOnlyList Stations, IReadOnlyList Counts); diff --git a/Schaad.OpenData.Traffic/Models/VehicleClass.cs b/Schaad.OpenData.Traffic/Models/VehicleClass.cs new file mode 100644 index 0000000..109876a --- /dev/null +++ b/Schaad.OpenData.Traffic/Models/VehicleClass.cs @@ -0,0 +1,15 @@ +namespace Schaad.OpenData.Traffic.Models; + +public enum VehicleClass +{ + Bus, + Motorcycle, + Car, + CarWithTrailer, + Van, + VanWithTrailer, + VanWithSemiTrailer, + Truck, + TruckWithTrailer, + SemiTrailerTruck, +} diff --git a/Schaad.OpenData.Traffic/Models/VehicleCounts.cs b/Schaad.OpenData.Traffic/Models/VehicleCounts.cs new file mode 100644 index 0000000..c7e8e30 --- /dev/null +++ b/Schaad.OpenData.Traffic/Models/VehicleCounts.cs @@ -0,0 +1,31 @@ +namespace Schaad.OpenData.Traffic.Models; + +public readonly record struct VehicleCounts( + int Bus, + int Motorcycle, + int Car, + int CarWithTrailer, + int Van, + int VanWithTrailer, + int VanWithSemiTrailer, + int Truck, + int TruckWithTrailer, + int SemiTrailerTruck) +{ + public int Total => Bus + Motorcycle + Car + CarWithTrailer + Van + VanWithTrailer + VanWithSemiTrailer + Truck + TruckWithTrailer + SemiTrailerTruck; + + public int[] ToArray() => + [Bus, Motorcycle, Car, CarWithTrailer, Van, VanWithTrailer, VanWithSemiTrailer, Truck, TruckWithTrailer, SemiTrailerTruck]; + + public static VehicleCounts operator +(VehicleCounts a, VehicleCounts b) => new( + a.Bus + b.Bus, + a.Motorcycle + b.Motorcycle, + a.Car + b.Car, + a.CarWithTrailer + b.CarWithTrailer, + a.Van + b.Van, + a.VanWithTrailer + b.VanWithTrailer, + a.VanWithSemiTrailer + b.VanWithSemiTrailer, + a.Truck + b.Truck, + a.TruckWithTrailer + b.TruckWithTrailer, + a.SemiTrailerTruck + b.SemiTrailerTruck); +} diff --git a/Schaad.OpenData.Traffic/Schaad.OpenData.Traffic.csproj b/Schaad.OpenData.Traffic/Schaad.OpenData.Traffic.csproj new file mode 100644 index 0000000..66bf7e7 --- /dev/null +++ b/Schaad.OpenData.Traffic/Schaad.OpenData.Traffic.csproj @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/Schaad.OpenData.Traffic/Source/ThurgauCoordinates.cs b/Schaad.OpenData.Traffic/Source/ThurgauCoordinates.cs new file mode 100644 index 0000000..7314f8e --- /dev/null +++ b/Schaad.OpenData.Traffic/Source/ThurgauCoordinates.cs @@ -0,0 +1,12 @@ +using System.Text.Json.Serialization; + +namespace Schaad.OpenData.Traffic.Source; + +public sealed class ThurgauCoordinates +{ + [JsonPropertyName("lat")] + public double Lat { get; init; } + + [JsonPropertyName("lon")] + public double Lon { get; init; } +} diff --git a/Schaad.OpenData.Traffic/Source/ThurgauTrafficClient.cs b/Schaad.OpenData.Traffic/Source/ThurgauTrafficClient.cs new file mode 100644 index 0000000..3d59ea0 --- /dev/null +++ b/Schaad.OpenData.Traffic/Source/ThurgauTrafficClient.cs @@ -0,0 +1,32 @@ +using System.Text.Json; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Source; + +public class ThurgauTrafficClient(HttpClient httpClient, IOptions options) +{ + public virtual async Task FetchAsync(DateOnly? since, CancellationToken cancellationToken) + { + var url = options.Value.SourceUrl; + if (since is { } from) + { + url += "?where=" + Uri.EscapeDataString($"datum >= date'{from:yyyy-MM-dd}'"); + } + + using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + response.EnsureSuccessStatusCode(); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + + var records = new List(); + await foreach (var record in JsonSerializer.DeserializeAsyncEnumerable(stream, cancellationToken: cancellationToken)) + { + if (record is not null) + { + records.Add(record); + } + } + + return ThurgauTrafficMapper.Map(records); + } +} diff --git a/Schaad.OpenData.Traffic/Source/ThurgauTrafficMapper.cs b/Schaad.OpenData.Traffic/Source/ThurgauTrafficMapper.cs new file mode 100644 index 0000000..0c95b91 --- /dev/null +++ b/Schaad.OpenData.Traffic/Source/ThurgauTrafficMapper.cs @@ -0,0 +1,77 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Source; + +public static partial class ThurgauTrafficMapper +{ + public static TrafficImport Map(IEnumerable records) + { + var counts = new List(); + var firstRecords = new Dictionary(); + var directions = new Dictionary>(); + + foreach (var record in records) + { + if (record.Coordinates is null || !TryParseDate(record.Date, out var date) || record.Hour is < 0 or > 23) + { + continue; + } + + firstRecords.TryAdd(record.Code, record); + if (!directions.TryGetValue(record.Code, out var stationDirections)) + { + stationDirections = new Dictionary(StringComparer.Ordinal); + directions[record.Code] = stationDirections; + } + + var direction = Clean(record.Direction); + if (!stationDirections.TryGetValue(direction, out var pooled)) + { + pooled = direction; + stationDirections[direction] = pooled; + } + + counts.Add(new HourlyCount(record.Code, pooled, date, record.Hour, ToCounts(record))); + } + + var stations = firstRecords.Values + .Select(r => new Station( + r.Code, + Clean(r.Name), + Clean(r.Municipality), + Clean(r.Address), + Clean(r.Road), + new GeoPoint(r.Coordinates!.Lat, r.Coordinates.Lon), + [.. directions[r.Code].Keys.Order(StringComparer.Ordinal)])) + .OrderBy(s => s.Code) + .ToList(); + + return new TrafficImport(stations, counts); + } + + private static VehicleCounts ToCounts(ThurgauTrafficRecord record) => new( + record.Bus ?? 0, + record.Motorcycle ?? 0, + record.Car ?? 0, + record.CarWithTrailer ?? 0, + record.Van ?? 0, + record.VanWithTrailer ?? 0, + record.VanWithSemiTrailer ?? 0, + record.Truck ?? 0, + record.TruckWithTrailer ?? 0, + record.SemiTrailerTruck ?? 0); + + private static bool TryParseDate(string? value, out DateOnly date) + { + date = default; + return value is { Length: >= 10 } + && DateOnly.TryParseExact(value[..10], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date); + } + + private static string Clean(string? value) => MultipleSpaces().Replace(value ?? "", " ").Trim(); + + [GeneratedRegex(@"\s+")] + private static partial Regex MultipleSpaces(); +} diff --git a/Schaad.OpenData.Traffic/Source/ThurgauTrafficRecord.cs b/Schaad.OpenData.Traffic/Source/ThurgauTrafficRecord.cs new file mode 100644 index 0000000..9c5545c --- /dev/null +++ b/Schaad.OpenData.Traffic/Source/ThurgauTrafficRecord.cs @@ -0,0 +1,63 @@ +using System.Text.Json.Serialization; + +namespace Schaad.OpenData.Traffic.Source; + +public sealed class ThurgauTrafficRecord +{ + [JsonPropertyName("code")] + public int Code { get; init; } + + [JsonPropertyName("name")] + public string? Name { get; init; } + + [JsonPropertyName("gemeinde")] + public string? Municipality { get; init; } + + [JsonPropertyName("adresse")] + public string? Address { get; init; } + + [JsonPropertyName("strasse")] + public string? Road { get; init; } + + [JsonPropertyName("richtung")] + public string? Direction { get; init; } + + [JsonPropertyName("datum")] + public string? Date { get; init; } + + [JsonPropertyName("stunde")] + public int Hour { get; init; } + + [JsonPropertyName("bus")] + public int? Bus { get; init; } + + [JsonPropertyName("mr")] + public int? Motorcycle { get; init; } + + [JsonPropertyName("pw")] + public int? Car { get; init; } + + [JsonPropertyName("pw0")] + public int? CarWithTrailer { get; init; } + + [JsonPropertyName("lief")] + public int? Van { get; init; } + + [JsonPropertyName("lief0")] + public int? VanWithTrailer { get; init; } + + [JsonPropertyName("lief_aufl")] + public int? VanWithSemiTrailer { get; init; } + + [JsonPropertyName("lw")] + public int? Truck { get; init; } + + [JsonPropertyName("lw0")] + public int? TruckWithTrailer { get; init; } + + [JsonPropertyName("sattelzug")] + public int? SemiTrailerTruck { get; init; } + + [JsonPropertyName("koordinaten")] + public ThurgauCoordinates? Coordinates { get; init; } +} diff --git a/Schaad.OpenData.Traffic/Storage/TrafficCacheMeta.cs b/Schaad.OpenData.Traffic/Storage/TrafficCacheMeta.cs new file mode 100644 index 0000000..ee43aa7 --- /dev/null +++ b/Schaad.OpenData.Traffic/Storage/TrafficCacheMeta.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Traffic.Storage; + +public sealed record TrafficCacheMeta(DateTimeOffset? LastRefresh); diff --git a/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs b/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs new file mode 100644 index 0000000..a7aca15 --- /dev/null +++ b/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs @@ -0,0 +1,74 @@ +using System.Globalization; +using System.Text.Json; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Storage; + +public class TrafficCacheStorage(IOptions options) +{ + private const string DayFormat = "yyyy-MM-dd"; + private const string GeometryFileName = "geometry-v5.json"; + + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true }; + + private string RootPath => Path.Combine(Path.GetFullPath(options.Value.DataPath), "traffic", "thurgau"); + + private string CountsPath => Path.Combine(RootPath, "counts"); + + public virtual async Task LoadAsync(CancellationToken cancellationToken) + { + var stations = await ReadAsync>(Path.Combine(RootPath, "stations.json"), cancellationToken) ?? []; + var geometry = await ReadAsync>(Path.Combine(RootPath, GeometryFileName), cancellationToken) ?? []; + var meta = await ReadAsync(Path.Combine(RootPath, "meta.json"), cancellationToken); + + var counts = new List(); + if (Directory.Exists(CountsPath)) + { + foreach (var file in Directory.EnumerateFiles(CountsPath, "*.json").Order(StringComparer.Ordinal)) + { + counts.AddRange(await ReadAsync>(file, cancellationToken) ?? []); + } + } + + return new TrafficSnapshot(stations, counts, geometry, meta?.LastRefresh); + } + + public virtual async Task SaveAsync(TrafficSnapshot snapshot, IReadOnlyCollection changedDays, CancellationToken cancellationToken) + { + await WriteAsync(Path.Combine(RootPath, "stations.json"), snapshot.Stations.Values.OrderBy(s => s.Code).ToList(), cancellationToken); + foreach (var day in changedDays) + { + var path = Path.Combine(CountsPath, day.ToString(DayFormat, CultureInfo.InvariantCulture) + ".json"); + await WriteAsync(path, snapshot.CountsByDate.GetValueOrDefault(day).ToList(), cancellationToken); + } + + await WriteAsync(Path.Combine(RootPath, "meta.json"), new TrafficCacheMeta(snapshot.LastRefresh), cancellationToken); + } + + public virtual Task SaveGeometryAsync(TrafficSnapshot snapshot, CancellationToken cancellationToken) => + WriteAsync(Path.Combine(RootPath, GeometryFileName), snapshot.Geometry.Values.OrderBy(g => g.StationCode).ToList(), cancellationToken); + + private static async Task ReadAsync(string path, CancellationToken cancellationToken) + { + if (!File.Exists(path)) + { + return default; + } + + await using var stream = File.OpenRead(path); + return await JsonSerializer.DeserializeAsync(stream, JsonOptions, cancellationToken); + } + + private static async Task WriteAsync(string path, T value, CancellationToken cancellationToken) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var tempPath = path + ".tmp"; + await using (var stream = File.Create(tempPath)) + { + await JsonSerializer.SerializeAsync(stream, value, JsonOptions, cancellationToken); + } + + File.Move(tempPath, path, true); + } +} diff --git a/Schaad.OpenData.Traffic/Storage/TrafficDataStore.cs b/Schaad.OpenData.Traffic/Storage/TrafficDataStore.cs new file mode 100644 index 0000000..b08c8e8 --- /dev/null +++ b/Schaad.OpenData.Traffic/Storage/TrafficDataStore.cs @@ -0,0 +1,10 @@ +namespace Schaad.OpenData.Traffic.Storage; + +public sealed class TrafficDataStore +{ + private volatile TrafficSnapshot current = TrafficSnapshot.Empty; + + public TrafficSnapshot Current => current; + + public void Replace(TrafficSnapshot snapshot) => current = snapshot; +} diff --git a/Schaad.OpenData.Traffic/Storage/TrafficSnapshot.cs b/Schaad.OpenData.Traffic/Storage/TrafficSnapshot.cs new file mode 100644 index 0000000..1a6b85b --- /dev/null +++ b/Schaad.OpenData.Traffic/Storage/TrafficSnapshot.cs @@ -0,0 +1,58 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using Schaad.OpenData.Traffic.Models; + +namespace Schaad.OpenData.Traffic.Storage; + +public sealed class TrafficSnapshot +{ + public TrafficSnapshot( + IEnumerable stations, + IEnumerable counts, + IEnumerable geometry, + DateTimeOffset? lastRefresh) + { + Stations = stations.ToFrozenDictionary(s => s.Code); + CountsByDate = counts + .GroupBy(c => c.Date) + .ToFrozenDictionary(g => g.Key, g => g.ToImmutableArray()); + Geometry = geometry.ToFrozenDictionary(g => g.StationCode); + Dates = [.. CountsByDate.Keys.Order()]; + LastRefresh = lastRefresh; + } + + public static TrafficSnapshot Empty { get; } = new([], [], [], null); + + public FrozenDictionary Stations { get; } + + public FrozenDictionary> CountsByDate { get; } + + public FrozenDictionary Geometry { get; } + + public ImmutableArray Dates { get; } + + public DateTimeOffset? LastRefresh { get; } + + public TrafficSnapshot Merge(TrafficImport import, DateTimeOffset refreshedAt, out IReadOnlyList changedDays) + { + var importedDays = import.Counts.Select(c => c.Date).ToHashSet(); + changedDays = [.. importedDays.Order()]; + + var stations = Stations.Values + .Where(s => import.Stations.All(i => i.Code != s.Code)) + .Concat(import.Stations); + var counts = CountsByDate + .Where(kv => !importedDays.Contains(kv.Key)) + .SelectMany(kv => kv.Value) + .Concat(import.Counts); + + return new TrafficSnapshot(stations, counts, Geometry.Values, refreshedAt); + } + + public TrafficSnapshot WithGeometry(IEnumerable geometry) + { + var added = geometry.ToList(); + var merged = Geometry.Values.Where(g => added.All(a => a.StationCode != g.StationCode)).Concat(added); + return new TrafficSnapshot(Stations.Values, CountsByDate.Values.SelectMany(c => c), merged, LastRefresh); + } +} diff --git a/Schaad.OpenData.Traffic/TrafficOptions.cs b/Schaad.OpenData.Traffic/TrafficOptions.cs new file mode 100644 index 0000000..ac5e819 --- /dev/null +++ b/Schaad.OpenData.Traffic/TrafficOptions.cs @@ -0,0 +1,14 @@ +namespace Schaad.OpenData.Traffic; + +public sealed class TrafficOptions +{ + public const string SectionName = "Traffic"; + + public string DataPath { get; set; } = "data"; + + public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromHours(6); + + public string SourceUrl { get; set; } = "https://data.tg.ch/api/explore/v2.1/catalog/datasets/dbu-tba-1/exports/json"; + + public string SwisstopoBaseUrl { get; set; } = "https://api3.geo.admin.ch/rest/services/api/"; +} diff --git a/Schaad.OpenData.Traffic/TrafficRefreshService.cs b/Schaad.OpenData.Traffic/TrafficRefreshService.cs new file mode 100644 index 0000000..f012c50 --- /dev/null +++ b/Schaad.OpenData.Traffic/TrafficRefreshService.cs @@ -0,0 +1,44 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Schaad.OpenData.Traffic; + +public sealed class TrafficRefreshService( + TrafficRefresher refresher, + IOptions options, + ILogger logger) : BackgroundService +{ + private static readonly TimeSpan CheckInterval = TimeSpan.FromMinutes(15); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + await refresher.LoadCacheAsync(stoppingToken); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError(exception, "Could not load the traffic cache"); + } + + while (!stoppingToken.IsCancellationRequested) + { + try + { + if (refresher.IsRefreshDue(options.Value.RefreshInterval)) + { + await refresher.RefreshAsync(stoppingToken); + } + + await refresher.BuildMissingGeometryAsync(stoppingToken); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError(exception, "Traffic refresh failed"); + } + + await Task.Delay(CheckInterval, stoppingToken); + } + } +} diff --git a/Schaad.OpenData.Traffic/TrafficRefresher.cs b/Schaad.OpenData.Traffic/TrafficRefresher.cs new file mode 100644 index 0000000..2783a94 --- /dev/null +++ b/Schaad.OpenData.Traffic/TrafficRefresher.cs @@ -0,0 +1,73 @@ +using Microsoft.Extensions.Logging; +using Schaad.OpenData.Traffic.Geometry; +using Schaad.OpenData.Traffic.Models; +using Schaad.OpenData.Traffic.Source; +using Schaad.OpenData.Traffic.Storage; + +namespace Schaad.OpenData.Traffic; + +public class TrafficRefresher( + ThurgauTrafficClient client, + TrafficCacheStorage storage, + TrafficDataStore store, + StationGeometryService geometryService, + TimeProvider timeProvider, + ILogger logger) +{ + public async Task LoadCacheAsync(CancellationToken cancellationToken) + { + var snapshot = await storage.LoadAsync(cancellationToken); + store.Replace(snapshot); + logger.LogInformation("Loaded traffic cache with {Stations} stations and {Days} days", snapshot.Stations.Count, snapshot.Dates.Length); + } + + public bool IsRefreshDue(TimeSpan interval) => + store.Current.LastRefresh is not { } lastRefresh || timeProvider.GetUtcNow() - lastRefresh >= interval; + + public async Task RefreshAsync(CancellationToken cancellationToken) + { + var current = store.Current; + DateOnly? since = current.Dates.IsEmpty ? null : current.Dates[^1].AddDays(-1); + var import = await client.FetchAsync(since, cancellationToken); + var updated = current.Merge(import, timeProvider.GetUtcNow(), out var changedDays); + await storage.SaveAsync(updated, changedDays, cancellationToken); + store.Replace(updated); + logger.LogInformation("Imported {Rows} traffic rows for {Days} days since {Since}", import.Counts.Count, changedDays.Count, since); + } + + public async Task BuildMissingGeometryAsync(CancellationToken cancellationToken) + { + var snapshot = store.Current; + var missing = snapshot.Stations.Values.Where(s => !snapshot.Geometry.ContainsKey(s.Code)).ToList(); + if (missing.Count == 0) + { + return; + } + + var built = new List(); + foreach (var station in missing) + { + try + { + built.Add(await geometryService.BuildAsync(station, cancellationToken)); + } + catch (HttpRequestException exception) + { + logger.LogWarning(exception, "Could not build road geometry for station {Code}", station.Code); + } + } + + if (built.Count == 0) + { + return; + } + + var updated = store.Current.WithGeometry(built); + await storage.SaveGeometryAsync(updated, cancellationToken); + store.Replace(updated); + logger.LogInformation( + "Built road geometry for {Count} stations, {Straight} without matching road", + built.Count, + built.Count(g => !g.FollowsRoad)); + } +} diff --git a/Schaad.OpenData.Traffic/TrafficServiceCollectionExtensions.cs b/Schaad.OpenData.Traffic/TrafficServiceCollectionExtensions.cs new file mode 100644 index 0000000..7bd6006 --- /dev/null +++ b/Schaad.OpenData.Traffic/TrafficServiceCollectionExtensions.cs @@ -0,0 +1,38 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Traffic.Geometry; +using Schaad.OpenData.Traffic.Source; +using Schaad.OpenData.Traffic.Storage; + +namespace Schaad.OpenData.Traffic; + +public static class TrafficServiceCollectionExtensions +{ + private const string UserAgent = "OpenDataVisualizer/1.0"; + + public static IServiceCollection AddTraffic(this IServiceCollection services, IConfiguration configuration) + { + services.Configure(configuration.GetSection(TrafficOptions.SectionName)); + services.AddSingleton(TimeProvider.System); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(); + + services.AddHttpClient(client => + { + client.Timeout = TimeSpan.FromMinutes(5); + client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent); + }); + services.AddHttpClient((provider, client) => + { + client.BaseAddress = new Uri(provider.GetRequiredService>().Value.SwisstopoBaseUrl); + client.Timeout = TimeSpan.FromSeconds(30); + client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent); + }); + + return services; + } +} diff --git a/client/.prettierrc.json b/client/.prettierrc.json new file mode 100644 index 0000000..f9fdc87 --- /dev/null +++ b/client/.prettierrc.json @@ -0,0 +1,6 @@ +{ + "semi": true, + "singleQuote": true, + "printWidth": 100, + "trailingComma": "all" +} diff --git a/client/index.html b/client/index.html new file mode 100644 index 0000000..60386db --- /dev/null +++ b/client/index.html @@ -0,0 +1,13 @@ + + + + + + + OpenDataVisualizer – Verkehr Thurgau + + +
+ + + diff --git a/client/package-lock.json b/client/package-lock.json new file mode 100644 index 0000000..cfe44a9 --- /dev/null +++ b/client/package-lock.json @@ -0,0 +1,1839 @@ +{ + "name": "opendatavisualizer-client", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "opendatavisualizer-client", + "version": "1.0.0", + "dependencies": { + "@tanstack/react-query": "^5.51.23", + "chart.js": "^4.4.4", + "leaflet": "^1.9.4", + "react": "^18.3.1", + "react-chartjs-2": "^5.2.0", + "react-dom": "^18.3.1" + }, + "devDependencies": { + "@types/leaflet": "^1.9.12", + "@types/react": "^18.3.3", + "@types/react-dom": "^18.3.0", + "@vitejs/plugin-react": "^4.3.1", + "prettier": "^3.3.3", + "typescript": "^5.5.4", + "vite": "^6.4.3" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.13.tgz", + "integrity": "sha512-T5FRo+RzVHvGjWOuF1Ljc44b+NXAOazodHkGUHp4I3zCkQ4/sNVJm56h1S278LMR0bY5xBhztGziSbli8zObIw==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.13.tgz", + "integrity": "sha512-/U96wOz+SCoZ7Da/8kjDGltcNY280JPQcRNPK0Hk3PTbdpaiBDQImtC6JsbVwb1HGMr3usZQU2WsWVjhYNmRzw==", + "dev": true, + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.13" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.13.tgz", + "integrity": "sha512-fWegr+WsEsiMVW4KUNdIIzzMTZSzNiqhy0//6+2MRi2d5NFNsL/AYwBQW8eBnRbTBVRnDVzjaJEUqKaCWjMMdQ==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.13.tgz", + "integrity": "sha512-laoRpD/kO/iA4CDlgJbixHekg7oPvWALK0PQyK3Ob2I2njZRvVAD77RfWCIImtqWCq6KijoBoZK7bp/HlTWASQ==", + "dev": true, + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.11" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.13.tgz", + "integrity": "sha512-fJM50YYjlTiBhgdkGmC1tBpv+FMAyo4annf2X6Aks+0yRlaiVkYW/3f07xAfVVkYIoZ9fFZp+mEThUFnuybhkQ==", + "dev": true, + "dependencies": { + "@babel/types": "^7.29.11" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.13.tgz", + "integrity": "sha512-0ve0xMlFA73dgY1oyJRY6RoW+/bncdcOQqg6jjYcVfXBK90OdLXjm9R6lmRetdZVrPjXkKIoMVBqYFPjcAlZ4Q==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.11", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.11", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.11.tgz", + "integrity": "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==", + "dev": true, + "dependencies": { + "@babel/helper-string-parser": "^7.29.11", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@kurkle/color": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz", + "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==" + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.0.tgz", + "integrity": "sha512-Ta2n0ntLfzP0LqwwcXOIh2z0mnHjlxMS+h4Y9lo+w33Quyf9KFKEi9QZ2IKqeEBKr0qxNpXc/DQjz5KVIs8AEA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.0.tgz", + "integrity": "sha512-iFDtS0oMaBvKbtrRKXmRcBSsI0UaWL2bWpd62iHzb0A8RSPrVz47mUGE0CfrrD0c/7/7dUhNtoN3cc6aEUn1Ow==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.0.tgz", + "integrity": "sha512-OnYETr+cZYSbesBD1tCvUjrBUTkjSaOcewRUoIHqD0XI3yn5i9WpdFaE3LZwrMlq0yeJNU0N5sxfHK/fNVMqlQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.0.tgz", + "integrity": "sha512-2qavWZtFeon/6oMkjsBF3OH7ENKgRTW4xRTwmz9VJeNUYhmPitpR9Jd4sAAc2OZJryHs2neoovMTCYnNvhvANQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.0.tgz", + "integrity": "sha512-QpgJO+GwNQDPt6uYcFSjZTFVyHNIeumN2am7RISDR9Nf3e/h8sur9cIfplPGihZPUn+sTw9j3JErZIUkHg8+Pw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.0.tgz", + "integrity": "sha512-TERqEn6P9bp4lsTyoFjT3nLKV6G++76HhGb4k6dRGcs+jvhVcTGaS2zkeRdLLRjwKxpBtdCZe11kUQ2hNGgFSA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.0.tgz", + "integrity": "sha512-RBjDrqb7h5l6Xgdgz5eKYvbpnUkii/z5ejWuZmHJsXORi0X0tTtFzEEgJj2DX995kW18c6T9LGFn/deEAMXDcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.0.tgz", + "integrity": "sha512-HtLgXBqjF1Ampt9eJjzSmoGDvNb4LP8Y2aPXQZeQ5qhyExXLmoXJB9Jfm/nPi/8fJ3UFn4sZ7pQKyr8V+oTN8g==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.0.tgz", + "integrity": "sha512-q51xJyqjaqCNtDjYD7xNVwsPa2TcVfAIBeP6E20wicKZ6XYp8Taz9SUPYhIENojAQIAoV7cO3mUdMUgWYEAuhQ==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.0.tgz", + "integrity": "sha512-wejnVabl92oFC/o4sr/EEJuJZMHtMq4C+LBIPphN4EUiVHe9qvZNw+biqhVHpX2ggs1+Z3ugXGwJxT+qhyaaYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.0.tgz", + "integrity": "sha512-tyu+hrsCWHHqV6+2tligV/recJH+HVvNV2Sp4nS1C+MKQPkNXRovKIzyHy0V0xXjm6igCLgsT2vTky5CvWP37g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.0.tgz", + "integrity": "sha512-5gjJNglKDfgs3OmnGi/RVZQPhEfRoCIHxwSAP9ngmdnxreu0Vl9lI4gxmFBXOhKdftpS82xRdc/7Dp5/A1F0qg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.0.tgz", + "integrity": "sha512-2IBxTUds33rFYwOIEyf77wfW8WQThwiQQ1ofXSraZQG7PiIq7BnQBf/ge0qEI/Ny/2cSc7SKkGO/wUDqmYXqTg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.0.tgz", + "integrity": "sha512-mE/Pj2PPTZIVHkNNuHq+eYoU3td8LCm73zjrXoBWkNlnuULJS2l/fxwgGPpN4WUCNZgKZ1IXwrnnETPyOcWPmg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.0.tgz", + "integrity": "sha512-dYuykUkAiTv+RQdP3Ib47XcFiImkBWiRpTGSQWAMfZPQyoQYGe8Je4IUeZYNUQWIojmRCUnt5xsH4BbUb2uqSw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.0.tgz", + "integrity": "sha512-OnPDDFXLqJewY56T6ow8sA4wuzbqlliD7QJgkrx2KX+pWOpjI3usYXgB0pwK3nsgTF2odCw9IuJs0Uis/jy2qA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.0.tgz", + "integrity": "sha512-CqoQf06cK0brrRfDqH7Mt8G4MdteFGbjBdC61zEMaSVna6xo6QMUixa9bAkAD4a92g3ElPbQAkLMUzdf+Lk8dg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.0.tgz", + "integrity": "sha512-LPHNmE8GwiyELGLUTkqj4zsP1YEHzGdtwnKxAcdP/swsNxXsfxPtpe5nrD/KGxr136xPB+eWv2r/SGj9md0pnQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.0.tgz", + "integrity": "sha512-GDOmvgephpRCNyNGRQOZh0KD2gTyRVM1Bb1iOo759xeCUpCAoRCmJioOOSu2MwyWfNOocGd0V5I9vYLfteC6/A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.0.tgz", + "integrity": "sha512-HADRxkvl5eg3hbemCmv81UwTfdQy/CiSJDOabLE+p5tpm3OTjuRtzpLXy5zPfGY9FQD4Qv7qHptXmG/YjmNmyw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.0.tgz", + "integrity": "sha512-iERrpqu1VEfyX736HLKiXRbwGDkCV/iybARY/mn14KcI6oKhJGBx1e+bU+g+umTKghtiGSPaHkwwpII4/N3RjA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.0.tgz", + "integrity": "sha512-hBn57IqAbpXpyktckonwePTaFOQS6THph8ZnpRO3eZHY4LncuZGjSsseigBnKuSMKKpLnJJ7PemDvXEzniXC+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.0.tgz", + "integrity": "sha512-pJWb7mIw9Z25Hl3Q6nHFjl7AnczfOpm2gbOFYguSRv6TiH7DzsoAk/thymb/URSQu9OUEK7uaDMC5Xfm+7TAww==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.0.tgz", + "integrity": "sha512-pnrhmoyF2otH2Mezol14/ELUFGuRddOCz6+I+J0pq2Itnp4UxkjABQcXawCNMaKNsCRiuL90BtNzbEd0fHjpIg==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.0.tgz", + "integrity": "sha512-1dJ3U+ktdtaIdPaOZKwIX57+bKQk4iAjs5M1wQWLKRB6Wglp98qf8LUeuN4u6bGlIYouZKaySZJ5Qd4OalUMnA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.0.tgz", + "integrity": "sha512-e/NRJFl48wL5DFNSzQrvm4kaB5dzNNmqWjIJ6And2Sjuw4klO3w3TXMvCAEF1tHTrQQgpOD4QVkBE/92/yBGrQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tanstack/query-core": { + "version": "5.106.1", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.106.1.tgz", + "integrity": "sha512-erYv/UACddcdgjOL2ixmFdK6tO/AVBeUcTCOtX2N51yZpDQ2U7KJ+xgB/bCNfsF3uoCDTqGHEEbDiFsIO9YUmQ==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.106.1", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.106.1.tgz", + "integrity": "sha512-ORDvJG/DSfmlFL9lQ8GDkE0VjtQbLeRDY7BL8xjKkQFGLfjFGfNWNuteWgPqA2gPJgLLuWfQ7IX0FlsHCJriyg==", + "dependencies": { + "@tanstack/query-core": "5.106.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@types/react": "^18 || ^19", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true + }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "dev": true + }, + "node_modules/@types/leaflet": { + "version": "1.9.22", + "resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.22.tgz", + "integrity": "sha512-h3lhECYEKDasG7LFHu+GiHqAvsgLuQvlJvVZzJDGONo3sEL+wUOqSFLnwkZlK0qVxnxbuGFW8iBlJNYs5wgndA==", + "dev": true, + "dependencies": { + "@types/geojson": "*" + } + }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "devOptional": true + }, + "node_modules/@types/react": { + "version": "18.3.31", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz", + "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==", + "devOptional": true, + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.7", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz", + "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", + "dev": true, + "peerDependencies": { + "@types/react": "^18.0.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.35", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.35.tgz", + "integrity": "sha512-GNk8KX52CHqeNKGk8+7tZnQab/2k1t/BgrUHPKNdijzpEhF1saPQZHVKb6m5loSAxB39gyrTYw34Qf9CQ3u1qQ==", + "dev": true, + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001823", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001823.tgz", + "integrity": "sha512-TQ5s/djDjNk1axreUW+4rULH+BmdCMLiJkhaXnO5wqivG7tITkSUj4ItIdzqdZHKaXcHAV8dhH3JxOM7/7bwqw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ] + }, + "node_modules/chart.js": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.6.1.tgz", + "integrity": "sha512-hJyniucsFmq//EvXYvJ6c6mahPoI3kaxdjVH8awTaJ/fDNWeSqqqArixMJWkWNN6fcYvPU3HneSANFNYtRi61g==", + "dependencies": { + "@kurkle/color": "^0.3.0" + }, + "engines": { + "pnpm": ">=8" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.478", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.478.tgz", + "integrity": "sha512-pftG+ma5Lm8O6/p45bhYT6StBN5ziQymaRzmCZwFl8DwWHKPPD93FdOmP1aqftcepolQYvrcyTLa17kE8Yf+jg==", + "dev": true + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/leaflet": { + "version": "1.9.4", + "resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz", + "integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.63", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.63.tgz", + "integrity": "sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q==", + "dev": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prettier": { + "version": "3.9.10", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz", + "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==", + "dev": true, + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-chartjs-2": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/react-chartjs-2/-/react-chartjs-2-5.3.1.tgz", + "integrity": "sha512-h5IPXKg9EXpjoBzUfyWJvllMjG2mQ4EiuHQFhms/AjUm0XSZHhyRy2xVmLXHKrtcdrPO4mnGqRtYoD0vp95A0A==", + "peerDependencies": { + "chart.js": "^4.1.1", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.68.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.0.tgz", + "integrity": "sha512-BIHWnc1Qjdy+WLfOdcSd67sxO4iW6pTnhdZosg+7ywSaiMWxxzKldkkNpUJqeXYAiJzyB14P2cIjqC6tlb6xzw==", + "dev": true, + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.0", + "@rollup/rollup-android-arm64": "4.68.0", + "@rollup/rollup-android-x64": "4.68.0", + "@rollup/rollup-darwin-arm64": "4.68.0", + "@rollup/rollup-darwin-x64": "4.68.0", + "@rollup/rollup-freebsd-arm64": "4.68.0", + "@rollup/rollup-freebsd-x64": "4.68.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.0", + "@rollup/rollup-linux-arm-musleabihf": "4.68.0", + "@rollup/rollup-linux-arm64-gnu": "4.68.0", + "@rollup/rollup-linux-arm64-musl": "4.68.0", + "@rollup/rollup-linux-loong64-gnu": "4.68.0", + "@rollup/rollup-linux-loong64-musl": "4.68.0", + "@rollup/rollup-linux-ppc64-gnu": "4.68.0", + "@rollup/rollup-linux-ppc64-musl": "4.68.0", + "@rollup/rollup-linux-riscv64-gnu": "4.68.0", + "@rollup/rollup-linux-riscv64-musl": "4.68.0", + "@rollup/rollup-linux-s390x-gnu": "4.68.0", + "@rollup/rollup-linux-x64-gnu": "4.68.0", + "@rollup/rollup-linux-x64-musl": "4.68.0", + "@rollup/rollup-openbsd-x64": "4.68.0", + "@rollup/rollup-openharmony-arm64": "4.68.0", + "@rollup/rollup-win32-arm64-msvc": "4.68.0", + "@rollup/rollup-win32-ia32-msvc": "4.68.0", + "@rollup/rollup-win32-x64-gnu": "4.68.0", + "@rollup/rollup-win32-x64-msvc": "4.68.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "6.4.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.5.tgz", + "integrity": "sha512-4enwjFfi4IwtEh0w+jPzpLVOFQiPHmmzPxcHXQOyEur47o6u0jE573DmGpjA+7irXoMLYRZD5ZaFUEneS3abPg==", + "dev": true, + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true + } + } +} diff --git a/client/package.json b/client/package.json new file mode 100644 index 0000000..535c0ca --- /dev/null +++ b/client/package.json @@ -0,0 +1,30 @@ +{ + "name": "opendatavisualizer-client", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "typecheck": "tsc", + "format": "prettier --write src", + "preview": "vite preview" + }, + "dependencies": { + "@tanstack/react-query": "^5.51.23", + "chart.js": "^4.4.4", + "leaflet": "^1.9.4", + "react": "^18.3.1", + "react-chartjs-2": "^5.2.0", + "react-dom": "^18.3.1" + }, + "devDependencies": { + "@types/leaflet": "^1.9.12", + "@types/react": "^18.3.3", + "@types/react-dom": "^18.3.0", + "@vitejs/plugin-react": "^4.3.1", + "prettier": "^3.3.3", + "typescript": "^5.5.4", + "vite": "^6.4.3" + } +} diff --git a/client/public/favicon.svg b/client/public/favicon.svg new file mode 100644 index 0000000..c5af88a --- /dev/null +++ b/client/public/favicon.svg @@ -0,0 +1 @@ + diff --git a/client/src/App.tsx b/client/src/App.tsx new file mode 100644 index 0000000..8778ee7 --- /dev/null +++ b/client/src/App.tsx @@ -0,0 +1,174 @@ +import { keepPreviousData, useQuery } from '@tanstack/react-query'; +import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { fetchDay, fetchMeta, fetchStations } from './api/traffic'; +import { Legend } from './components/Legend'; +import { StationPanel } from './components/StationPanel'; +import { SPEEDS, TimeControls } from './components/TimeControls'; +import { TrafficMap } from './components/TrafficMap'; +import type { FlowAnimator } from './traffic/flowAnimator'; +import { formatNumber } from './traffic/format'; +import { sumCounts } from './traffic/vehicleClasses'; + +const MemoStationPanel = memo(StationPanel); + +const INITIAL_TIME = 7.5; + +export function App() { + const metaQuery = useQuery({ + queryKey: ['meta'], + queryFn: fetchMeta, + refetchInterval: 10 * 60_000, + }); + const stationsQuery = useQuery({ + queryKey: ['stations'], + queryFn: fetchStations, + refetchInterval: (query) => + query.state.data?.some((s) => s.directions.some((d) => d.path.length < 2)) ? 30_000 : false, + }); + + const dates = useMemo(() => metaQuery.data?.dates ?? [], [metaQuery.data]); + const [date, setDate] = useState(null); + const [time, setTime] = useState(INITIAL_TIME); + const [playing, setPlaying] = useState(false); + const [hoursPerSecond, setHoursPerSecond] = useState(SPEEDS[1].hoursPerSecond); + const [selectedCode, setSelectedCode] = useState(null); + const animatorRef = useRef(null); + const datesRef = useRef(dates); + datesRef.current = dates; + + useEffect(() => { + if (!date && dates.length > 0) { + setDate(dates[dates.length - 1]); + } + }, [date, dates]); + + const dayQuery = useQuery({ + queryKey: ['day', date], + queryFn: () => fetchDay(date!), + enabled: !!date, + placeholderData: keepPreviousData, + staleTime: 5 * 60_000, + }); + const day = dayQuery.data ?? null; + + const handleAnimatorReady = useCallback((animator: FlowAnimator) => { + animatorRef.current = animator; + animator.time = INITIAL_TIME; + animator.onTick = setTime; + animator.onDayEnd = () => + setDate((current) => { + const all = datesRef.current; + const index = current ? all.indexOf(current) : -1; + return all.length === 0 ? current : all[(index + 1) % all.length]; + }); + }, []); + + useEffect(() => { + if (animatorRef.current) { + animatorRef.current.playing = playing; + } + }, [playing]); + + useEffect(() => { + if (animatorRef.current) { + animatorRef.current.hoursPerSecond = hoursPerSecond; + } + }, [hoursPerSecond]); + + const handleTimeChange = useCallback((value: number) => { + if (animatorRef.current) { + animatorRef.current.time = value; + } + setTime(value); + }, []); + + const handleClose = useCallback(() => setSelectedCode(null), []); + + const hour = Math.min(23, Math.floor(time)); + const stations = useMemo(() => stationsQuery.data ?? [], [stationsQuery.data]); + const selectedStation = stations.find((s) => s.code === selectedCode) ?? null; + + const hourTotal = useMemo( + () => + day?.stations.reduce( + (sum, station) => + sum + station.directions.reduce((s, d) => s + sumCounts(d.hours[hour]), 0), + 0, + ) ?? 0, + [day, hour], + ); + + const error = metaQuery.error ?? stationsQuery.error ?? dayQuery.error; + + return ( +
+
+
+

OpenDataVisualizer

+ + Strassenverkehr Kanton Thurgau · stündliche Zählungen nach Fahrzeugklassen + +
+
+
+ {stations.length} + Zählstellen +
+
+ {formatNumber(hourTotal)} + Fahrzeuge in dieser Stunde +
+
+
+ +
+ + +
+ {date && ( + + )} + +
+ + {(metaQuery.isLoading || (metaQuery.data && dates.length === 0)) && ( +
+ Verkehrsdaten werden geladen… (erster Start lädt die Daten von data.tg.ch) +
+ )} + {error &&
Fehler beim Laden: {String(error.message)}
} +
+ + {selectedStation && ( + + )} + + +
+ ); +} diff --git a/client/src/api/traffic.ts b/client/src/api/traffic.ts new file mode 100644 index 0000000..dac0ecc --- /dev/null +++ b/client/src/api/traffic.ts @@ -0,0 +1,86 @@ +export type VehicleCounts = number[]; + +export interface TrafficMeta { + title: string; + publisher: string; + sourceUrl: string; + license: string; + vehicleClasses: string[]; + dates: string[]; + lastRefresh: string | null; +} + +export interface StationDirection { + name: string; + path: [number, number][]; +} + +export interface Station { + code: number; + name: string; + municipality: string; + address: string; + road: string; + lat: number; + lon: number; + followsRoad: boolean; + directions: StationDirection[]; +} + +export interface DirectionDay { + direction: string; + hours: (VehicleCounts | null)[]; +} + +export interface StationDay { + code: number; + directions: DirectionDay[]; +} + +export interface DayView { + date: string; + stations: StationDay[]; +} + +export interface HourlyTotal { + time: string; + total: number; +} + +export interface DailyTotal { + date: string; + total: number; +} + +export interface DirectionSummary { + direction: string; + hourly: HourlyTotal[]; + daily: DailyTotal[]; + weekdayProfile: number[]; + weekendProfile: number[]; +} + +export interface StationSummary { + code: number; + from: string; + to: string; + directions: DirectionSummary[]; + classTotals: VehicleCounts; +} + +async function getJson(url: string): Promise { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`${response.status} ${response.statusText}`); + } + return (await response.json()) as T; +} + +export const fetchMeta = () => getJson('/api/traffic/meta'); + +export const fetchStations = () => getJson('/api/traffic/stations'); + +export const fetchDay = (date: string) => getJson(`/api/traffic/days/${date}`); + +export const fetchStationSummary = (code: number) => + getJson(`/api/traffic/stations/${code}/summary`); diff --git a/client/src/components/Legend.tsx b/client/src/components/Legend.tsx new file mode 100644 index 0000000..288974d --- /dev/null +++ b/client/src/components/Legend.tsx @@ -0,0 +1,21 @@ +import { GROUP_ORDER, VEHICLE_GROUPS } from '../traffic/vehicleClasses'; + +export function Legend() { + return ( +
+ {GROUP_ORDER.map((group) => { + const style = VEHICLE_GROUPS[group]; + return ( + + + {style.label} + + ); + })} + Punktdichte ∝ Fahrzeuge pro Stunde · Rechtsverkehr +
+ ); +} diff --git a/client/src/components/StationPanel.tsx b/client/src/components/StationPanel.tsx new file mode 100644 index 0000000..9b8b689 --- /dev/null +++ b/client/src/components/StationPanel.tsx @@ -0,0 +1,290 @@ +import { useQuery } from '@tanstack/react-query'; +import { + BarElement, + CategoryScale, + Chart as ChartJS, + Filler, + Legend, + LinearScale, + LogarithmicScale, + LineElement, + PointElement, + Tooltip, + type ChartOptions, +} from 'chart.js'; +import { Bar, Line } from 'react-chartjs-2'; +import { fetchStationSummary, type DayView, type Station } from '../api/traffic'; +import { formatDate, formatNumber } from '../traffic/format'; +import { + DIRECTION_COLORS, + VEHICLE_CLASSES, + VEHICLE_GROUPS, + sumCounts, +} from '../traffic/vehicleClasses'; + +ChartJS.register( + CategoryScale, + LinearScale, + LogarithmicScale, + PointElement, + LineElement, + BarElement, + Filler, + Tooltip, + Legend, +); +ChartJS.defaults.font.family = 'system-ui, -apple-system, "Segoe UI", sans-serif'; +ChartJS.defaults.font.size = 11; +ChartJS.defaults.color = '#475569'; + +interface StationPanelProps { + station: Station; + day: DayView | null; + hour: number; + onClose: () => void; +} + +const HOUR_LABELS = Array.from({ length: 24 }, (_, h) => String(h).padStart(2, '0')); + +const baseLineOptions: ChartOptions<'line'> = { + responsive: true, + maintainAspectRatio: false, + animation: false, + interaction: { mode: 'index', intersect: false }, + plugins: { legend: { position: 'bottom', labels: { boxWidth: 12, boxHeight: 2 } } }, + elements: { point: { radius: 0, hoverRadius: 3 }, line: { borderWidth: 1.75, tension: 0.25 } }, + scales: { + x: { grid: { display: false }, ticks: { maxRotation: 0, autoSkipPadding: 16 } }, + y: { beginAtZero: true, grid: { color: '#e2e8f0' }, title: { display: true, text: 'Fz/h' } }, + }, +}; + +export function StationPanel({ station, day, hour, onClose }: StationPanelProps) { + const summaryQuery = useQuery({ + queryKey: ['station-summary', station.code], + queryFn: () => fetchStationSummary(station.code), + }); + const summary = summaryQuery.data; + + const stationDay = day?.stations.find((s) => s.code === station.code); + const hourIndex = Math.min(23, Math.max(0, hour)); + + const hourlyLabels = summary?.directions[0]?.hourly.map((h) => formatHourLabel(h.time)) ?? []; + const dailyLabels = + summary?.directions[0]?.daily.map((d) => formatDate(d.date, { year: undefined })) ?? []; + + return ( + + ); +} + +function formatHourLabel(time: string): string { + const date = new Date(time); + return `${date.toLocaleDateString('de-CH', { weekday: 'short', day: '2-digit', month: '2-digit' })} ${String(date.getHours()).padStart(2, '0')}:00`; +} diff --git a/client/src/components/TimeControls.tsx b/client/src/components/TimeControls.tsx new file mode 100644 index 0000000..a42ec03 --- /dev/null +++ b/client/src/components/TimeControls.tsx @@ -0,0 +1,99 @@ +import { formatClock, formatDate } from '../traffic/format'; + +export const SPEEDS = [ + { label: '1 h = 10 s', hoursPerSecond: 0.1 }, + { label: '1 h = 4 s', hoursPerSecond: 0.25 }, + { label: '1 h = 1 s', hoursPerSecond: 1 }, +]; + +interface TimeControlsProps { + dates: string[]; + date: string; + time: number; + playing: boolean; + hoursPerSecond: number; + onDateChange: (date: string) => void; + onTimeChange: (time: number) => void; + onPlayingChange: (playing: boolean) => void; + onSpeedChange: (hoursPerSecond: number) => void; +} + +export function TimeControls({ + dates, + date, + time, + playing, + hoursPerSecond, + onDateChange, + onTimeChange, + onPlayingChange, + onSpeedChange, +}: TimeControlsProps) { + const index = dates.indexOf(date); + + return ( +
+ + +
+ + + +
+ +
{formatClock(time)}
+ + onTimeChange(Number(e.target.value))} + aria-label="Uhrzeit" + /> + + +
+ ); +} diff --git a/client/src/components/TrafficMap.tsx b/client/src/components/TrafficMap.tsx new file mode 100644 index 0000000..ccb791b --- /dev/null +++ b/client/src/components/TrafficMap.tsx @@ -0,0 +1,192 @@ +import 'leaflet/dist/leaflet.css'; +import L from 'leaflet'; +import { useEffect, useRef } from 'react'; +import type { DayView, Station } from '../api/traffic'; +import { FlowAnimator } from '../traffic/flowAnimator'; +import { sumCounts } from '../traffic/vehicleClasses'; + +interface TrafficMapProps { + stations: Station[]; + day: DayView | null; + hour: number; + selectedCode: number | null; + onSelect: (code: number) => void; + onAnimatorReady: (animator: FlowAnimator) => void; +} + +const THURGAU_CENTER: L.LatLngTuple = [47.57, 9.1]; +const BASE_MAP_STORAGE_KEY = 'odv.baseMap'; +const ATTRIBUTION = + '© swisstopo · Daten: Kanton Thurgau'; +const BASE_MAPS = [ + { name: 'Grau', layer: 'ch.swisstopo.pixelkarte-grau', maxNativeZoom: 18 }, + { name: 'Farbe', layer: 'ch.swisstopo.pixelkarte-farbe', maxNativeZoom: 18 }, + { name: 'Luftbild', layer: 'ch.swisstopo.swissimage', maxNativeZoom: 19 }, +]; + +function createBaseLayers(): Record { + return Object.fromEntries( + BASE_MAPS.map((baseMap) => [ + baseMap.name, + L.tileLayer( + `https://wmts.geo.admin.ch/1.0.0/${baseMap.layer}/default/current/3857/{z}/{x}/{y}.jpeg`, + { maxZoom: 19, maxNativeZoom: baseMap.maxNativeZoom, attribution: ATTRIBUTION }, + ), + ]), + ); +} + +export function TrafficMap({ + stations, + day, + hour, + selectedCode, + onSelect, + onAnimatorReady, +}: TrafficMapProps) { + const containerRef = useRef(null); + const mapRef = useRef(null); + const animatorRef = useRef(null); + const roadsRef = useRef(null); + const markersRef = useRef>(new Map()); + const onSelectRef = useRef(onSelect); + onSelectRef.current = onSelect; + const fittedRef = useRef(false); + const dayRef = useRef(day); + dayRef.current = day; + + useEffect(() => { + if (!containerRef.current) { + return; + } + + const map = L.map(containerRef.current, { zoomSnap: 0.5 }).setView(THURGAU_CENTER, 10); + const baseLayers = createBaseLayers(); + const storedBaseMap = localStorage.getItem(BASE_MAP_STORAGE_KEY); + (baseLayers[storedBaseMap ?? ''] ?? baseLayers[BASE_MAPS[0].name]).addTo(map); + L.control.layers(baseLayers, undefined, { position: 'topright' }).addTo(map); + map.on('baselayerchange', (event: L.LayersControlEvent) => + localStorage.setItem(BASE_MAP_STORAGE_KEY, event.name), + ); + + const canvas = document.createElement('canvas'); + canvas.className = 'flow-canvas'; + map.getContainer().appendChild(canvas); + + roadsRef.current = L.layerGroup().addTo(map); + const animator = new FlowAnimator(map, canvas); + animator.start(); + + mapRef.current = map; + animatorRef.current = animator; + onAnimatorReady(animator); + + const resizeObserver = new ResizeObserver(() => map.invalidateSize()); + resizeObserver.observe(containerRef.current); + + return () => { + resizeObserver.disconnect(); + animator.dispose(); + map.remove(); + mapRef.current = null; + animatorRef.current = null; + markersRef.current.clear(); + }; + }, [onAnimatorReady]); + + useEffect(() => { + const map = mapRef.current; + const roads = roadsRef.current; + if (!map || !roads) { + return; + } + + roads.clearLayers(); + markersRef.current.forEach((marker) => marker.remove()); + markersRef.current.clear(); + + for (const station of stations) { + for (const direction of station.directions.slice(0, 1)) { + if (direction.path.length >= 2) { + L.polyline(direction.path, { + color: '#334155', + weight: 5, + opacity: 0.18, + interactive: false, + }).addTo(roads); + } + } + + const marker = L.circleMarker([station.lat, station.lon], { + radius: 5, + color: '#0f172a', + weight: 1.5, + fillColor: '#ffffff', + fillOpacity: 0.85, + }) + .on('click', () => { + onSelectRef.current(station.code); + if (map.getZoom() < 14) { + map.flyTo([station.lat, station.lon], 15, { duration: 0.8 }); + } + }) + .addTo(map); + markersRef.current.set(station.code, marker); + } + + animatorRef.current?.setStations(stations); + animatorRef.current?.setDay(dayRef.current); + + if (stations.length > 0 && !fittedRef.current) { + fittedRef.current = true; + map.fitBounds(L.latLngBounds(stations.map((s) => [s.lat, s.lon] as L.LatLngTuple)), { + padding: [40, 40], + }); + } + }, [stations]); + + useEffect(() => { + animatorRef.current?.setDay(day); + }, [day]); + + useEffect(() => { + const hourIndex = Math.min(23, Math.max(0, hour)); + const dayByStation = new Map(day?.stations.map((s) => [s.code, s]) ?? []); + + for (const station of stations) { + const marker = markersRef.current.get(station.code); + if (!marker) { + continue; + } + + const stationDay = dayByStation.get(station.code); + const perDirection = station.directions.map((direction) => { + const hours = stationDay?.directions.find((d) => d.direction === direction.name)?.hours; + return { name: direction.name, total: sumCounts(hours?.[hourIndex]) }; + }); + const total = perDirection.reduce((sum, d) => sum + d.total, 0); + const selected = station.code === selectedCode; + + marker.setRadius(3 + Math.sqrt(total) / 6); + marker.setStyle({ + color: selected ? '#dc2626' : '#0f172a', + weight: selected ? 3 : 1.5, + fillColor: selected ? '#fee2e2' : '#ffffff', + }); + marker.bindTooltip( + `${escapeHtml(station.name)}
` + + `${escapeHtml(station.road)} · ${String(hourIndex).padStart(2, '0')}:00–${String(hourIndex + 1).padStart(2, '0')}:00
` + + perDirection + .map((d) => `${escapeHtml(d.name)}: ${d.total} Fz/h`) + .join('
'), + { direction: 'top', offset: [0, -6] }, + ); + } + }, [stations, day, hour, selectedCode]); + + return
; +} + +function escapeHtml(value: string): string { + return value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); +} diff --git a/client/src/main.tsx b/client/src/main.tsx new file mode 100644 index 0000000..eb39b90 --- /dev/null +++ b/client/src/main.tsx @@ -0,0 +1,17 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { App } from './App'; +import './styles.css'; + +const queryClient = new QueryClient({ + defaultOptions: { queries: { refetchOnWindowFocus: false, retry: 1 } }, +}); + +createRoot(document.getElementById('root')!).render( + + + + + , +); diff --git a/client/src/styles.css b/client/src/styles.css new file mode 100644 index 0000000..099ddbe --- /dev/null +++ b/client/src/styles.css @@ -0,0 +1,360 @@ +:root { + --bg: #f8fafc; + --surface: #ffffff; + --border: #e2e8f0; + --text: #0f172a; + --muted: #64748b; + --accent: #2563eb; + --panel-width: 440px; + font-family: + system-ui, + -apple-system, + 'Segoe UI', + sans-serif; + color: var(--text); + background: var(--bg); +} + +* { + box-sizing: border-box; +} + +html, +body, +#root { + height: 100%; + margin: 0; +} + +.app { + display: grid; + grid-template-columns: 1fr; + grid-template-rows: auto 1fr auto; + grid-template-areas: + 'header' + 'map' + 'footer'; + height: 100%; +} + +.app.with-panel { + grid-template-columns: 1fr var(--panel-width); + grid-template-areas: + 'header header' + 'map panel' + 'footer footer'; +} + +.app-header { + grid-area: header; + display: flex; + justify-content: space-between; + align-items: center; + gap: 16px; + padding: 10px 18px; + background: var(--surface); + border-bottom: 1px solid var(--border); +} + +.title h1 { + margin: 0; + font-size: 18px; + letter-spacing: -0.01em; +} + +.subtitle { + color: var(--muted); + font-size: 13px; +} + +.stats { + display: flex; + gap: 24px; +} + +.stats > div { + display: flex; + flex-direction: column; + align-items: flex-end; +} + +.stat-value { + font-size: 20px; + font-weight: 600; + font-variant-numeric: tabular-nums; +} + +.stat-label { + font-size: 11px; + color: var(--muted); +} + +.map-area { + grid-area: map; + position: relative; + min-height: 0; +} + +.traffic-map { + position: absolute; + inset: 0; +} + +.flow-canvas { + position: absolute; + top: 0; + left: 0; + z-index: 450; + pointer-events: none; + transition: opacity 0.15s; +} + +.overlay-bottom { + position: absolute; + left: 12px; + right: 12px; + bottom: 22px; + z-index: 800; + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + pointer-events: none; +} + +.overlay-bottom > * { + pointer-events: auto; +} + +.time-controls, +.legend { + background: rgba(255, 255, 255, 0.94); + border: 1px solid var(--border); + border-radius: 10px; + box-shadow: 0 4px 16px rgba(15, 23, 42, 0.12); +} + +.time-controls { + display: flex; + align-items: center; + gap: 12px; + padding: 8px 12px; + width: min(820px, 100%); +} + +.play-button { + width: 38px; + height: 38px; + border-radius: 50%; + border: none; + background: var(--accent); + color: white; + font-size: 14px; + cursor: pointer; + flex: none; +} + +.date-picker { + display: flex; + align-items: center; + gap: 2px; +} + +.date-picker button { + border: 1px solid var(--border); + background: white; + border-radius: 6px; + width: 26px; + height: 30px; + cursor: pointer; +} + +.date-picker button:disabled { + opacity: 0.4; + cursor: default; +} + +select { + height: 30px; + border: 1px solid var(--border); + border-radius: 6px; + background: white; + padding: 0 6px; + font: inherit; + font-size: 13px; +} + +.clock { + font-size: 20px; + font-weight: 600; + font-variant-numeric: tabular-nums; + width: 60px; + text-align: center; +} + +.time-slider { + flex: 1; + accent-color: var(--accent); +} + +.legend { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 14px; + padding: 5px 12px; + font-size: 12px; +} + +.legend-item { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.legend-dot { + display: inline-block; + border-radius: 50%; +} + +.legend-dot.small { + width: 8px; + height: 8px; + margin-right: 6px; +} + +.legend-note { + color: var(--muted); +} + +.notice { + position: absolute; + top: 12px; + left: 50%; + transform: translateX(-50%); + z-index: 800; + background: white; + border: 1px solid var(--border); + border-radius: 8px; + padding: 8px 14px; + font-size: 13px; + box-shadow: 0 4px 16px rgba(15, 23, 42, 0.12); +} + +.error { + color: #b91c1c; +} + +.muted { + color: var(--muted); +} + +.station-panel { + grid-area: panel; + overflow-y: auto; + background: var(--surface); + border-left: 1px solid var(--border); + padding: 14px 16px 24px; +} + +.station-panel-header { + display: flex; + justify-content: space-between; + gap: 8px; +} + +.station-panel h2 { + margin: 0 0 4px; + font-size: 16px; +} + +.station-panel-header p { + margin: 0; + color: var(--muted); + font-size: 12px; +} + +.close-button { + border: none; + background: none; + font-size: 24px; + line-height: 1; + cursor: pointer; + color: var(--muted); +} + +.station-panel section { + margin-top: 18px; +} + +.station-panel h3 { + font-size: 13px; + margin: 0 0 8px; + color: #334155; +} + +.class-table { + width: 100%; + border-collapse: collapse; + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +.class-table th, +.class-table td { + padding: 3px 4px; + border-bottom: 1px solid #f1f5f9; + text-align: right; +} + +.class-table th:first-child, +.class-table td:first-child { + text-align: left; +} + +.class-table .total-row td { + font-weight: 600; + border-top: 1px solid var(--border); +} + +.chart { + position: relative; + height: 200px; +} + +.chart-tall { + height: 230px; +} + +.app-footer { + grid-area: footer; + font-size: 11px; + color: var(--muted); + padding: 4px 18px; + border-top: 1px solid var(--border); + background: var(--surface); +} + +.app-footer a { + color: inherit; +} + +@media (max-width: 900px) { + .app.with-panel { + grid-template-columns: 1fr; + grid-template-rows: auto 1fr 45% auto; + grid-template-areas: + 'header' + 'map' + 'panel' + 'footer'; + } + + .stats { + display: none; + } + + .time-controls { + flex-wrap: wrap; + } +} diff --git a/client/src/traffic/flowAnimator.ts b/client/src/traffic/flowAnimator.ts new file mode 100644 index 0000000..f82b9a5 --- /dev/null +++ b/client/src/traffic/flowAnimator.ts @@ -0,0 +1,294 @@ +import L from 'leaflet'; +import type { DayView, Station } from '../api/traffic'; +import { VEHICLE_CLASSES, VEHICLE_GROUPS, type VehicleGroup } from './vehicleClasses'; + +const DOTS_PER_SECOND_PER_VEHICLE_HOUR = 1 / 80; +const TRAVEL_SECONDS = 4.5; +const MAX_PARTICLES_PER_LANE = 220; +const FADE_PORTION = 0.12; +const GROUP_SPEED: Record = { + car: 1, + motorcycle: 1.1, + van: 0.97, + truck: 0.82, + bus: 0.85, +}; + +interface Lane { + key: string; + latLngs: L.LatLng[]; + points: L.Point[]; + cumulative: number[]; + length: number; + spawnDebt: number; + hours: (number[] | null)[]; +} + +interface Particle { + lane: Lane; + progress: number; + speed: number; + group: VehicleGroup; +} + +export function laneKey(stationCode: number, direction: string): string { + return `${stationCode}|${direction}`; +} + +export class FlowAnimator { + time = 8; + playing = false; + hoursPerSecond = 0.25; + onTick: ((time: number) => void) | null = null; + onDayEnd: (() => void) | null = null; + + private lanes: Lane[] = []; + private particles: Particle[] = []; + private frame = 0; + private lastFrame = 0; + private lastTick = 0; + private projectionDirty = true; + private zooming = false; + + constructor( + private readonly map: L.Map, + private readonly canvas: HTMLCanvasElement, + ) { + map.on('move resize viewreset', this.markDirty); + map.on('zoomstart', this.handleZoomStart); + map.on('zoomend', this.handleZoomEnd); + } + + setStations(stations: Station[]) { + this.lanes = stations.flatMap((station) => + station.directions + .filter((direction) => direction.path.length >= 2) + .map((direction) => ({ + key: laneKey(station.code, direction.name), + latLngs: direction.path.map(([lat, lon]) => L.latLng(lat, lon)), + points: [], + cumulative: [], + length: 0, + spawnDebt: 0, + hours: [], + })), + ); + this.particles = []; + this.projectionDirty = true; + } + + setDay(day: DayView | null) { + const hoursByLane = new Map(); + for (const station of day?.stations ?? []) { + for (const direction of station.directions) { + hoursByLane.set(laneKey(station.code, direction.direction), direction.hours); + } + } + for (const lane of this.lanes) { + lane.hours = hoursByLane.get(lane.key) ?? []; + } + } + + countsAt(hours: (number[] | null)[], time: number): number[] | null { + const hour = Math.min(23, Math.floor(time)); + const current = hours[hour] ?? null; + const next = hours[Math.min(23, hour + 1)] ?? current; + if (!current) { + return null; + } + const fraction = Math.min(1, Math.max(0, time - hour)); + return current.map((value, i) => value + ((next?.[i] ?? value) - value) * fraction); + } + + start() { + if (this.frame === 0) { + this.lastFrame = performance.now(); + this.frame = requestAnimationFrame(this.step); + } + } + + dispose() { + cancelAnimationFrame(this.frame); + this.frame = 0; + this.map.off('move resize viewreset', this.markDirty); + this.map.off('zoomstart', this.handleZoomStart); + this.map.off('zoomend', this.handleZoomEnd); + } + + private markDirty = () => { + this.projectionDirty = true; + }; + + private handleZoomStart = () => { + this.zooming = true; + this.canvas.style.opacity = '0'; + }; + + private handleZoomEnd = () => { + this.zooming = false; + this.projectionDirty = true; + this.canvas.style.opacity = '1'; + }; + + private step = (now: number) => { + const dt = Math.min(0.1, (now - this.lastFrame) / 1000); + this.lastFrame = now; + + if (this.playing) { + this.time += dt * this.hoursPerSecond; + if (this.time >= 24) { + this.time = 0; + this.onDayEnd?.(); + } + } + + if (this.onTick && now - this.lastTick > 100) { + this.lastTick = now; + this.onTick(this.time); + } + + this.spawn(dt); + this.advance(dt); + if (!this.zooming) { + this.draw(); + } + + this.frame = requestAnimationFrame(this.step); + }; + + private spawn(dt: number) { + for (const lane of this.lanes) { + const counts = this.countsAt(lane.hours, this.time); + const total = counts ? counts.reduce((sum, value) => sum + value, 0) : 0; + if (total <= 0) { + lane.spawnDebt = 0; + continue; + } + + lane.spawnDebt += total * DOTS_PER_SECOND_PER_VEHICLE_HOUR * dt; + while (lane.spawnDebt >= 1) { + lane.spawnDebt -= 1; + if (this.particles.length > this.lanes.length * MAX_PARTICLES_PER_LANE) { + continue; + } + const group = pickGroup(counts!, total); + this.particles.push({ + lane, + progress: 0, + speed: (GROUP_SPEED[group] * (0.88 + Math.random() * 0.24)) / TRAVEL_SECONDS, + group, + }); + } + } + } + + private advance(dt: number) { + let write = 0; + for (const particle of this.particles) { + particle.progress += particle.speed * dt; + if (particle.progress < 1) { + this.particles[write++] = particle; + } + } + this.particles.length = write; + } + + private project() { + const size = this.map.getSize(); + const ratio = window.devicePixelRatio || 1; + if (this.canvas.width !== size.x * ratio || this.canvas.height !== size.y * ratio) { + this.canvas.width = size.x * ratio; + this.canvas.height = size.y * ratio; + this.canvas.style.width = `${size.x}px`; + this.canvas.style.height = `${size.y}px`; + } + + for (const lane of this.lanes) { + lane.points = lane.latLngs.map((latLng) => this.map.latLngToContainerPoint(latLng)); + lane.cumulative = [0]; + for (let i = 1; i < lane.points.length; i++) { + lane.cumulative.push( + lane.cumulative[i - 1] + lane.points[i].distanceTo(lane.points[i - 1]), + ); + } + lane.length = lane.cumulative[lane.cumulative.length - 1]; + } + this.projectionDirty = false; + } + + private draw() { + if (this.projectionDirty) { + this.project(); + } + + const context = this.canvas.getContext('2d'); + if (!context) { + return; + } + + const ratio = window.devicePixelRatio || 1; + const zoom = this.map.getZoom(); + const scale = Math.max(0.55, Math.min(1.6, (zoom - 9) / 5)); + const laneOffset = Math.max(1.5, Math.min(7, (zoom - 10) * 1.3)); + + context.setTransform(ratio, 0, 0, ratio, 0, 0); + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + for (const particle of this.particles) { + const lane = particle.lane; + if (lane.length < 1) { + continue; + } + const position = pointAlong(lane, particle.progress * lane.length, laneOffset); + if (!position) { + continue; + } + + const style = VEHICLE_GROUPS[particle.group]; + context.globalAlpha = Math.min( + 1, + particle.progress / FADE_PORTION, + (1 - particle.progress) / FADE_PORTION, + ); + context.fillStyle = style.color; + context.beginPath(); + context.arc(position.x, position.y, style.radius * scale, 0, Math.PI * 2); + context.fill(); + } + context.globalAlpha = 1; + } +} + +function pickGroup(counts: number[], total: number): VehicleGroup { + let threshold = Math.random() * total; + for (let i = 0; i < counts.length; i++) { + threshold -= counts[i]; + if (threshold <= 0) { + return VEHICLE_CLASSES[i].group; + } + } + return 'car'; +} + +function pointAlong(lane: Lane, distance: number, offset: number): { x: number; y: number } | null { + const { points, cumulative } = lane; + let index = 1; + while (index < cumulative.length - 1 && cumulative[index] < distance) { + index++; + } + + const a = points[index - 1]; + const b = points[index]; + const segmentLength = cumulative[index] - cumulative[index - 1]; + if (!a || !b || segmentLength <= 0) { + return null; + } + + const t = (distance - cumulative[index - 1]) / segmentLength; + const dx = (b.x - a.x) / segmentLength; + const dy = (b.y - a.y) / segmentLength; + return { + x: a.x + (b.x - a.x) * t - dy * offset, + y: a.y + (b.y - a.y) * t + dx * offset, + }; +} diff --git a/client/src/traffic/format.ts b/client/src/traffic/format.ts new file mode 100644 index 0000000..4b75ba3 --- /dev/null +++ b/client/src/traffic/format.ts @@ -0,0 +1,20 @@ +export function formatDate(date: string, options: Intl.DateTimeFormatOptions = {}): string { + return new Date(`${date}T00:00:00`).toLocaleDateString('de-CH', { + weekday: 'short', + day: '2-digit', + month: '2-digit', + year: 'numeric', + ...options, + }); +} + +export function formatClock(time: number): string { + const totalMinutes = Math.min(24 * 60 - 1, Math.floor(time * 60)); + const hours = Math.floor(totalMinutes / 60); + const minutes = totalMinutes % 60; + return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`; +} + +export function formatNumber(value: number): string { + return Math.round(value).toLocaleString('de-CH'); +} diff --git a/client/src/traffic/vehicleClasses.ts b/client/src/traffic/vehicleClasses.ts new file mode 100644 index 0000000..61a3d15 --- /dev/null +++ b/client/src/traffic/vehicleClasses.ts @@ -0,0 +1,41 @@ +export type VehicleGroup = 'car' | 'motorcycle' | 'van' | 'truck' | 'bus'; + +export interface VehicleClassInfo { + label: string; + group: VehicleGroup; +} + +export const VEHICLE_CLASSES: VehicleClassInfo[] = [ + { label: 'Bus/Car', group: 'bus' }, + { label: 'Motorrad', group: 'motorcycle' }, + { label: 'Personenwagen', group: 'car' }, + { label: 'PW mit Anhänger', group: 'car' }, + { label: 'Lieferwagen', group: 'van' }, + { label: 'Lieferwagen mit Anhänger', group: 'van' }, + { label: 'Lieferwagen mit Auflieger', group: 'van' }, + { label: 'Lastwagen', group: 'truck' }, + { label: 'Lastenzug', group: 'truck' }, + { label: 'Sattelzug', group: 'truck' }, +]; + +export interface VehicleGroupStyle { + label: string; + color: string; + radius: number; +} + +export const VEHICLE_GROUPS: Record = { + car: { label: 'Personenwagen', color: '#2563eb', radius: 2.6 }, + motorcycle: { label: 'Motorräder', color: '#0d9488', radius: 2 }, + van: { label: 'Lieferwagen', color: '#16a34a', radius: 3 }, + truck: { label: 'Lastwagen', color: '#ea580c', radius: 4 }, + bus: { label: 'Busse', color: '#9333ea', radius: 4 }, +}; + +export const GROUP_ORDER: VehicleGroup[] = ['car', 'van', 'truck', 'bus', 'motorcycle']; + +export const DIRECTION_COLORS = ['#2563eb', '#ea580c']; + +export function sumCounts(counts: number[] | null | undefined): number { + return counts ? counts.reduce((sum, value) => sum + value, 0) : 0; +} diff --git a/client/tsconfig.json b/client/tsconfig.json new file mode 100644 index 0000000..83b5c91 --- /dev/null +++ b/client/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true + }, + "include": ["src"] +} diff --git a/client/vite.config.ts b/client/vite.config.ts new file mode 100644 index 0000000..a0e21ee --- /dev/null +++ b/client/vite.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; + +export default defineConfig({ + plugins: [react()], + server: { + port: 5173, + proxy: { + '/api': 'http://localhost:5080', + }, + }, + build: { + outDir: '../Schaad.OpenData.Server/wwwroot', + emptyOutDir: true, + }, +}); diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..b68604b --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,15 @@ +services: + opendatavisualizer: + build: . + image: opendatavisualizer:latest + container_name: opendatavisualizer + restart: unless-stopped + ports: + - "${HOST_PORT:-8080}:8080" + environment: + Traffic__RefreshInterval: "06:00:00" + volumes: + - opendatavisualizer-data:/app/data + +volumes: + opendatavisualizer-data: -- 2.39.5 From 8de869b02394dce9caba56de39afc8835d242d9a Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Fri, 6 Nov 2026 20:50:48 +0100 Subject: [PATCH 2/3] Fix roundabout arm geometry for untargetable directions Stations like "WEINFELDEN Kreisel West - Umfahrung" have directions such as "zur Umfahrung" or "von Egelseestrasse" that cannot be geocoded, so their dots were drawn on a nearby side road or around the roundabout ring. - Derive the roundabout centre from all stations sharing the name before " - " and point each arm outward from it - Prefer road segments named like the station's address when following an arm; reject arms that don't get away from the centre - Parse "zur", "zum", "Richtung" and "vom" direction prefixes - Treat only swissTLM3D object kinds 12-19 as non-roads; kind 20 is a regular road (e.g. Dunantstrasse in Weinfelden) - Bump the geometry cache to v7 so all stations are rebuilt Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 8 +-- .../DirectionTargetTestShould.cs | 6 ++ .../StationGeometryServiceTestShould.cs | 60 ++++++++++++++++++- .../SwisstopoClientTestShould.cs | 8 ++- .../Geometry/DirectionTarget.cs | 17 ++++-- .../Geometry/RoadPathBuilder.cs | 39 ++++++++---- .../Geometry/RoadSegment.cs | 2 +- .../Geometry/StationGeometryService.cs | 44 ++++++++++++-- .../Geometry/SwisstopoClient.cs | 11 +++- .../Storage/TrafficCacheStorage.cs | 2 +- Schaad.OpenData.Traffic/TrafficRefresher.cs | 5 +- 11 files changed, 165 insertions(+), 37 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index bfa245f..bcecc55 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,11 +56,11 @@ The cache accumulates history beyond the source's two-week window; refreshes onl The source has one point per station and directions as text (`nach X`, `von X`, or just `X`). `StationGeometryService` turns that into a road polyline per direction, oriented in driving direction: -1. `SwisstopoClient.GetRoadSegmentsAsync` loads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200). `verkehrsbedeutung != 999998` marks main roads, `objektart <= 11` drivable roads (higher values are paths and lane markings). +1. `SwisstopoClient.GetRoadSegmentsAsync` loads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200) with their street name. `verkehrsbedeutung != 999998` marks main roads; `objektart` 12–19 are paths and lane markings (15/16 seen in practice), everything else is a road — note that 20 is a regular road type. 2. `RoadPathBuilder.BuildRoadPath` snaps to a main road within 60 m (else the nearest drivable road), stitches connected segments (≤ 60° turn, penalty for changing road class) and trims to ±300 m. -3. Stations named `… Kreisel …` sit on a roundabout arm: `BuildArmPath` follows every road segment within 80 m outward (600 m) and keeps the one that gets furthest toward the target town (a roundabout ring loops back and loses); it falls back to `BuildRoadPath`. -4. `SwisstopoClient.FindPlaceAsync` geocodes the target town (SearchServer, municipalities + gazetteer, label must contain the name with ä→ae etc., nearest candidate wins — "Landquart" is also a place in Arbon). Names with `/` are split, since the SearchServer returns 503 for slashes. -5. `RoadPathBuilder.Orient` points each direction toward (`nach`) or away from (`von`) its target; the two directions of a station are always opposite. +3. Stations named `… Kreisel …` sit on a roundabout arm. The roundabout centre is the average position of all stations sharing the name part before ` - ` (e.g. the four `WEINFELDEN Kreisel West` stations), and the arm target is a point 3 km outward from that centre through the station (`StationGeometryService.OutwardTarget`), so no geocoding is needed. `BuildArmPath` follows every segment within 80 m outward for 600 m, preferring segments named like the station's address (the arm's street), and keeps the arm that gets furthest outward; a ring loops back and is rejected. A roundabout with a single station falls back to the geocoded target. +4. Otherwise `SwisstopoClient.FindPlaceAsync` geocodes the target town (SearchServer, municipalities + gazetteer, label must contain the name with ä→ae etc., nearest candidate wins — "Landquart" is also a place in Arbon). Names with `/` are split, since the SearchServer returns 503 for slashes. Directions can be `nach`/`zur`/`zum`/`Richtung X` (toward) or `von`/`vom X` (from); targets like `Umfahrung`, `Zentrum` or street names cannot be geocoded. +5. `RoadPathBuilder.Orient` points each direction toward or away from its target; the two directions of a station are always opposite. When the geometry algorithm changes, bump `GeometryFileName` in `TrafficCacheStorage` so all stations are rebuilt. diff --git a/Schaad.OpenData.Tests/DirectionTargetTestShould.cs b/Schaad.OpenData.Tests/DirectionTargetTestShould.cs index b2d9891..5f17af9 100644 --- a/Schaad.OpenData.Tests/DirectionTargetTestShould.cs +++ b/Schaad.OpenData.Tests/DirectionTargetTestShould.cs @@ -16,6 +16,12 @@ public class DirectionTargetTestShould DirectionTarget.Parse("von Frauenfeld").ShouldBe(new DirectionTarget("Frauenfeld", false)); } + [Fact] + public void ParseDestinationWhenDirectionStartsWithZur() + { + DirectionTarget.Parse("zur Umfahrung").ShouldBe(new DirectionTarget("Umfahrung", true)); + } + [Fact] public void TreatPlainNameAsDestinationWhenDirectionHasNoPrefix() { diff --git a/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs b/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs index c7ce702..b9a8efe 100644 --- a/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs +++ b/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs @@ -21,18 +21,74 @@ public class StationGeometryServiceTestShould swisstopoClient.FindPlaceAsync("Wilen", Arg.Any(), Arg.Any()).Returns((GeoPoint?)null); swisstopoClient.FindPlaceAsync("Busswil", Arg.Any(), Arg.Any()).Returns(TestData.Meters(0, 2000)); - var geometry = await service.BuildAsync(TestData.Station(413, "Wilen/Busswil", "Gloten"), CancellationToken.None); + var geometry = await service.BuildAsync(TestData.Station(413, "Wilen/Busswil", "Gloten"), [], CancellationToken.None); await swisstopoClient.DidNotReceive().FindPlaceAsync("Wilen/Busswil", Arg.Any(), Arg.Any()); geometry.Directions[0].Path[^1].Lat.ShouldBeGreaterThan(TestData.Origin.Lat); } + private static Station Arm(int code, string name, (double East, double North) offset, string address, params string[] directions) => + TestData.Station(code, directions) with + { + Name = name, + Address = address, + Location = TestData.Meters(offset.East, offset.North), + }; + + private static Station[] KreiselWest() => + [ + Arm(1, "WEINFELDEN Kreisel West - Weinfelden", (30, 0), "Frauenfelderstrasse", "nach Weinfelden", "von Weinfelden"), + Arm(2, "WEINFELDEN Kreisel West - Umfahrung", (0, -30), "Dunantstrasse", "von Umfahrung", "zur Umfahrung"), + Arm(3, "WEINFELDEN Kreisel West - Märstetten", (-30, 0), "Frauenfelderstrasse", "nach Maerstetten", "von Maerstetten"), + Arm(4, "WEINFELDEN Kreisel West - Egelseestrasse", (0, 30), "Egelseestrasse", "von Egelseestrasse", "zur Egelseestrasse"), + ]; + + [Fact] + public void PointAwayFromRoundaboutCenterWhenComputingOutwardTarget() + { + var stations = KreiselWest(); + + var target = StationGeometryService.OutwardTarget(stations[1], stations)!.Value; + + target.Lat.ShouldBeLessThan(TestData.Meters(0, -2900).Lat); + target.Lon.ShouldBe(TestData.Origin.Lon, 1e-6); + } + + [Fact] + public void ReturnNoOutwardTargetWhenRoundaboutHasSingleStation() + { + var station = KreiselWest()[0]; + + StationGeometryService.OutwardTarget(station, [station]).ShouldBeNull(); + } + + [Fact] + public async Task FollowArmNamedLikeStationAddressWhenTargetIsNotAPlace() + { + var stations = KreiselWest(); + swisstopoClient.GetRoadSegmentsAsync(default, default, default).ReturnsForAnyArgs( + [ + new RoadSegment([TestData.Meters(0, -28), TestData.Meters(-80, 60)], true, true, null), + new RoadSegment([TestData.Meters(0, -10), TestData.Meters(0, -200)], true, true, "Dunantstrasse"), + new RoadSegment([TestData.Meters(0, -200), TestData.Meters(0, -700)], true, true, "Dunantstrasse"), + ]); + + var geometry = await service.BuildAsync(stations[1], stations, CancellationToken.None); + + await swisstopoClient.DidNotReceiveWithAnyArgs().FindPlaceAsync(default!, default, default); + var outward = geometry.Directions.Single(d => d.Direction == "zur Umfahrung").Path; + var inward = geometry.Directions.Single(d => d.Direction == "von Umfahrung").Path; + outward[^1].Lat.ShouldBeLessThan(outward[0].Lat); + outward[^1].Lon.ShouldBe(TestData.Origin.Lon, 1e-6); + inward[^1].ShouldBe(outward[0]); + } + [Fact] public async Task UseStraightPathWhenNoRoadIsFound() { swisstopoClient.FindPlaceAsync(default!, default, default).ReturnsForAnyArgs(TestData.Meters(1000, 0)); - var geometry = await service.BuildAsync(TestData.Station(1, "nach A", "von A"), CancellationToken.None); + var geometry = await service.BuildAsync(TestData.Station(1, "nach A", "von A"), [], CancellationToken.None); geometry.FollowsRoad.ShouldBeFalse(); geometry.Directions.Count.ShouldBe(2); diff --git a/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs b/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs index 5c3ea47..726cf8c 100644 --- a/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs +++ b/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs @@ -97,15 +97,17 @@ public class SwisstopoClientTestShould { var body = """ {"results":[ - {"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{"objektart":9}}, - {"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"objektart":15}} + {"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{"objektart":9,"strassenname":"Dunantstrasse"}}, + {"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"objektart":15}}, + {"geometry":{"type":"LineString","coordinates":[[9.1,47.7],[9.2,47.7]]},"properties":{"objektart":20}} ]} """; var client = Client(new StubHandler((HttpStatusCode.OK, body))); var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None); - segments.Select(s => s.IsDrivable).ShouldBe([true, false]); + segments.Select(s => s.IsDrivable).ShouldBe([true, false, true]); + segments.Select(s => s.Name).ShouldBe(["Dunantstrasse", null, null]); } [Fact] diff --git a/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs b/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs index 99a33a2..97245a3 100644 --- a/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs +++ b/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs @@ -2,17 +2,26 @@ namespace Schaad.OpenData.Traffic.Geometry; public sealed record DirectionTarget(string Place, bool IsDestination) { + private static readonly string[] DestinationPrefixes = ["nach ", "zur ", "zum ", "richtung "]; + private static readonly string[] OriginPrefixes = ["von ", "vom "]; + public static DirectionTarget Parse(string direction) { var text = direction.Trim(); - if (text.StartsWith("nach ", StringComparison.OrdinalIgnoreCase)) + foreach (var prefix in OriginPrefixes) { - return new DirectionTarget(text[5..].Trim(), true); + if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + return new DirectionTarget(text[prefix.Length..].Trim(), false); + } } - if (text.StartsWith("von ", StringComparison.OrdinalIgnoreCase)) + foreach (var prefix in DestinationPrefixes) { - return new DirectionTarget(text[4..].Trim(), false); + if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + return new DirectionTarget(text[prefix.Length..].Trim(), true); + } } return new DirectionTarget(text, true); diff --git a/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs b/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs index cd8ec1d..d7bc16c 100644 --- a/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs +++ b/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs @@ -13,15 +13,16 @@ public static class RoadPathBuilder private const double ArmSearchMeters = 80; private const float ArmDistancePenalty = 2f; + private const float MinimumArmProgressMeters = 30f; - private sealed record RoadLine(List Points, bool IsMainRoad); + private sealed record RoadLine(List Points, bool IsMainRoad, string? Name); private static List ToLines(IReadOnlyList segments, LocalProjection projection) { var usable = segments.Where(s => s.Points.Count >= 2).ToList(); var drivable = usable.Where(s => s.IsDrivable).ToList(); return (drivable.Count > 0 ? drivable : usable) - .Select(s => new RoadLine(s.Points.Select(projection.ToLocal).ToList(), s.IsMainRoad)) + .Select(s => new RoadLine(s.Points.Select(projection.ToLocal).ToList(), s.IsMainRoad, s.Name)) .ToList(); } @@ -54,7 +55,12 @@ public static class RoadPathBuilder return trimmed.Count >= 2 ? trimmed.Select(projection.ToGeo).ToList() : null; } - public static IReadOnlyList? BuildArmPath(GeoPoint station, IReadOnlyList segments, GeoPoint target, double lengthMeters) + public static IReadOnlyList? BuildArmPath( + GeoPoint station, + IReadOnlyList segments, + GeoPoint target, + double lengthMeters, + string? roadName = null) { var projection = new LocalProjection(station); var toward = projection.ToLocal(target); @@ -65,22 +71,33 @@ public static class RoadPathBuilder toward = Vector2.Normalize(toward); var lines = ToLines(segments, projection); - var best = lines - .Select((line, index) => (Index: index, Distance: DistanceToPolyline(Vector2.Zero, line.Points))) + var nearby = lines + .Select((line, index) => (Index: index, Distance: DistanceToPolyline(Vector2.Zero, line.Points), line.Name)) .Where(c => c.Distance <= ArmSearchMeters) + .ToList(); + var named = nearby + .Where(c => !string.IsNullOrEmpty(roadName) && string.Equals(c.Name, roadName, StringComparison.OrdinalIgnoreCase)) + .Select(c => (c.Index, c.Distance)) + .ToList(); + var all = nearby.Select(c => (c.Index, c.Distance)).ToList(); + + var arm = BestArm(lines, named, toward, lengthMeters) ?? BestArm(lines, all, toward, lengthMeters); + return arm?.Select(projection.ToGeo).ToList(); + } + + private static List? BestArm(List lines, List<(int Index, double Distance)> candidates, Vector2 toward, double lengthMeters) => + candidates .Select(c => { var arm = FollowArm(lines, c.Index, toward, lengthMeters); - var progress = arm.Count >= 2 && Length(arm) >= MinimumSideLengthMeters ? Vector2.Dot(arm[^1], toward) : float.MinValue; - return (Arm: arm, Score: progress - ArmDistancePenalty * c.Distance); + var isValid = arm.Count >= 2 && Length(arm) >= MinimumSideLengthMeters && Vector2.Dot(arm[^1], toward) >= MinimumArmProgressMeters; + return (Arm: arm, IsValid: isValid, Score: Vector2.Dot(arm.Count > 0 ? arm[^1] : Vector2.Zero, toward) - ArmDistancePenalty * c.Distance); }) - .Where(c => c.Score > float.MinValue / 2) + .Where(c => c.IsValid) .OrderByDescending(c => c.Score) + .Select(c => c.Arm) .FirstOrDefault(); - return best.Arm?.Select(projection.ToGeo).ToList(); - } - private static List FollowArm(List lines, int start, Vector2 toward, double lengthMeters) { var chain = new List(lines[start].Points); diff --git a/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs b/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs index f00f3c5..03c2ed7 100644 --- a/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs +++ b/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs @@ -2,4 +2,4 @@ using Schaad.OpenData.Traffic.Models; namespace Schaad.OpenData.Traffic.Geometry; -public sealed record RoadSegment(IReadOnlyList Points, bool IsMainRoad, bool IsDrivable = true); +public sealed record RoadSegment(IReadOnlyList Points, bool IsMainRoad, bool IsDrivable = true, string? Name = null); diff --git a/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs b/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs index 38b7394..5ee3cb9 100644 --- a/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs +++ b/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs @@ -6,22 +6,28 @@ public class StationGeometryService(SwisstopoClient swisstopoClient) { private const double HalfPathLengthMeters = 300; private const double SearchRadiusMeters = 650; + private const double MetersPerDegreeLat = 111_320; + private const double MinimumArmOffsetMeters = 3; + private const double OutwardTargetMeters = 3000; + private const string RoundaboutMarker = "Kreisel"; - public virtual async Task BuildAsync(Station station, CancellationToken cancellationToken) + public virtual async Task BuildAsync(Station station, IReadOnlyList stations, CancellationToken cancellationToken) { + var isRoundaboutArm = station.Name.Contains(RoundaboutMarker, StringComparison.OrdinalIgnoreCase); + var outwardTarget = isRoundaboutArm ? OutwardTarget(station, stations) : null; + var directions = new List(); foreach (var direction in station.Directions) { var target = DirectionTarget.Parse(direction); - directions.Add(new ResolvedDirection(direction, target, await FindPlaceAsync(target.Place, station.Location, cancellationToken))); + var location = outwardTarget ?? await FindPlaceAsync(target.Place, station.Location, cancellationToken); + directions.Add(new ResolvedDirection(direction, target, location)); } var targetLocation = directions.Select(d => d.TargetLocation).FirstOrDefault(l => l is not null); - var isRoundaboutArm = station.Name.Contains("Kreisel", StringComparison.OrdinalIgnoreCase) && targetLocation is not null; - var segments = await swisstopoClient.GetRoadSegmentsAsync(station.Location, SearchRadiusMeters, cancellationToken); - var roadPath = (isRoundaboutArm - ? RoadPathBuilder.BuildArmPath(station.Location, segments, targetLocation!.Value, 2 * HalfPathLengthMeters) + var roadPath = (isRoundaboutArm && targetLocation is { } armTarget + ? RoadPathBuilder.BuildArmPath(station.Location, segments, armTarget, 2 * HalfPathLengthMeters, station.Address) : null) ?? RoadPathBuilder.BuildRoadPath(station.Location, segments, HalfPathLengthMeters); @@ -30,6 +36,32 @@ public class StationGeometryService(SwisstopoClient swisstopoClient) return new StationGeometry(station.Code, roadPath is not null, RoadPathBuilder.Orient(station.Location, path, directions)); } + internal static GeoPoint? OutwardTarget(Station station, IReadOnlyList stations) + { + var key = RoundaboutKey(station.Name); + var siblings = stations.Where(s => RoundaboutKey(s.Name) == key).ToList(); + if (siblings.Count < 2) + { + return null; + } + + var center = new GeoPoint(siblings.Average(s => s.Location.Lat), siblings.Average(s => s.Location.Lon)); + var deltaLat = station.Location.Lat - center.Lat; + var deltaLon = station.Location.Lon - center.Lon; + var meters = Math.Sqrt( + Math.Pow(deltaLat * MetersPerDegreeLat, 2) + + Math.Pow(deltaLon * MetersPerDegreeLat * Math.Cos(center.Lat * Math.PI / 180), 2)); + if (meters < MinimumArmOffsetMeters) + { + return null; + } + + var scale = OutwardTargetMeters / meters; + return new GeoPoint(center.Lat + deltaLat * scale, center.Lon + deltaLon * scale); + } + + private static string RoundaboutKey(string name) => name.Split(" - ", 2)[0].Trim(); + private async Task FindPlaceAsync(string place, GeoPoint near, CancellationToken cancellationToken) { foreach (var part in place.Split('/', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) diff --git a/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs b/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs index 327abb0..f811b1f 100644 --- a/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs +++ b/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs @@ -13,7 +13,8 @@ public partial class SwisstopoClient(HttpClient httpClient) private const int MaxRetries = 2; private const int PageSize = 200; private const int MaxPages = 5; - private const int MaxDrivableObjectKind = 11; + private const int FirstNonRoadObjectKind = 12; + private const int LastNonRoadObjectKind = 19; public virtual async Task> GetRoadSegmentsAsync(GeoPoint center, double radiusMeters, CancellationToken cancellationToken) { @@ -61,7 +62,10 @@ public partial class SwisstopoClient(HttpClient httpClient) var isDrivable = !hasProperties || !properties.TryGetProperty("objektart", out var kind) || kind.ValueKind != JsonValueKind.Number - || kind.GetInt32() <= MaxDrivableObjectKind; + || kind.GetInt32() is < FirstNonRoadObjectKind or > LastNonRoadObjectKind; + var name = hasProperties && properties.TryGetProperty("strassenname", out var streetName) && streetName.ValueKind == JsonValueKind.String + ? streetName.GetString() + : null; var coordinates = geometry.GetProperty("coordinates"); var parts = geometry.GetProperty("type").GetString() switch @@ -74,7 +78,8 @@ public partial class SwisstopoClient(HttpClient httpClient) return parts.Select(part => new RoadSegment( part.EnumerateArray().Select(p => new GeoPoint(p[1].GetDouble(), p[0].GetDouble())).ToList(), isMainRoad, - isDrivable)); + isDrivable, + name)); } public virtual async Task FindPlaceAsync(string name, GeoPoint near, CancellationToken cancellationToken) diff --git a/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs b/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs index a7aca15..f38de5d 100644 --- a/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs +++ b/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs @@ -8,7 +8,7 @@ namespace Schaad.OpenData.Traffic.Storage; public class TrafficCacheStorage(IOptions options) { private const string DayFormat = "yyyy-MM-dd"; - private const string GeometryFileName = "geometry-v5.json"; + private const string GeometryFileName = "geometry-v7.json"; private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true }; diff --git a/Schaad.OpenData.Traffic/TrafficRefresher.cs b/Schaad.OpenData.Traffic/TrafficRefresher.cs index 2783a94..922ef7a 100644 --- a/Schaad.OpenData.Traffic/TrafficRefresher.cs +++ b/Schaad.OpenData.Traffic/TrafficRefresher.cs @@ -38,7 +38,8 @@ public class TrafficRefresher( public async Task BuildMissingGeometryAsync(CancellationToken cancellationToken) { var snapshot = store.Current; - var missing = snapshot.Stations.Values.Where(s => !snapshot.Geometry.ContainsKey(s.Code)).ToList(); + var stations = snapshot.Stations.Values.ToList(); + var missing = stations.Where(s => !snapshot.Geometry.ContainsKey(s.Code)).ToList(); if (missing.Count == 0) { return; @@ -49,7 +50,7 @@ public class TrafficRefresher( { try { - built.Add(await geometryService.BuildAsync(station, cancellationToken)); + built.Add(await geometryService.BuildAsync(station, stations, cancellationToken)); } catch (HttpRequestException exception) { -- 2.39.5 From d7401b63cdddbdb736f2ee1dc33ab7a4d615b271 Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Fri, 6 Nov 2026 20:50:55 +0100 Subject: [PATCH 3/3] Add start page with tiles for the available maps The app will show several maps and datasets, so it now opens on a start page with one large tile per map instead of the traffic map. - Routing with react-router-dom: "/" is the start page, the Thurgau traffic map moved to "/verkehr/thurgau" (pages/TrafficThurgauPage) - Map registry in src/maps.ts drives the tiles (title, region, description, tags, source, preview image) - SVG preview illustration for the traffic map tile - Traffic map header links back to the start page; page titles set per page Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + client/index.html | 2 +- client/package-lock.json | 41 ++++- client/package.json | 3 +- client/public/previews/traffic-thurgau.svg | 74 ++++++++ client/src/App.tsx | 177 +------------------ client/src/main.tsx | 5 +- client/src/maps.ts | 22 +++ client/src/pages/HomePage.tsx | 47 ++++++ client/src/pages/TrafficThurgauPage.tsx | 187 +++++++++++++++++++++ client/src/styles.css | 162 ++++++++++++++++++ 11 files changed, 548 insertions(+), 173 deletions(-) create mode 100644 client/public/previews/traffic-thurgau.svg create mode 100644 client/src/maps.ts create mode 100644 client/src/pages/HomePage.tsx create mode 100644 client/src/pages/TrafficThurgauPage.tsx diff --git a/CLAUDE.md b/CLAUDE.md index bcecc55..2b14bc9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -66,6 +66,7 @@ When the geometry algorithm changes, bump `GeometryFileName` in `TrafficCacheSto ### Client +- Routing with `react-router-dom`: `/` is the start page (`pages/HomePage.tsx`) with one large tile per map, each map has its own page (`/verkehr/thurgau` → `pages/TrafficThurgauPage.tsx`). Tiles come from the registry in `src/maps.ts`; a new map needs an entry there (with a preview image in `public/previews/`) and a route in `App.tsx`. Deep links work because the server falls back to `index.html`. - `traffic/flowAnimator.ts` owns the animation clock (time of day in hours, play/pause, speed) and draws on a canvas above Leaflet's overlay pane. Dots spawn per direction at a rate proportional to the interpolated hourly count, colored and sized by vehicle group, offset to the right of the driving direction. It reports the time to React at ~10 Hz via `onTick`; React components only get the integer hour, so markers and charts don't re-render every frame. - The vehicle class order in `traffic/vehicleClasses.ts` must match the `VehicleClass` enum / `VehicleCounts.ToArray()` order; count arrays in the API are positional. - UI language is German (de-CH). Base maps are swisstopo WMTS layers (grey `pixelkarte-grau` as default, colour `pixelkarte-farbe`, aerial `swissimage`), switchable via Leaflet's layer control; the choice is stored in localStorage (`odv.baseMap`). diff --git a/client/index.html b/client/index.html index 60386db..1f0b0e4 100644 --- a/client/index.html +++ b/client/index.html @@ -4,7 +4,7 @@ - OpenDataVisualizer – Verkehr Thurgau + OpenDataVisualizer
diff --git a/client/package-lock.json b/client/package-lock.json index cfe44a9..e2ea090 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -13,7 +13,8 @@ "leaflet": "^1.9.4", "react": "^18.3.1", "react-chartjs-2": "^5.2.0", - "react-dom": "^18.3.1" + "react-dom": "^18.3.1", + "react-router-dom": "^6.30.6" }, "devDependencies": { "@types/leaflet": "^1.9.12", @@ -754,6 +755,14 @@ "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz", "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==" }, + "node_modules/@remix-run/router": { + "version": "1.23.4", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.4.tgz", + "integrity": "sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/@rolldown/pluginutils": { "version": "1.0.0-beta.27", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", @@ -1625,6 +1634,36 @@ "node": ">=0.10.0" } }, + "node_modules/react-router": { + "version": "6.30.6", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.6.tgz", + "integrity": "sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==", + "dependencies": { + "@remix-run/router": "1.23.4" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8" + } + }, + "node_modules/react-router-dom": { + "version": "6.30.6", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.6.tgz", + "integrity": "sha512-0RHKZz7wwffvkU+2MFVT2NnjK44ssLEV+m0CAJaS2Ksmorrwj7WxH00jO0SOCW26/tINUnJHToXblDs33I38YQ==", + "dependencies": { + "@remix-run/router": "1.23.4", + "react-router": "6.30.6" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, "node_modules/rollup": { "version": "4.68.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.0.tgz", diff --git a/client/package.json b/client/package.json index 535c0ca..debc024 100644 --- a/client/package.json +++ b/client/package.json @@ -16,7 +16,8 @@ "leaflet": "^1.9.4", "react": "^18.3.1", "react-chartjs-2": "^5.2.0", - "react-dom": "^18.3.1" + "react-dom": "^18.3.1", + "react-router-dom": "^6.30.6" }, "devDependencies": { "@types/leaflet": "^1.9.12", diff --git a/client/public/previews/traffic-thurgau.svg b/client/public/previews/traffic-thurgau.svg new file mode 100644 index 0000000..24234f3 --- /dev/null +++ b/client/public/previews/traffic-thurgau.svg @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/src/App.tsx b/client/src/App.tsx index 8778ee7..49a556f 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,174 +1,13 @@ -import { keepPreviousData, useQuery } from '@tanstack/react-query'; -import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { fetchDay, fetchMeta, fetchStations } from './api/traffic'; -import { Legend } from './components/Legend'; -import { StationPanel } from './components/StationPanel'; -import { SPEEDS, TimeControls } from './components/TimeControls'; -import { TrafficMap } from './components/TrafficMap'; -import type { FlowAnimator } from './traffic/flowAnimator'; -import { formatNumber } from './traffic/format'; -import { sumCounts } from './traffic/vehicleClasses'; - -const MemoStationPanel = memo(StationPanel); - -const INITIAL_TIME = 7.5; +import { Navigate, Route, Routes } from 'react-router-dom'; +import { HomePage } from './pages/HomePage'; +import { TrafficThurgauPage } from './pages/TrafficThurgauPage'; export function App() { - const metaQuery = useQuery({ - queryKey: ['meta'], - queryFn: fetchMeta, - refetchInterval: 10 * 60_000, - }); - const stationsQuery = useQuery({ - queryKey: ['stations'], - queryFn: fetchStations, - refetchInterval: (query) => - query.state.data?.some((s) => s.directions.some((d) => d.path.length < 2)) ? 30_000 : false, - }); - - const dates = useMemo(() => metaQuery.data?.dates ?? [], [metaQuery.data]); - const [date, setDate] = useState(null); - const [time, setTime] = useState(INITIAL_TIME); - const [playing, setPlaying] = useState(false); - const [hoursPerSecond, setHoursPerSecond] = useState(SPEEDS[1].hoursPerSecond); - const [selectedCode, setSelectedCode] = useState(null); - const animatorRef = useRef(null); - const datesRef = useRef(dates); - datesRef.current = dates; - - useEffect(() => { - if (!date && dates.length > 0) { - setDate(dates[dates.length - 1]); - } - }, [date, dates]); - - const dayQuery = useQuery({ - queryKey: ['day', date], - queryFn: () => fetchDay(date!), - enabled: !!date, - placeholderData: keepPreviousData, - staleTime: 5 * 60_000, - }); - const day = dayQuery.data ?? null; - - const handleAnimatorReady = useCallback((animator: FlowAnimator) => { - animatorRef.current = animator; - animator.time = INITIAL_TIME; - animator.onTick = setTime; - animator.onDayEnd = () => - setDate((current) => { - const all = datesRef.current; - const index = current ? all.indexOf(current) : -1; - return all.length === 0 ? current : all[(index + 1) % all.length]; - }); - }, []); - - useEffect(() => { - if (animatorRef.current) { - animatorRef.current.playing = playing; - } - }, [playing]); - - useEffect(() => { - if (animatorRef.current) { - animatorRef.current.hoursPerSecond = hoursPerSecond; - } - }, [hoursPerSecond]); - - const handleTimeChange = useCallback((value: number) => { - if (animatorRef.current) { - animatorRef.current.time = value; - } - setTime(value); - }, []); - - const handleClose = useCallback(() => setSelectedCode(null), []); - - const hour = Math.min(23, Math.floor(time)); - const stations = useMemo(() => stationsQuery.data ?? [], [stationsQuery.data]); - const selectedStation = stations.find((s) => s.code === selectedCode) ?? null; - - const hourTotal = useMemo( - () => - day?.stations.reduce( - (sum, station) => - sum + station.directions.reduce((s, d) => s + sumCounts(d.hours[hour]), 0), - 0, - ) ?? 0, - [day, hour], - ); - - const error = metaQuery.error ?? stationsQuery.error ?? dayQuery.error; - return ( -
-
-
-

OpenDataVisualizer

- - Strassenverkehr Kanton Thurgau · stündliche Zählungen nach Fahrzeugklassen - -
-
-
- {stations.length} - Zählstellen -
-
- {formatNumber(hourTotal)} - Fahrzeuge in dieser Stunde -
-
-
- -
- - -
- {date && ( - - )} - -
- - {(metaQuery.isLoading || (metaQuery.data && dates.length === 0)) && ( -
- Verkehrsdaten werden geladen… (erster Start lädt die Daten von data.tg.ch) -
- )} - {error &&
Fehler beim Laden: {String(error.message)}
} -
- - {selectedStation && ( - - )} - - -
+ + } /> + } /> + } /> + ); } diff --git a/client/src/main.tsx b/client/src/main.tsx index eb39b90..282a07e 100644 --- a/client/src/main.tsx +++ b/client/src/main.tsx @@ -1,4 +1,5 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { BrowserRouter } from 'react-router-dom'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { App } from './App'; @@ -11,7 +12,9 @@ const queryClient = new QueryClient({ createRoot(document.getElementById('root')!).render( - + + + , ); diff --git a/client/src/maps.ts b/client/src/maps.ts new file mode 100644 index 0000000..c74d403 --- /dev/null +++ b/client/src/maps.ts @@ -0,0 +1,22 @@ +export interface MapEntry { + path: string; + title: string; + region: string; + description: string; + source: string; + tags: string[]; + preview: string; +} + +export const MAPS: MapEntry[] = [ + { + path: '/verkehr/thurgau', + title: 'Strassenverkehr', + region: 'Kanton Thurgau', + description: + 'Fahrzeuge fahren animiert über die Strassen der 64 Zählstellen – stündlich nach Fahrzeugklasse, mit Tagesverlauf und Auswertungen pro Zählstelle.', + source: 'Tiefbauamt Kanton Thurgau', + tags: ['Verkehr', 'Stundenwerte', 'Animation'], + preview: '/previews/traffic-thurgau.svg', + }, +]; diff --git a/client/src/pages/HomePage.tsx b/client/src/pages/HomePage.tsx new file mode 100644 index 0000000..223e80f --- /dev/null +++ b/client/src/pages/HomePage.tsx @@ -0,0 +1,47 @@ +import { useEffect } from 'react'; +import { Link } from 'react-router-dom'; +import { MAPS } from '../maps'; + +export function HomePage() { + useEffect(() => { + document.title = 'OpenDataVisualizer'; + }, []); + + return ( +
+
+

OpenDataVisualizer

+

+ Karten und Visualisierungen zu offenen Daten der Schweiz von{' '} + + opendata.swiss + + . +

+
+ +
+ {MAPS.map((map) => ( + +
+ +
+
+ {map.region} +

{map.title}

+

{map.description}

+
+ {map.tags.map((tag) => ( + + {tag} + + ))} +
+ Quelle: {map.source} +
+ + ))} +
+
+ ); +} diff --git a/client/src/pages/TrafficThurgauPage.tsx b/client/src/pages/TrafficThurgauPage.tsx new file mode 100644 index 0000000..d0b8eb0 --- /dev/null +++ b/client/src/pages/TrafficThurgauPage.tsx @@ -0,0 +1,187 @@ +import { keepPreviousData, useQuery } from '@tanstack/react-query'; +import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { Link } from 'react-router-dom'; +import { fetchDay, fetchMeta, fetchStations } from '../api/traffic'; +import { Legend } from '../components/Legend'; +import { StationPanel } from '../components/StationPanel'; +import { SPEEDS, TimeControls } from '../components/TimeControls'; +import { TrafficMap } from '../components/TrafficMap'; +import type { FlowAnimator } from '../traffic/flowAnimator'; +import { formatNumber } from '../traffic/format'; +import { sumCounts } from '../traffic/vehicleClasses'; + +const MemoStationPanel = memo(StationPanel); + +const INITIAL_TIME = 7.5; + +export function TrafficThurgauPage() { + const metaQuery = useQuery({ + queryKey: ['meta'], + queryFn: fetchMeta, + refetchInterval: 10 * 60_000, + }); + const stationsQuery = useQuery({ + queryKey: ['stations'], + queryFn: fetchStations, + refetchInterval: (query) => + query.state.data?.some((s) => s.directions.some((d) => d.path.length < 2)) ? 30_000 : false, + }); + + const dates = useMemo(() => metaQuery.data?.dates ?? [], [metaQuery.data]); + const [date, setDate] = useState(null); + const [time, setTime] = useState(INITIAL_TIME); + const [playing, setPlaying] = useState(false); + const [hoursPerSecond, setHoursPerSecond] = useState(SPEEDS[1].hoursPerSecond); + const [selectedCode, setSelectedCode] = useState(null); + const animatorRef = useRef(null); + useEffect(() => { + document.title = 'Strassenverkehr Thurgau – OpenDataVisualizer'; + }, []); + + const datesRef = useRef(dates); + datesRef.current = dates; + + useEffect(() => { + if (!date && dates.length > 0) { + setDate(dates[dates.length - 1]); + } + }, [date, dates]); + + const dayQuery = useQuery({ + queryKey: ['day', date], + queryFn: () => fetchDay(date!), + enabled: !!date, + placeholderData: keepPreviousData, + staleTime: 5 * 60_000, + }); + const day = dayQuery.data ?? null; + + const handleAnimatorReady = useCallback((animator: FlowAnimator) => { + animatorRef.current = animator; + animator.time = INITIAL_TIME; + animator.onTick = setTime; + animator.onDayEnd = () => + setDate((current) => { + const all = datesRef.current; + const index = current ? all.indexOf(current) : -1; + return all.length === 0 ? current : all[(index + 1) % all.length]; + }); + }, []); + + useEffect(() => { + if (animatorRef.current) { + animatorRef.current.playing = playing; + } + }, [playing]); + + useEffect(() => { + if (animatorRef.current) { + animatorRef.current.hoursPerSecond = hoursPerSecond; + } + }, [hoursPerSecond]); + + const handleTimeChange = useCallback((value: number) => { + if (animatorRef.current) { + animatorRef.current.time = value; + } + setTime(value); + }, []); + + const handleClose = useCallback(() => setSelectedCode(null), []); + + const hour = Math.min(23, Math.floor(time)); + const stations = useMemo(() => stationsQuery.data ?? [], [stationsQuery.data]); + const selectedStation = stations.find((s) => s.code === selectedCode) ?? null; + + const hourTotal = useMemo( + () => + day?.stations.reduce( + (sum, station) => + sum + station.directions.reduce((s, d) => s + sumCounts(d.hours[hour]), 0), + 0, + ) ?? 0, + [day, hour], + ); + + const error = metaQuery.error ?? stationsQuery.error ?? dayQuery.error; + + return ( +
+
+
+ + ← + +
+

+ + OpenDataVisualizer + {' '} + / Strassenverkehr Thurgau +

+ Stündliche Zählungen nach Fahrzeugklassen +
+
+
+
+ {stations.length} + Zählstellen +
+
+ {formatNumber(hourTotal)} + Fahrzeuge in dieser Stunde +
+
+
+ +
+ + +
+ {date && ( + + )} + +
+ + {(metaQuery.isLoading || (metaQuery.data && dates.length === 0)) && ( +
+ Verkehrsdaten werden geladen… (erster Start lädt die Daten von data.tg.ch) +
+ )} + {error &&
Fehler beim Laden: {String(error.message)}
} +
+ + {selectedStation && ( + + )} + + +
+ ); +} diff --git a/client/src/styles.css b/client/src/styles.css index 099ddbe..129dd19 100644 --- a/client/src/styles.css +++ b/client/src/styles.css @@ -358,3 +358,165 @@ select { flex-wrap: wrap; } } + +.title-row { + display: flex; + align-items: center; + gap: 12px; +} + +.back-link { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 8px; + border: 1px solid var(--border); + color: var(--text); + text-decoration: none; + font-size: 16px; +} + +.back-link:hover { + background: var(--bg); +} + +.brand-link { + color: inherit; + text-decoration: none; +} + +.brand-link:hover { + color: var(--accent); +} + +.title-separator { + color: var(--muted); + font-weight: 400; +} + +.home { + height: 100%; + overflow-y: auto; + padding: 48px 32px 64px; +} + +.home-header { + max-width: 1200px; + margin: 0 auto 32px; +} + +.home-header h1 { + margin: 0 0 6px; + font-size: 32px; + letter-spacing: -0.02em; +} + +.home-header p { + margin: 0; + color: var(--muted); + font-size: 16px; +} + +.home-header a { + color: var(--accent); +} + +.map-tiles { + max-width: 1200px; + margin: 0 auto; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(min(100%, 480px), 1fr)); + gap: 24px; +} + +.map-tile { + display: flex; + flex-direction: column; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 16px; + overflow: hidden; + color: inherit; + text-decoration: none; + box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06); + transition: + transform 0.15s, + box-shadow 0.15s, + border-color 0.15s; +} + +.map-tile:hover, +.map-tile:focus-visible { + transform: translateY(-3px); + border-color: #bfdbfe; + box-shadow: 0 12px 32px rgba(15, 23, 42, 0.12); + outline: none; +} + +.map-tile-preview { + aspect-ratio: 16 / 9; + background: #e3e8e1; + border-bottom: 1px solid var(--border); +} + +.map-tile-preview img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; +} + +.map-tile-body { + display: flex; + flex-direction: column; + gap: 8px; + padding: 20px 22px 22px; +} + +.map-tile-region { + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--accent); +} + +.map-tile h2 { + margin: 0; + font-size: 24px; + letter-spacing: -0.01em; +} + +.map-tile p { + margin: 0; + color: #334155; + line-height: 1.5; +} + +.map-tile-tags { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: 4px; +} + +.tag { + font-size: 12px; + padding: 3px 9px; + border-radius: 999px; + background: #eff6ff; + color: #1d4ed8; +} + +.map-tile-source { + font-size: 12px; + color: var(--muted); +} + +@media (max-width: 600px) { + .home { + padding: 28px 16px 40px; + } +} -- 2.39.5