Compare commits
3 commits
8907d321b3
...
d7401b63cd
| Author | SHA1 | Date | |
|---|---|---|---|
| d7401b63cd | |||
| 8de869b023 | |||
| e729ea3403 |
86 changed files with 6847 additions and 1 deletions
11
.claude/launch.json
Normal file
11
.claude/launch.json
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "server",
|
||||
"runtimeExecutable": "dotnet",
|
||||
"runtimeArgs": ["run", "--project", "Schaad.OpenData.Server", "--launch-profile", "http"],
|
||||
"port": 5080
|
||||
}
|
||||
]
|
||||
}
|
||||
10
.dockerignore
Normal file
10
.dockerignore
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
**/bin/
|
||||
**/obj/
|
||||
**/node_modules/
|
||||
client/dist/
|
||||
Schaad.OpenData.Server/wwwroot/
|
||||
data/
|
||||
.git/
|
||||
.idea/
|
||||
.vs/
|
||||
.claude/
|
||||
492
.gitignore
vendored
Normal file
492
.gitignore
vendored
Normal file
|
|
@ -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/
|
||||
79
CLAUDE.md
Normal file
79
CLAUDE.md
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
# 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) 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. 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.
|
||||
|
||||
### 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`).
|
||||
|
||||
## 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 `<Subject>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).
|
||||
7
Directory.Build.props
Normal file
7
Directory.Build.props
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
<Project>
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
18
Directory.Packages.props
Normal file
18
Directory.Packages.props
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<Project>
|
||||
<PropertyGroup>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Http" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.0" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageVersion Include="NSubstitute" Version="5.3.0" />
|
||||
<PackageVersion Include="Shouldly" Version="4.3.0" />
|
||||
<PackageVersion Include="xunit" Version="2.9.3" />
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
31
Dockerfile
Normal file
31
Dockerfile
Normal file
|
|
@ -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"]
|
||||
62
OpenDataVisualizer.sln
Normal file
62
OpenDataVisualizer.sln
Normal file
|
|
@ -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
|
||||
23
README.md
23
README.md
|
|
@ -1,3 +1,24 @@
|
|||
# OpenDataVisualizer
|
||||
|
||||
Visualization for opendata.swiss
|
||||
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).
|
||||
|
|
|
|||
17
Schaad.OpenData.Server/Program.cs
Normal file
17
Schaad.OpenData.Server/Program.cs
Normal file
|
|
@ -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();
|
||||
14
Schaad.OpenData.Server/Properties/launchSettings.json
Normal file
14
Schaad.OpenData.Server/Properties/launchSettings.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
7
Schaad.OpenData.Server/Schaad.OpenData.Server.csproj
Normal file
7
Schaad.OpenData.Server/Schaad.OpenData.Server.csproj
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Schaad.OpenData.Traffic\Schaad.OpenData.Traffic.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
3
Schaad.OpenData.Server/Traffic/DirectionResponse.cs
Normal file
3
Schaad.OpenData.Server/Traffic/DirectionResponse.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Server.Traffic;
|
||||
|
||||
public sealed record DirectionResponse(string Name, IReadOnlyList<double[]> Path);
|
||||
10
Schaad.OpenData.Server/Traffic/MetaResponse.cs
Normal file
10
Schaad.OpenData.Server/Traffic/MetaResponse.cs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
namespace Schaad.OpenData.Server.Traffic;
|
||||
|
||||
public sealed record MetaResponse(
|
||||
string Title,
|
||||
string Publisher,
|
||||
string SourceUrl,
|
||||
string License,
|
||||
IReadOnlyList<string> VehicleClasses,
|
||||
IReadOnlyList<DateOnly> Dates,
|
||||
DateTimeOffset? LastRefresh);
|
||||
30
Schaad.OpenData.Server/Traffic/StationResponse.cs
Normal file
30
Schaad.OpenData.Server/Traffic/StationResponse.cs
Normal file
|
|
@ -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<DirectionResponse> 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());
|
||||
}
|
||||
43
Schaad.OpenData.Server/Traffic/TrafficEndpoints.cs
Normal file
43
Schaad.OpenData.Server/Traffic/TrafficEndpoints.cs
Normal file
|
|
@ -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<VehicleClass>().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;
|
||||
}
|
||||
}
|
||||
14
Schaad.OpenData.Server/appsettings.json
Normal file
14
Schaad.OpenData.Server/appsettings.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"System.Net.Http.HttpClient": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Traffic": {
|
||||
"DataPath": "../data",
|
||||
"RefreshInterval": "06:00:00"
|
||||
}
|
||||
}
|
||||
30
Schaad.OpenData.Tests/DirectionTargetTestShould.cs
Normal file
30
Schaad.OpenData.Tests/DirectionTargetTestShould.cs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
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 ParseDestinationWhenDirectionStartsWithZur()
|
||||
{
|
||||
DirectionTarget.Parse("zur Umfahrung").ShouldBe(new DirectionTarget("Umfahrung", true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TreatPlainNameAsDestinationWhenDirectionHasNoPrefix()
|
||||
{
|
||||
DirectionTarget.Parse("Diessenhofen").ShouldBe(new DirectionTarget("Diessenhofen", true));
|
||||
}
|
||||
}
|
||||
190
Schaad.OpenData.Tests/RoadPathBuilderTestShould.cs
Normal file
190
Schaad.OpenData.Tests/RoadPathBuilderTestShould.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
25
Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj
Normal file
25
Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="NSubstitute" />
|
||||
<PackageReference Include="Shouldly" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
<Using Include="Shouldly" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Schaad.OpenData.Traffic\Schaad.OpenData.Traffic.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
96
Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs
Normal file
96
Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
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<SwisstopoClient>(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<GeoPoint>(), Arg.Any<CancellationToken>()).Returns((GeoPoint?)null);
|
||||
swisstopoClient.FindPlaceAsync("Busswil", Arg.Any<GeoPoint>(), Arg.Any<CancellationToken>()).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<GeoPoint>(), Arg.Any<CancellationToken>());
|
||||
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);
|
||||
|
||||
geometry.FollowsRoad.ShouldBeFalse();
|
||||
geometry.Directions.Count.ShouldBe(2);
|
||||
}
|
||||
}
|
||||
126
Schaad.OpenData.Tests/SwisstopoClientTestShould.cs
Normal file
126
Schaad.OpenData.Tests/SwisstopoClientTestShould.cs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
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<Uri> Requests { get; } = [];
|
||||
|
||||
protected override Task<HttpResponseMessage> 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":"<b>Landquart (GR)</b>","lat":46.956,"lon":9.578}},
|
||||
{"attrs":{"label":"Landquart [district]","lat":46.961,"lon":9.560}},
|
||||
{"attrs":{"label":"Populated Place <b>Landquart (TG)</b> - 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":"<b>Tägerwilen (TG)</b>","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,"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, true]);
|
||||
segments.Select(s => s.Name).ShouldBe(["Dunantstrasse", null, null]);
|
||||
}
|
||||
|
||||
[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]);
|
||||
}
|
||||
}
|
||||
45
Schaad.OpenData.Tests/TestData.cs
Normal file
45
Schaad.OpenData.Tests/TestData.cs
Normal file
|
|
@ -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 },
|
||||
};
|
||||
}
|
||||
62
Schaad.OpenData.Tests/ThurgauTrafficMapperTestShould.cs
Normal file
62
Schaad.OpenData.Tests/ThurgauTrafficMapperTestShould.cs
Normal file
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
75
Schaad.OpenData.Tests/TrafficAnalysisTestShould.cs
Normal file
75
Schaad.OpenData.Tests/TrafficAnalysisTestShould.cs
Normal file
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
68
Schaad.OpenData.Tests/TrafficCacheStorageTestShould.cs
Normal file
68
Schaad.OpenData.Tests/TrafficCacheStorageTestShould.cs
Normal file
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
61
Schaad.OpenData.Tests/TrafficSnapshotTestShould.cs
Normal file
61
Schaad.OpenData.Tests/TrafficSnapshotTestShould.cs
Normal file
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
3
Schaad.OpenData.Traffic/Analysis/DailyTotal.cs
Normal file
3
Schaad.OpenData.Traffic/Analysis/DailyTotal.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Analysis;
|
||||
|
||||
public sealed record DailyTotal(DateOnly Date, int Total);
|
||||
3
Schaad.OpenData.Traffic/Analysis/DayView.cs
Normal file
3
Schaad.OpenData.Traffic/Analysis/DayView.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Analysis;
|
||||
|
||||
public sealed record DayView(DateOnly Date, IReadOnlyList<StationDayView> Stations);
|
||||
3
Schaad.OpenData.Traffic/Analysis/DirectionDayView.cs
Normal file
3
Schaad.OpenData.Traffic/Analysis/DirectionDayView.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Analysis;
|
||||
|
||||
public sealed record DirectionDayView(string Direction, IReadOnlyList<int[]?> Hours);
|
||||
8
Schaad.OpenData.Traffic/Analysis/DirectionSummary.cs
Normal file
8
Schaad.OpenData.Traffic/Analysis/DirectionSummary.cs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
namespace Schaad.OpenData.Traffic.Analysis;
|
||||
|
||||
public sealed record DirectionSummary(
|
||||
string Direction,
|
||||
IReadOnlyList<HourlyTotal> Hourly,
|
||||
IReadOnlyList<DailyTotal> Daily,
|
||||
double[] WeekdayProfile,
|
||||
double[] WeekendProfile);
|
||||
3
Schaad.OpenData.Traffic/Analysis/HourlyTotal.cs
Normal file
3
Schaad.OpenData.Traffic/Analysis/HourlyTotal.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Analysis;
|
||||
|
||||
public sealed record HourlyTotal(DateTime Time, int Total);
|
||||
3
Schaad.OpenData.Traffic/Analysis/StationDayView.cs
Normal file
3
Schaad.OpenData.Traffic/Analysis/StationDayView.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Analysis;
|
||||
|
||||
public sealed record StationDayView(int Code, IReadOnlyList<DirectionDayView> Directions);
|
||||
8
Schaad.OpenData.Traffic/Analysis/StationSummary.cs
Normal file
8
Schaad.OpenData.Traffic/Analysis/StationSummary.cs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
namespace Schaad.OpenData.Traffic.Analysis;
|
||||
|
||||
public sealed record StationSummary(
|
||||
int Code,
|
||||
DateOnly From,
|
||||
DateOnly To,
|
||||
IReadOnlyList<DirectionSummary> Directions,
|
||||
int[] ClassTotals);
|
||||
94
Schaad.OpenData.Traffic/Analysis/TrafficAnalysis.cs
Normal file
94
Schaad.OpenData.Traffic/Analysis/TrafficAnalysis.cs
Normal file
|
|
@ -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<HourlyCount> 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<HourlyCount> 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;
|
||||
}
|
||||
29
Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs
Normal file
29
Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
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();
|
||||
foreach (var prefix in OriginPrefixes)
|
||||
{
|
||||
if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new DirectionTarget(text[prefix.Length..].Trim(), false);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var prefix in DestinationPrefixes)
|
||||
{
|
||||
if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new DirectionTarget(text[prefix.Length..].Trim(), true);
|
||||
}
|
||||
}
|
||||
|
||||
return new DirectionTarget(text, true);
|
||||
}
|
||||
}
|
||||
19
Schaad.OpenData.Traffic/Geometry/LocalProjection.cs
Normal file
19
Schaad.OpenData.Traffic/Geometry/LocalProjection.cs
Normal file
|
|
@ -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));
|
||||
}
|
||||
5
Schaad.OpenData.Traffic/Geometry/ResolvedDirection.cs
Normal file
5
Schaad.OpenData.Traffic/Geometry/ResolvedDirection.cs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
using Schaad.OpenData.Traffic.Models;
|
||||
|
||||
namespace Schaad.OpenData.Traffic.Geometry;
|
||||
|
||||
public sealed record ResolvedDirection(string Direction, DirectionTarget Target, GeoPoint? TargetLocation);
|
||||
302
Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs
Normal file
302
Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs
Normal file
|
|
@ -0,0 +1,302 @@
|
|||
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 const float MinimumArmProgressMeters = 30f;
|
||||
|
||||
private sealed record RoadLine(List<Vector2> Points, bool IsMainRoad, string? Name);
|
||||
|
||||
private static List<RoadLine> ToLines(IReadOnlyList<RoadSegment> 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, s.Name))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public static IReadOnlyList<GeoPoint>? BuildRoadPath(GeoPoint station, IReadOnlyList<RoadSegment> 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<Vector2>(lines[start].Points);
|
||||
var used = new HashSet<int> { 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<GeoPoint>? BuildArmPath(
|
||||
GeoPoint station,
|
||||
IReadOnlyList<RoadSegment> segments,
|
||||
GeoPoint target,
|
||||
double lengthMeters,
|
||||
string? roadName = null)
|
||||
{
|
||||
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 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<Vector2>? BestArm(List<RoadLine> lines, List<(int Index, double Distance)> candidates, Vector2 toward, double lengthMeters) =>
|
||||
candidates
|
||||
.Select(c =>
|
||||
{
|
||||
var arm = FollowArm(lines, c.Index, toward, lengthMeters);
|
||||
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.IsValid)
|
||||
.OrderByDescending(c => c.Score)
|
||||
.Select(c => c.Arm)
|
||||
.FirstOrDefault();
|
||||
|
||||
private static List<Vector2> FollowArm(List<RoadLine> lines, int start, Vector2 toward, double lengthMeters)
|
||||
{
|
||||
var chain = new List<Vector2>(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<GeoPoint> 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<DirectionGeometry> Orient(GeoPoint station, IReadOnlyList<GeoPoint> path, IReadOnlyList<ResolvedDirection> 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<Vector2> chain, List<RoadLine> lines, HashSet<int> 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<Vector2>? bestLine = null;
|
||||
|
||||
for (var i = 0; i < lines.Count; i++)
|
||||
{
|
||||
if (used.Contains(i))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var line = lines[i].Points;
|
||||
List<Vector2>? 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<Vector2> Trim(List<Vector2> chain, double center, double halfLengthMeters)
|
||||
{
|
||||
var from = center - halfLengthMeters;
|
||||
var to = center + halfLengthMeters;
|
||||
var result = new List<Vector2>();
|
||||
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<Vector2> 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<Vector2> 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<Vector2> 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);
|
||||
}
|
||||
}
|
||||
5
Schaad.OpenData.Traffic/Geometry/RoadSegment.cs
Normal file
5
Schaad.OpenData.Traffic/Geometry/RoadSegment.cs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
using Schaad.OpenData.Traffic.Models;
|
||||
|
||||
namespace Schaad.OpenData.Traffic.Geometry;
|
||||
|
||||
public sealed record RoadSegment(IReadOnlyList<GeoPoint> Points, bool IsMainRoad, bool IsDrivable = true, string? Name = null);
|
||||
77
Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs
Normal file
77
Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
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;
|
||||
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<StationGeometry> BuildAsync(Station station, IReadOnlyList<Station> stations, CancellationToken cancellationToken)
|
||||
{
|
||||
var isRoundaboutArm = station.Name.Contains(RoundaboutMarker, StringComparison.OrdinalIgnoreCase);
|
||||
var outwardTarget = isRoundaboutArm ? OutwardTarget(station, stations) : null;
|
||||
|
||||
var directions = new List<ResolvedDirection>();
|
||||
foreach (var direction in station.Directions)
|
||||
{
|
||||
var target = DirectionTarget.Parse(direction);
|
||||
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 segments = await swisstopoClient.GetRoadSegmentsAsync(station.Location, SearchRadiusMeters, cancellationToken);
|
||||
var roadPath = (isRoundaboutArm && targetLocation is { } armTarget
|
||||
? RoadPathBuilder.BuildArmPath(station.Location, segments, armTarget, 2 * HalfPathLengthMeters, station.Address)
|
||||
: 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));
|
||||
}
|
||||
|
||||
internal static GeoPoint? OutwardTarget(Station station, IReadOnlyList<Station> 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<GeoPoint?> 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;
|
||||
}
|
||||
}
|
||||
145
Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs
Normal file
145
Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
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 FirstNonRoadObjectKind = 12;
|
||||
private const int LastNonRoadObjectKind = 19;
|
||||
|
||||
public virtual async Task<IReadOnlyList<RoadSegment>> 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<RoadSegment>();
|
||||
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<RoadSegment> 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() 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
|
||||
{
|
||||
"LineString" => [coordinates],
|
||||
"MultiLineString" => coordinates.EnumerateArray().ToList(),
|
||||
_ => new List<JsonElement>(),
|
||||
};
|
||||
|
||||
return parts.Select(part => new RoadSegment(
|
||||
part.EnumerateArray().Select(p => new GeoPoint(p[1].GetDouble(), p[0].GetDouble())).ToList(),
|
||||
isMainRoad,
|
||||
isDrivable,
|
||||
name));
|
||||
}
|
||||
|
||||
public virtual async Task<GeoPoint?> 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<JsonDocument> 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();
|
||||
}
|
||||
3
Schaad.OpenData.Traffic/Models/DirectionGeometry.cs
Normal file
3
Schaad.OpenData.Traffic/Models/DirectionGeometry.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Models;
|
||||
|
||||
public sealed record DirectionGeometry(string Direction, IReadOnlyList<GeoPoint> Path);
|
||||
3
Schaad.OpenData.Traffic/Models/GeoPoint.cs
Normal file
3
Schaad.OpenData.Traffic/Models/GeoPoint.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Models;
|
||||
|
||||
public readonly record struct GeoPoint(double Lat, double Lon);
|
||||
3
Schaad.OpenData.Traffic/Models/HourlyCount.cs
Normal file
3
Schaad.OpenData.Traffic/Models/HourlyCount.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Models;
|
||||
|
||||
public sealed record HourlyCount(int StationCode, string Direction, DateOnly Date, int Hour, VehicleCounts Counts);
|
||||
10
Schaad.OpenData.Traffic/Models/Station.cs
Normal file
10
Schaad.OpenData.Traffic/Models/Station.cs
Normal file
|
|
@ -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<string> Directions);
|
||||
3
Schaad.OpenData.Traffic/Models/StationGeometry.cs
Normal file
3
Schaad.OpenData.Traffic/Models/StationGeometry.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Models;
|
||||
|
||||
public sealed record StationGeometry(int StationCode, bool FollowsRoad, IReadOnlyList<DirectionGeometry> Directions);
|
||||
3
Schaad.OpenData.Traffic/Models/TrafficImport.cs
Normal file
3
Schaad.OpenData.Traffic/Models/TrafficImport.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Models;
|
||||
|
||||
public sealed record TrafficImport(IReadOnlyList<Station> Stations, IReadOnlyList<HourlyCount> Counts);
|
||||
15
Schaad.OpenData.Traffic/Models/VehicleClass.cs
Normal file
15
Schaad.OpenData.Traffic/Models/VehicleClass.cs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
namespace Schaad.OpenData.Traffic.Models;
|
||||
|
||||
public enum VehicleClass
|
||||
{
|
||||
Bus,
|
||||
Motorcycle,
|
||||
Car,
|
||||
CarWithTrailer,
|
||||
Van,
|
||||
VanWithTrailer,
|
||||
VanWithSemiTrailer,
|
||||
Truck,
|
||||
TruckWithTrailer,
|
||||
SemiTrailerTruck,
|
||||
}
|
||||
31
Schaad.OpenData.Traffic/Models/VehicleCounts.cs
Normal file
31
Schaad.OpenData.Traffic/Models/VehicleCounts.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
15
Schaad.OpenData.Traffic/Schaad.OpenData.Traffic.csproj
Normal file
15
Schaad.OpenData.Traffic/Schaad.OpenData.Traffic.csproj
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Schaad.OpenData.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
12
Schaad.OpenData.Traffic/Source/ThurgauCoordinates.cs
Normal file
12
Schaad.OpenData.Traffic/Source/ThurgauCoordinates.cs
Normal file
|
|
@ -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; }
|
||||
}
|
||||
32
Schaad.OpenData.Traffic/Source/ThurgauTrafficClient.cs
Normal file
32
Schaad.OpenData.Traffic/Source/ThurgauTrafficClient.cs
Normal file
|
|
@ -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<TrafficOptions> options)
|
||||
{
|
||||
public virtual async Task<TrafficImport> 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<ThurgauTrafficRecord>();
|
||||
await foreach (var record in JsonSerializer.DeserializeAsyncEnumerable<ThurgauTrafficRecord>(stream, cancellationToken: cancellationToken))
|
||||
{
|
||||
if (record is not null)
|
||||
{
|
||||
records.Add(record);
|
||||
}
|
||||
}
|
||||
|
||||
return ThurgauTrafficMapper.Map(records);
|
||||
}
|
||||
}
|
||||
77
Schaad.OpenData.Traffic/Source/ThurgauTrafficMapper.cs
Normal file
77
Schaad.OpenData.Traffic/Source/ThurgauTrafficMapper.cs
Normal file
|
|
@ -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<ThurgauTrafficRecord> records)
|
||||
{
|
||||
var counts = new List<HourlyCount>();
|
||||
var firstRecords = new Dictionary<int, ThurgauTrafficRecord>();
|
||||
var directions = new Dictionary<int, Dictionary<string, string>>();
|
||||
|
||||
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<string, string>(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();
|
||||
}
|
||||
63
Schaad.OpenData.Traffic/Source/ThurgauTrafficRecord.cs
Normal file
63
Schaad.OpenData.Traffic/Source/ThurgauTrafficRecord.cs
Normal file
|
|
@ -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; }
|
||||
}
|
||||
3
Schaad.OpenData.Traffic/Storage/TrafficCacheMeta.cs
Normal file
3
Schaad.OpenData.Traffic/Storage/TrafficCacheMeta.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Traffic.Storage;
|
||||
|
||||
public sealed record TrafficCacheMeta(DateTimeOffset? LastRefresh);
|
||||
74
Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs
Normal file
74
Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs
Normal file
|
|
@ -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<TrafficOptions> options)
|
||||
{
|
||||
private const string DayFormat = "yyyy-MM-dd";
|
||||
private const string GeometryFileName = "geometry-v7.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<TrafficSnapshot> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var stations = await ReadAsync<List<Station>>(Path.Combine(RootPath, "stations.json"), cancellationToken) ?? [];
|
||||
var geometry = await ReadAsync<List<StationGeometry>>(Path.Combine(RootPath, GeometryFileName), cancellationToken) ?? [];
|
||||
var meta = await ReadAsync<TrafficCacheMeta>(Path.Combine(RootPath, "meta.json"), cancellationToken);
|
||||
|
||||
var counts = new List<HourlyCount>();
|
||||
if (Directory.Exists(CountsPath))
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(CountsPath, "*.json").Order(StringComparer.Ordinal))
|
||||
{
|
||||
counts.AddRange(await ReadAsync<List<HourlyCount>>(file, cancellationToken) ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
return new TrafficSnapshot(stations, counts, geometry, meta?.LastRefresh);
|
||||
}
|
||||
|
||||
public virtual async Task SaveAsync(TrafficSnapshot snapshot, IReadOnlyCollection<DateOnly> 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<T?> ReadAsync<T>(string path, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
await using var stream = File.OpenRead(path);
|
||||
return await JsonSerializer.DeserializeAsync<T>(stream, JsonOptions, cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task WriteAsync<T>(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);
|
||||
}
|
||||
}
|
||||
10
Schaad.OpenData.Traffic/Storage/TrafficDataStore.cs
Normal file
10
Schaad.OpenData.Traffic/Storage/TrafficDataStore.cs
Normal file
|
|
@ -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;
|
||||
}
|
||||
58
Schaad.OpenData.Traffic/Storage/TrafficSnapshot.cs
Normal file
58
Schaad.OpenData.Traffic/Storage/TrafficSnapshot.cs
Normal file
|
|
@ -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<Station> stations,
|
||||
IEnumerable<HourlyCount> counts,
|
||||
IEnumerable<StationGeometry> 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<int, Station> Stations { get; }
|
||||
|
||||
public FrozenDictionary<DateOnly, ImmutableArray<HourlyCount>> CountsByDate { get; }
|
||||
|
||||
public FrozenDictionary<int, StationGeometry> Geometry { get; }
|
||||
|
||||
public ImmutableArray<DateOnly> Dates { get; }
|
||||
|
||||
public DateTimeOffset? LastRefresh { get; }
|
||||
|
||||
public TrafficSnapshot Merge(TrafficImport import, DateTimeOffset refreshedAt, out IReadOnlyList<DateOnly> 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<StationGeometry> 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);
|
||||
}
|
||||
}
|
||||
14
Schaad.OpenData.Traffic/TrafficOptions.cs
Normal file
14
Schaad.OpenData.Traffic/TrafficOptions.cs
Normal file
|
|
@ -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/";
|
||||
}
|
||||
44
Schaad.OpenData.Traffic/TrafficRefreshService.cs
Normal file
44
Schaad.OpenData.Traffic/TrafficRefreshService.cs
Normal file
|
|
@ -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<TrafficOptions> options,
|
||||
ILogger<TrafficRefreshService> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
74
Schaad.OpenData.Traffic/TrafficRefresher.cs
Normal file
74
Schaad.OpenData.Traffic/TrafficRefresher.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
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<TrafficRefresher> 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 stations = snapshot.Stations.Values.ToList();
|
||||
var missing = stations.Where(s => !snapshot.Geometry.ContainsKey(s.Code)).ToList();
|
||||
if (missing.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var built = new List<StationGeometry>();
|
||||
foreach (var station in missing)
|
||||
{
|
||||
try
|
||||
{
|
||||
built.Add(await geometryService.BuildAsync(station, stations, 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));
|
||||
}
|
||||
}
|
||||
|
|
@ -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<TrafficOptions>(configuration.GetSection(TrafficOptions.SectionName));
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.AddSingleton<TrafficDataStore>();
|
||||
services.AddSingleton<TrafficCacheStorage>();
|
||||
services.AddSingleton<StationGeometryService>();
|
||||
services.AddSingleton<TrafficRefresher>();
|
||||
services.AddHostedService<TrafficRefreshService>();
|
||||
|
||||
services.AddHttpClient<ThurgauTrafficClient>(client =>
|
||||
{
|
||||
client.Timeout = TimeSpan.FromMinutes(5);
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
|
||||
});
|
||||
services.AddHttpClient<SwisstopoClient>((provider, client) =>
|
||||
{
|
||||
client.BaseAddress = new Uri(provider.GetRequiredService<IOptions<TrafficOptions>>().Value.SwisstopoBaseUrl);
|
||||
client.Timeout = TimeSpan.FromSeconds(30);
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
6
client/.prettierrc.json
Normal file
6
client/.prettierrc.json
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"printWidth": 100,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
13
client/index.html
Normal file
13
client/index.html
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<!doctype html>
|
||||
<html lang="de-CH">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>OpenDataVisualizer</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
1878
client/package-lock.json
generated
Normal file
1878
client/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
31
client/package.json
Normal file
31
client/package.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"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",
|
||||
"react-router-dom": "^6.30.6"
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
1
client/public/favicon.svg
Normal file
1
client/public/favicon.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#1f2937"/><path d="M6 24 C12 20 14 10 26 8" stroke="#94a3b8" stroke-width="3" fill="none" stroke-linecap="round"/><circle cx="11" cy="20" r="2.6" fill="#3b82f6"/><circle cx="17" cy="14" r="2.6" fill="#f59e0b"/><circle cx="23" cy="9.5" r="2.6" fill="#3b82f6"/></svg>
|
||||
|
After Width: | Height: | Size: 368 B |
74
client/public/previews/traffic-thurgau.svg
Normal file
74
client/public/previews/traffic-thurgau.svg
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 450">
|
||||
<defs>
|
||||
<linearGradient id="land" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#eef2ec"/>
|
||||
<stop offset="1" stop-color="#e3e8e1"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="800" height="450" fill="url(#land)"/>
|
||||
<path d="M520 0 C560 60 640 90 800 70 L800 0 Z" fill="#cfe0ee"/>
|
||||
<path d="M590 0 C610 30 660 45 720 40 C760 37 790 30 800 25 L800 0 Z" fill="#bcd4e8"/>
|
||||
<path d="M0 330 C120 300 210 330 300 300 C380 272 420 300 520 290" fill="none" stroke="#d6dcd3" stroke-width="10"/>
|
||||
<g fill="none" stroke="#9aa5b1" stroke-linecap="round">
|
||||
<path d="M-20 260 C120 250 220 210 330 220 C450 230 520 180 640 170 C720 163 780 150 820 140" stroke-width="14"/>
|
||||
<path d="M140 470 C170 380 230 300 330 220 C400 165 430 100 470 -20" stroke-width="12"/>
|
||||
<path d="M330 220 C380 270 470 330 620 360 C700 375 760 400 820 420" stroke-width="10"/>
|
||||
<path d="M640 170 C650 230 640 300 620 360" stroke-width="8"/>
|
||||
</g>
|
||||
<g fill="none" stroke="#ffffff" stroke-width="1.5" stroke-dasharray="10 9" opacity="0.8">
|
||||
<path d="M-20 260 C120 250 220 210 330 220 C450 230 520 180 640 170 C720 163 780 150 820 140"/>
|
||||
<path d="M140 470 C170 380 230 300 330 220 C400 165 430 100 470 -20"/>
|
||||
</g>
|
||||
<g>
|
||||
<circle cx="40" cy="252" r="5" fill="#2563eb"/>
|
||||
<circle cx="78" cy="250" r="5" fill="#2563eb"/>
|
||||
<circle cx="105" cy="248" r="5.5" fill="#16a34a"/>
|
||||
<circle cx="150" cy="242" r="5" fill="#2563eb"/>
|
||||
<circle cx="196" cy="230" r="7" fill="#ea580c"/>
|
||||
<circle cx="232" cy="219" r="5" fill="#2563eb"/>
|
||||
<circle cx="268" cy="213" r="5" fill="#2563eb"/>
|
||||
<circle cx="300" cy="212" r="5" fill="#0d9488"/>
|
||||
<circle cx="60" cy="266" r="5" fill="#2563eb"/>
|
||||
<circle cx="128" cy="261" r="5" fill="#2563eb"/>
|
||||
<circle cx="170" cy="252" r="5" fill="#2563eb"/>
|
||||
<circle cx="250" cy="231" r="5.5" fill="#16a34a"/>
|
||||
<circle cx="290" cy="227" r="5" fill="#2563eb"/>
|
||||
<circle cx="372" cy="216" r="5" fill="#2563eb"/>
|
||||
<circle cx="420" cy="220" r="5" fill="#2563eb"/>
|
||||
<circle cx="470" cy="210" r="7" fill="#9333ea"/>
|
||||
<circle cx="520" cy="190" r="5" fill="#2563eb"/>
|
||||
<circle cx="566" cy="174" r="5" fill="#2563eb"/>
|
||||
<circle cx="612" cy="166" r="7" fill="#ea580c"/>
|
||||
<circle cx="690" cy="157" r="5" fill="#2563eb"/>
|
||||
<circle cx="740" cy="146" r="5" fill="#2563eb"/>
|
||||
<circle cx="398" cy="236" r="5" fill="#2563eb"/>
|
||||
<circle cx="448" cy="234" r="5" fill="#2563eb"/>
|
||||
<circle cx="545" cy="196" r="5.5" fill="#16a34a"/>
|
||||
<circle cx="660" cy="180" r="5" fill="#2563eb"/>
|
||||
<circle cx="720" cy="168" r="5" fill="#2563eb"/>
|
||||
<circle cx="168" cy="420" r="5" fill="#2563eb"/>
|
||||
<circle cx="190" cy="370" r="5" fill="#2563eb"/>
|
||||
<circle cx="228" cy="320" r="7" fill="#ea580c"/>
|
||||
<circle cx="270" cy="280" r="5" fill="#2563eb"/>
|
||||
<circle cx="388" cy="166" r="5" fill="#2563eb"/>
|
||||
<circle cx="414" cy="124" r="5.5" fill="#16a34a"/>
|
||||
<circle cx="440" cy="66" r="5" fill="#2563eb"/>
|
||||
<circle cx="200" cy="400" r="5" fill="#2563eb"/>
|
||||
<circle cx="246" cy="318" r="5" fill="#2563eb"/>
|
||||
<circle cx="372" cy="196" r="5" fill="#2563eb"/>
|
||||
<circle cx="402" cy="146" r="5" fill="#2563eb"/>
|
||||
<circle cx="380" cy="268" r="5" fill="#2563eb"/>
|
||||
<circle cx="440" cy="306" r="5" fill="#2563eb"/>
|
||||
<circle cx="520" cy="338" r="7" fill="#ea580c"/>
|
||||
<circle cx="590" cy="350" r="5" fill="#2563eb"/>
|
||||
<circle cx="700" cy="384" r="5" fill="#2563eb"/>
|
||||
<circle cx="648" cy="230" r="5" fill="#2563eb"/>
|
||||
<circle cx="640" cy="300" r="5.5" fill="#16a34a"/>
|
||||
</g>
|
||||
<g fill="#ffffff" stroke="#0f172a" stroke-width="3">
|
||||
<circle cx="330" cy="220" r="14"/>
|
||||
<circle cx="640" cy="170" r="11"/>
|
||||
<circle cx="620" cy="360" r="9"/>
|
||||
<circle cx="96" cy="256" r="8"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
13
client/src/App.tsx
Normal file
13
client/src/App.tsx
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { HomePage } from './pages/HomePage';
|
||||
import { TrafficThurgauPage } from './pages/TrafficThurgauPage';
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/verkehr/thurgau" element={<TrafficThurgauPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
86
client/src/api/traffic.ts
Normal file
86
client/src/api/traffic.ts
Normal file
|
|
@ -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<T>(url: string): Promise<T> {
|
||||
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<TrafficMeta>('/api/traffic/meta');
|
||||
|
||||
export const fetchStations = () => getJson<Station[]>('/api/traffic/stations');
|
||||
|
||||
export const fetchDay = (date: string) => getJson<DayView>(`/api/traffic/days/${date}`);
|
||||
|
||||
export const fetchStationSummary = (code: number) =>
|
||||
getJson<StationSummary>(`/api/traffic/stations/${code}/summary`);
|
||||
21
client/src/components/Legend.tsx
Normal file
21
client/src/components/Legend.tsx
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { GROUP_ORDER, VEHICLE_GROUPS } from '../traffic/vehicleClasses';
|
||||
|
||||
export function Legend() {
|
||||
return (
|
||||
<div className="legend">
|
||||
{GROUP_ORDER.map((group) => {
|
||||
const style = VEHICLE_GROUPS[group];
|
||||
return (
|
||||
<span key={group} className="legend-item">
|
||||
<span
|
||||
className="legend-dot"
|
||||
style={{ background: style.color, width: style.radius * 3, height: style.radius * 3 }}
|
||||
/>
|
||||
{style.label}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span className="legend-note">Punktdichte ∝ Fahrzeuge pro Stunde · Rechtsverkehr</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
290
client/src/components/StationPanel.tsx
Normal file
290
client/src/components/StationPanel.tsx
Normal file
|
|
@ -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 (
|
||||
<aside className="station-panel">
|
||||
<header className="station-panel-header">
|
||||
<div>
|
||||
<h2>{station.name}</h2>
|
||||
<p>
|
||||
{station.road} · {station.address}, {station.municipality} · Zählstelle {station.code}
|
||||
{!station.followsRoad && ' · Strassenverlauf geschätzt'}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="close-button" onClick={onClose} aria-label="Schliessen">
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h3>
|
||||
{day ? formatDate(day.date) : ''}, {HOUR_LABELS[hourIndex]}:00–
|
||||
{HOUR_LABELS[(hourIndex + 1) % 24]}:00
|
||||
</h3>
|
||||
<table className="class-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Fahrzeugklasse</th>
|
||||
{station.directions.map((direction, i) => (
|
||||
<th
|
||||
key={direction.name}
|
||||
style={{ color: DIRECTION_COLORS[i % DIRECTION_COLORS.length] }}
|
||||
>
|
||||
{direction.name}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{VEHICLE_CLASSES.map((vehicleClass, classIndex) => (
|
||||
<tr key={vehicleClass.label}>
|
||||
<td>
|
||||
<span
|
||||
className="legend-dot small"
|
||||
style={{ background: VEHICLE_GROUPS[vehicleClass.group].color }}
|
||||
/>
|
||||
{vehicleClass.label}
|
||||
</td>
|
||||
{station.directions.map((direction) => (
|
||||
<td key={direction.name}>
|
||||
{stationDay?.directions.find((d) => d.direction === direction.name)?.hours[
|
||||
hourIndex
|
||||
]?.[classIndex] ?? '–'}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
<tr className="total-row">
|
||||
<td>Total</td>
|
||||
{station.directions.map((direction) => (
|
||||
<td key={direction.name}>
|
||||
{formatNumber(
|
||||
sumCounts(
|
||||
stationDay?.directions.find((d) => d.direction === direction.name)?.hours[
|
||||
hourIndex
|
||||
],
|
||||
),
|
||||
)}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
{summaryQuery.isLoading && <p className="muted">Lade Auswertung…</p>}
|
||||
{summaryQuery.isError && <p className="error">Auswertung konnte nicht geladen werden.</p>}
|
||||
|
||||
{summary && (
|
||||
<>
|
||||
<section>
|
||||
<h3>
|
||||
Stundenwerte {formatDate(summary.from, { weekday: undefined })} –{' '}
|
||||
{formatDate(summary.to, { weekday: undefined })}
|
||||
</h3>
|
||||
<div className="chart chart-tall">
|
||||
<Line
|
||||
options={baseLineOptions}
|
||||
data={{
|
||||
labels: hourlyLabels,
|
||||
datasets: summary.directions.map((direction, i) => ({
|
||||
label: direction.direction,
|
||||
data: direction.hourly.map((h) => h.total),
|
||||
borderColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
|
||||
backgroundColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
|
||||
})),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Durchschnittlicher Tagesverlauf</h3>
|
||||
<div className="chart">
|
||||
<Line
|
||||
options={{
|
||||
...baseLineOptions,
|
||||
elements: {
|
||||
...baseLineOptions.elements,
|
||||
line: { borderWidth: 2, tension: 0.35 },
|
||||
},
|
||||
}}
|
||||
data={{
|
||||
labels: HOUR_LABELS,
|
||||
datasets: summary.directions.flatMap((direction, i) => [
|
||||
{
|
||||
label: `${direction.direction} (Mo–Fr)`,
|
||||
data: direction.weekdayProfile,
|
||||
borderColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
|
||||
backgroundColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
|
||||
},
|
||||
{
|
||||
label: `${direction.direction} (Sa–So)`,
|
||||
data: direction.weekendProfile,
|
||||
borderColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
|
||||
backgroundColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
|
||||
borderDash: [5, 4],
|
||||
},
|
||||
]),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Tagesverkehr</h3>
|
||||
<div className="chart">
|
||||
<Bar
|
||||
options={{
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: false,
|
||||
plugins: { legend: { position: 'bottom', labels: { boxWidth: 12 } } },
|
||||
scales: {
|
||||
x: { stacked: true, grid: { display: false } },
|
||||
y: {
|
||||
stacked: true,
|
||||
beginAtZero: true,
|
||||
grid: { color: '#e2e8f0' },
|
||||
title: { display: true, text: 'Fz/Tag' },
|
||||
},
|
||||
},
|
||||
}}
|
||||
data={{
|
||||
labels: dailyLabels,
|
||||
datasets: summary.directions.map((direction, i) => ({
|
||||
label: direction.direction,
|
||||
data: direction.daily.map((d) => d.total),
|
||||
backgroundColor: DIRECTION_COLORS[i % DIRECTION_COLORS.length],
|
||||
borderRadius: 2,
|
||||
})),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Fahrzeugklassen (Zeitraum gesamt)</h3>
|
||||
<div className="chart">
|
||||
<Bar
|
||||
options={{
|
||||
indexAxis: 'y',
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
callbacks: {
|
||||
label: (context) => {
|
||||
const total = sumCounts(summary.classTotals);
|
||||
const value = Number(context.raw);
|
||||
return `${formatNumber(value)} (${((value / Math.max(1, total)) * 100).toFixed(1)} %)`;
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
type: 'logarithmic',
|
||||
grid: { color: '#e2e8f0' },
|
||||
title: { display: true, text: 'Fahrzeuge (log)' },
|
||||
},
|
||||
y: { grid: { display: false } },
|
||||
},
|
||||
}}
|
||||
data={{
|
||||
labels: VEHICLE_CLASSES.map((c) => c.label),
|
||||
datasets: [
|
||||
{
|
||||
data: summary.classTotals,
|
||||
backgroundColor: VEHICLE_CLASSES.map((c) => VEHICLE_GROUPS[c.group].color),
|
||||
borderRadius: 2,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
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`;
|
||||
}
|
||||
99
client/src/components/TimeControls.tsx
Normal file
99
client/src/components/TimeControls.tsx
Normal file
|
|
@ -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 (
|
||||
<div className="time-controls">
|
||||
<button
|
||||
type="button"
|
||||
className="play-button"
|
||||
onClick={() => onPlayingChange(!playing)}
|
||||
aria-label={playing ? 'Pause' : 'Abspielen'}
|
||||
title={playing ? 'Pause' : 'Abspielen'}
|
||||
>
|
||||
{playing ? '❚❚' : '▶'}
|
||||
</button>
|
||||
|
||||
<div className="date-picker">
|
||||
<button
|
||||
type="button"
|
||||
disabled={index <= 0}
|
||||
onClick={() => onDateChange(dates[index - 1])}
|
||||
aria-label="Vorheriger Tag"
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
<select value={date} onChange={(e) => onDateChange(e.target.value)}>
|
||||
{dates.map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{formatDate(d)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
disabled={index < 0 || index >= dates.length - 1}
|
||||
onClick={() => onDateChange(dates[index + 1])}
|
||||
aria-label="Nächster Tag"
|
||||
>
|
||||
›
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="clock">{formatClock(time)}</div>
|
||||
|
||||
<input
|
||||
className="time-slider"
|
||||
type="range"
|
||||
min={0}
|
||||
max={23.99}
|
||||
step={0.05}
|
||||
value={time}
|
||||
onChange={(e) => onTimeChange(Number(e.target.value))}
|
||||
aria-label="Uhrzeit"
|
||||
/>
|
||||
|
||||
<select
|
||||
className="speed-select"
|
||||
value={hoursPerSecond}
|
||||
onChange={(e) => onSpeedChange(Number(e.target.value))}
|
||||
aria-label="Geschwindigkeit"
|
||||
>
|
||||
{SPEEDS.map((speed) => (
|
||||
<option key={speed.hoursPerSecond} value={speed.hoursPerSecond}>
|
||||
{speed.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
192
client/src/components/TrafficMap.tsx
Normal file
192
client/src/components/TrafficMap.tsx
Normal file
|
|
@ -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 =
|
||||
'© <a href="https://www.swisstopo.admin.ch/">swisstopo</a> · Daten: <a href="https://data.tg.ch/explore/dataset/dbu-tba-1/">Kanton Thurgau</a>';
|
||||
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<string, L.TileLayer> {
|
||||
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<HTMLDivElement>(null);
|
||||
const mapRef = useRef<L.Map | null>(null);
|
||||
const animatorRef = useRef<FlowAnimator | null>(null);
|
||||
const roadsRef = useRef<L.LayerGroup | null>(null);
|
||||
const markersRef = useRef<Map<number, L.CircleMarker>>(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(
|
||||
`<strong>${escapeHtml(station.name)}</strong><br/>` +
|
||||
`${escapeHtml(station.road)} · ${String(hourIndex).padStart(2, '0')}:00–${String(hourIndex + 1).padStart(2, '0')}:00<br/>` +
|
||||
perDirection
|
||||
.map((d) => `${escapeHtml(d.name)}: <strong>${d.total}</strong> Fz/h`)
|
||||
.join('<br/>'),
|
||||
{ direction: 'top', offset: [0, -6] },
|
||||
);
|
||||
}
|
||||
}, [stations, day, hour, selectedCode]);
|
||||
|
||||
return <div ref={containerRef} className="traffic-map" />;
|
||||
}
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
||||
}
|
||||
20
client/src/main.tsx
Normal file
20
client/src/main.tsx
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
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';
|
||||
import './styles.css';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { refetchOnWindowFocus: false, retry: 1 } },
|
||||
});
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
22
client/src/maps.ts
Normal file
22
client/src/maps.ts
Normal file
|
|
@ -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',
|
||||
},
|
||||
];
|
||||
47
client/src/pages/HomePage.tsx
Normal file
47
client/src/pages/HomePage.tsx
Normal file
|
|
@ -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 (
|
||||
<div className="home">
|
||||
<header className="home-header">
|
||||
<h1>OpenDataVisualizer</h1>
|
||||
<p>
|
||||
Karten und Visualisierungen zu offenen Daten der Schweiz von{' '}
|
||||
<a href="https://opendata.swiss" target="_blank" rel="noreferrer">
|
||||
opendata.swiss
|
||||
</a>
|
||||
.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<main className="map-tiles">
|
||||
{MAPS.map((map) => (
|
||||
<Link key={map.path} to={map.path} className="map-tile">
|
||||
<div className="map-tile-preview">
|
||||
<img src={map.preview} alt="" />
|
||||
</div>
|
||||
<div className="map-tile-body">
|
||||
<span className="map-tile-region">{map.region}</span>
|
||||
<h2>{map.title}</h2>
|
||||
<p>{map.description}</p>
|
||||
<div className="map-tile-tags">
|
||||
{map.tags.map((tag) => (
|
||||
<span key={tag} className="tag">
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<span className="map-tile-source">Quelle: {map.source}</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
187
client/src/pages/TrafficThurgauPage.tsx
Normal file
187
client/src/pages/TrafficThurgauPage.tsx
Normal file
|
|
@ -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<string | null>(null);
|
||||
const [time, setTime] = useState(INITIAL_TIME);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [hoursPerSecond, setHoursPerSecond] = useState(SPEEDS[1].hoursPerSecond);
|
||||
const [selectedCode, setSelectedCode] = useState<number | null>(null);
|
||||
const animatorRef = useRef<FlowAnimator | null>(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 (
|
||||
<div className={`app ${selectedStation ? 'with-panel' : ''}`}>
|
||||
<header className="app-header">
|
||||
<div className="title-row">
|
||||
<Link to="/" className="back-link" aria-label="Zur Übersicht" title="Zur Übersicht">
|
||||
←
|
||||
</Link>
|
||||
<div className="title">
|
||||
<h1>
|
||||
<Link to="/" className="brand-link">
|
||||
OpenDataVisualizer
|
||||
</Link>{' '}
|
||||
<span className="title-separator">/</span> Strassenverkehr Thurgau
|
||||
</h1>
|
||||
<span className="subtitle">Stündliche Zählungen nach Fahrzeugklassen</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="stats">
|
||||
<div>
|
||||
<span className="stat-value">{stations.length}</span>
|
||||
<span className="stat-label">Zählstellen</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="stat-value">{formatNumber(hourTotal)}</span>
|
||||
<span className="stat-label">Fahrzeuge in dieser Stunde</span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="map-area">
|
||||
<TrafficMap
|
||||
stations={stations}
|
||||
day={day}
|
||||
hour={hour}
|
||||
selectedCode={selectedCode}
|
||||
onSelect={setSelectedCode}
|
||||
onAnimatorReady={handleAnimatorReady}
|
||||
/>
|
||||
|
||||
<div className="overlay-bottom">
|
||||
{date && (
|
||||
<TimeControls
|
||||
dates={dates}
|
||||
date={date}
|
||||
time={time}
|
||||
playing={playing}
|
||||
hoursPerSecond={hoursPerSecond}
|
||||
onDateChange={setDate}
|
||||
onTimeChange={handleTimeChange}
|
||||
onPlayingChange={setPlaying}
|
||||
onSpeedChange={setHoursPerSecond}
|
||||
/>
|
||||
)}
|
||||
<Legend />
|
||||
</div>
|
||||
|
||||
{(metaQuery.isLoading || (metaQuery.data && dates.length === 0)) && (
|
||||
<div className="notice">
|
||||
Verkehrsdaten werden geladen… (erster Start lädt die Daten von data.tg.ch)
|
||||
</div>
|
||||
)}
|
||||
{error && <div className="notice error">Fehler beim Laden: {String(error.message)}</div>}
|
||||
</main>
|
||||
|
||||
{selectedStation && (
|
||||
<MemoStationPanel station={selectedStation} day={day} hour={hour} onClose={handleClose} />
|
||||
)}
|
||||
|
||||
<footer className="app-footer">
|
||||
Quelle:{' '}
|
||||
<a href={metaQuery.data?.sourceUrl} target="_blank" rel="noreferrer">
|
||||
{metaQuery.data?.publisher ?? 'Kanton Thurgau'}
|
||||
</a>{' '}
|
||||
· Lizenz {metaQuery.data?.license ?? 'CC0 1.0'}
|
||||
{metaQuery.data?.lastRefresh &&
|
||||
` · aktualisiert ${new Date(metaQuery.data.lastRefresh).toLocaleString('de-CH')}`}
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
522
client/src/styles.css
Normal file
522
client/src/styles.css
Normal file
|
|
@ -0,0 +1,522 @@
|
|||
: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;
|
||||
}
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
}
|
||||
294
client/src/traffic/flowAnimator.ts
Normal file
294
client/src/traffic/flowAnimator.ts
Normal file
|
|
@ -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<VehicleGroup, number> = {
|
||||
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<string, (number[] | null)[]>();
|
||||
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,
|
||||
};
|
||||
}
|
||||
20
client/src/traffic/format.ts
Normal file
20
client/src/traffic/format.ts
Normal file
|
|
@ -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');
|
||||
}
|
||||
41
client/src/traffic/vehicleClasses.ts
Normal file
41
client/src/traffic/vehicleClasses.ts
Normal file
|
|
@ -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<VehicleGroup, VehicleGroupStyle> = {
|
||||
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;
|
||||
}
|
||||
19
client/tsconfig.json
Normal file
19
client/tsconfig.json
Normal file
|
|
@ -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"]
|
||||
}
|
||||
16
client/vite.config.ts
Normal file
16
client/vite.config.ts
Normal file
|
|
@ -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,
|
||||
},
|
||||
});
|
||||
15
docker-compose.yml
Normal file
15
docker-compose.yml
Normal file
|
|
@ -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:
|
||||
Loading…
Reference in a new issue