From 81c3661687a39d52b7c97dd998d7f095fb66834a Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Fri, 6 Nov 2026 22:41:47 +0100 Subject: [PATCH] Add Thurgau vehicle stock map Choropleth of the 80 Thurgau municipalities from the road vehicle stock dataset (djs-stv-17): vehicles per 1000 inhabitants by vehicle group or share of a car brand among passenger cars, with year controls and a municipality panel. Population comes from sk-stat-56, outlines from swisstopo swissBOUNDARIES3D. Also fixes the broken ENV line in the Dockerfile. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 30 +- Dockerfile | 6 +- OpenDataVisualizer.sln | 14 + README.md | 9 + Schaad.OpenData.Server/Program.cs | 4 + .../Schaad.OpenData.Server.csproj | 1 + .../Vehicles/VehicleEndpoints.cs | 35 ++ .../Vehicles/VehicleMetaResponse.cs | 15 + Schaad.OpenData.Server/appsettings.json | 4 + .../MunicipalityBoundaryClientTestShould.cs | 62 ++++ .../Schaad.OpenData.Tests.csproj | 1 + .../ThurgauVehicleClientTestShould.cs | 81 +++++ .../VehicleAnalysisTestShould.cs | 95 ++++++ .../VehicleCacheStorageTestShould.cs | 62 ++++ .../VehicleRefresherTestShould.cs | 88 +++++ Schaad.OpenData.Tests/VehicleTestData.cs | 19 ++ .../Analysis/AreaSummary.cs | 11 + .../Analysis/MunicipalityShape.cs | 3 + .../Analysis/VehicleAnalysis.cs | 139 ++++++++ .../Analysis/VehicleOverview.cs | 7 + .../Analysis/VehicleTypeInfo.cs | 3 + .../Analysis/VehicleYearInfo.cs | 3 + .../Analysis/VehicleYearView.cs | 7 + .../Models/DatasetVersion.cs | 3 + .../Models/MunicipalityOutline.cs | 3 + .../Models/PopulationEntry.cs | 3 + Schaad.OpenData.Vehicles/Models/StockEntry.cs | 11 + .../Schaad.OpenData.Vehicles.csproj | 15 + .../Source/MunicipalityBoundaryClient.cs | 50 +++ .../Source/ThurgauPopulationRecord.cs | 15 + .../Source/ThurgauStockRecord.cs | 30 ++ .../Source/ThurgauVehicleClient.cs | 53 +++ .../Source/ThurgauVehicleMapper.cs | 42 +++ .../Storage/VehicleCacheMeta.cs | 5 + .../Storage/VehicleCacheStorage.cs | 65 ++++ .../Storage/VehicleDataStore.cs | 10 + .../Storage/VehicleSnapshot.cs | 16 + Schaad.OpenData.Vehicles/VehicleOptions.cs | 19 ++ .../VehicleRefreshService.cs | 42 +++ Schaad.OpenData.Vehicles/VehicleRefresher.cs | 75 ++++ .../VehicleServiceCollectionExtensions.cs | 35 ++ client/public/previews/vehicles-thurgau.svg | 40 +++ client/src/App.tsx | 2 + client/src/api/vehicles.ts | 64 ++++ .../components/vehicles/MetricControls.tsx | 147 ++++++++ .../components/vehicles/MunicipalityPanel.tsx | 323 ++++++++++++++++++ client/src/components/vehicles/VehicleMap.tsx | 139 ++++++++ .../components/watercraft/YearControls.tsx | 3 +- client/src/maps.ts | 10 + client/src/pages/VehiclesThurgauPage.tsx | 210 ++++++++++++ client/src/styles.css | 65 ++++ client/src/vehicles/metrics.ts | 111 ++++++ 52 files changed, 2296 insertions(+), 9 deletions(-) create mode 100644 Schaad.OpenData.Server/Vehicles/VehicleEndpoints.cs create mode 100644 Schaad.OpenData.Server/Vehicles/VehicleMetaResponse.cs create mode 100644 Schaad.OpenData.Tests/MunicipalityBoundaryClientTestShould.cs create mode 100644 Schaad.OpenData.Tests/ThurgauVehicleClientTestShould.cs create mode 100644 Schaad.OpenData.Tests/VehicleAnalysisTestShould.cs create mode 100644 Schaad.OpenData.Tests/VehicleCacheStorageTestShould.cs create mode 100644 Schaad.OpenData.Tests/VehicleRefresherTestShould.cs create mode 100644 Schaad.OpenData.Tests/VehicleTestData.cs create mode 100644 Schaad.OpenData.Vehicles/Analysis/AreaSummary.cs create mode 100644 Schaad.OpenData.Vehicles/Analysis/MunicipalityShape.cs create mode 100644 Schaad.OpenData.Vehicles/Analysis/VehicleAnalysis.cs create mode 100644 Schaad.OpenData.Vehicles/Analysis/VehicleOverview.cs create mode 100644 Schaad.OpenData.Vehicles/Analysis/VehicleTypeInfo.cs create mode 100644 Schaad.OpenData.Vehicles/Analysis/VehicleYearInfo.cs create mode 100644 Schaad.OpenData.Vehicles/Analysis/VehicleYearView.cs create mode 100644 Schaad.OpenData.Vehicles/Models/DatasetVersion.cs create mode 100644 Schaad.OpenData.Vehicles/Models/MunicipalityOutline.cs create mode 100644 Schaad.OpenData.Vehicles/Models/PopulationEntry.cs create mode 100644 Schaad.OpenData.Vehicles/Models/StockEntry.cs create mode 100644 Schaad.OpenData.Vehicles/Schaad.OpenData.Vehicles.csproj create mode 100644 Schaad.OpenData.Vehicles/Source/MunicipalityBoundaryClient.cs create mode 100644 Schaad.OpenData.Vehicles/Source/ThurgauPopulationRecord.cs create mode 100644 Schaad.OpenData.Vehicles/Source/ThurgauStockRecord.cs create mode 100644 Schaad.OpenData.Vehicles/Source/ThurgauVehicleClient.cs create mode 100644 Schaad.OpenData.Vehicles/Source/ThurgauVehicleMapper.cs create mode 100644 Schaad.OpenData.Vehicles/Storage/VehicleCacheMeta.cs create mode 100644 Schaad.OpenData.Vehicles/Storage/VehicleCacheStorage.cs create mode 100644 Schaad.OpenData.Vehicles/Storage/VehicleDataStore.cs create mode 100644 Schaad.OpenData.Vehicles/Storage/VehicleSnapshot.cs create mode 100644 Schaad.OpenData.Vehicles/VehicleOptions.cs create mode 100644 Schaad.OpenData.Vehicles/VehicleRefreshService.cs create mode 100644 Schaad.OpenData.Vehicles/VehicleRefresher.cs create mode 100644 Schaad.OpenData.Vehicles/VehicleServiceCollectionExtensions.cs create mode 100644 client/public/previews/vehicles-thurgau.svg create mode 100644 client/src/api/vehicles.ts create mode 100644 client/src/components/vehicles/MetricControls.tsx create mode 100644 client/src/components/vehicles/MunicipalityPanel.tsx create mode 100644 client/src/components/vehicles/VehicleMap.tsx create mode 100644 client/src/pages/VehiclesThurgauPage.tsx create mode 100644 client/src/vehicles/metrics.ts diff --git a/CLAUDE.md b/CLAUDE.md index 2223c0e..954c1c7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,17 +28,19 @@ There is no lint step besides `tsc` (strict, no unused locals/parameters). `dotn ## Architecture -Visualizes open data from opendata.swiss. Two datasets so far, both from the canton of Thurgau on data.tg.ch: +Visualizes open data from opendata.swiss. Three datasets so far, all from the canton of Thurgau on data.tg.ch: - hourly traffic counts by vehicle class (`dbu-tba-1`, CC0): 64 counting stations, each with exactly two directions, 10 vehicle classes (SWISS10) - registered watercraft (one dataset per year, `djs-kpo-5/8/7/9/10` for 2021–2025, CC BY 4.0): ~7000 boats, one row per boat with location (harbour village or `ohne festen Standort`), type, propulsion, fuel, emission group, length and power +- road vehicle stock (`djs-stv-17`, CC BY 4.0, yearly from 2023): count per municipality (BFS number), vehicle group, vehicle type and brand at 31.12.; brands with fewer than 5 vehicles per municipality and type are folded into `Andere`. Population per municipality comes from `sk-stat-56` | Project | Role | |---|---| | `Schaad.OpenData.Traffic` | Fetching, JSON cache, road geometry, analysis — everything except HTTP hosting | | `Schaad.OpenData.Watercraft` | Watercraft: catalog lookup, JSON cache, aggregation per location | -| `Schaad.OpenData.Server` | Minimal API (`/api/traffic/*` in `Traffic/TrafficEndpoints.cs`, `/api/watercraft/*` in `Watercraft/WatercraftEndpoints.cs`), serves the built client from `wwwroot` with SPA fallback | -| `Schaad.OpenData.Tests` | Tests for the Traffic and Watercraft libraries | +| `Schaad.OpenData.Vehicles` | Vehicle stock: dataset fetch, municipality boundaries, JSON cache, aggregation per municipality | +| `Schaad.OpenData.Server` | Minimal API (`/api/traffic/*` in `Traffic/TrafficEndpoints.cs`, `/api/watercraft/*` in `Watercraft/WatercraftEndpoints.cs`, `/api/vehicles/*` in `Vehicles/VehicleEndpoints.cs`), serves the built client from `wwwroot` with SPA fallback | +| `Schaad.OpenData.Tests` | Tests for the Traffic, Watercraft and Vehicles libraries | | `client/` | React SPA: Leaflet map with animated traffic, Chart.js station charts | ### Data flow @@ -54,7 +56,7 @@ TrafficRefreshService (BackgroundService, checks every 15 min) → 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` and `Watercraft` in `appsettings.json` (`Traffic__DataPath=/app/data` and `Watercraft__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. +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`, `Watercraft` and `Vehicles` in `appsettings.json` (`Traffic__DataPath`, `Watercraft__DataPath` and `Vehicles__DataPath` are `/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) @@ -82,17 +84,33 @@ WatercraftRefreshService (BackgroundService, checks every 30 min, refreshes dail The source has no coordinates. `WatercraftLocations` maps each location name to a point on the shore (village point from the swisstopo gazetteer snapped to the nearest Bodensee/Untersee shoreline and pushed 150 m into the lake, or onto the Rhine). An unknown name gets no position and is listed beside the map instead of on it. Missing values become categories (`Ohne Motor`, `Keine Angabe`, `Ohne besondere Verwendung`), which the client draws in grey. +### Vehicle stock + +``` +VehicleRefreshService (BackgroundService, checks every 30 min, refreshes daily) + → VehicleRefresher + → ThurgauVehicleClient.GetVersionAsync catalog `modified` of djs-stv-17 and sk-stat-56; a dataset is only re-exported when it changed + → ThurgauVehicleClient.FetchStockAsync / FetchPopulationAsync + → MunicipalityBoundaryClient.FetchAsync swissBOUNDARIES3D outline per BFS number (api3.geo.admin.ch, WGS84, rounded to 5 decimals), only for municipalities without a cached outline + → VehicleCacheStorage {DataPath}/vehicles/thurgau/{meta.json, stock.json, population.json, outlines-v1.json} + → VehicleDataStore + → VehicleAnalysis groups/types/brands ordered by frequency over all years (count arrays in the API are positional), per municipality and canton: counts per group, type and passenger-car brand plus population; missing population years fall back to the latest earlier year +``` + +Brand counts only include the group `Personenwagen`, with `Andere` always last. When the outline processing changes, bump `OutlinesFileName` in `VehicleCacheStorage`. + ### 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`, `/schifffahrt/thurgau?jahr=2023` → `pages/WatercraftThurgauPage.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`. +- 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`, `/schifffahrt/thurgau?jahr=2023` → `pages/WatercraftThurgauPage.tsx`, `/fahrzeuge/thurgau?jahr=2025` → `pages/VehiclesThurgauPage.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. - Watercraft page: `components/watercraft/WatercraftMap.tsx` draws one SVG donut per location (area ∝ boats, segments by the selected dimension); markers are created once and resized in place, so year changes animate via CSS. `watercraft/categories.ts` folds categories into at most six coloured groups plus grey `Übrige` and grey "absent" groups; legend chips hide groups, which shrinks the donuts. The panel shows the canton or the selected location for the selected year plus a stacked trend over all years. +- Vehicle page: `components/vehicles/VehicleMap.tsx` draws a choropleth of the municipality outlines (polygons created once, restyled in place). `vehicles/metrics.ts` defines the metric (vehicles per 1000 inhabitants for all or one group, or a brand's share of passenger cars) and a 7-class quantile scale computed over all years, so colours stay comparable while playing through the years. `YearControls` is shared with the watercraft page. - UI language is German (de-CH). Base maps (shared in `map/baseLayers.ts`) 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`, `ThurgauWatercraftClient`, `WatercraftCacheStorage`) use `virtual` methods instead of single-implementation interfaces. +- Classes that tests need to mock (`SwisstopoClient`, `StationGeometryService`, `ThurgauTrafficClient`, `TrafficCacheStorage`, `ThurgauWatercraftClient`, `WatercraftCacheStorage`, `ThurgauVehicleClient`, `MunicipalityBoundaryClient`, `VehicleCacheStorage`) use `virtual` methods instead of single-implementation interfaces. - Tests: one `TestShould` class per subject, method names `DoThisWhenThat`, Shouldly assertions (no `Assert.*`). HTTP clients are tested with a stub `HttpMessageHandler`, storage with a temp directory cleaned up in `Dispose`. - TypeScript: Prettier config in `client/.prettierrc.json` (single quotes, width 100). diff --git a/Dockerfile b/Dockerfile index 9a0f191..4a277d8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,10 +13,12 @@ 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/ COPY Schaad.OpenData.Watercraft/Schaad.OpenData.Watercraft.csproj Schaad.OpenData.Watercraft/ +COPY Schaad.OpenData.Vehicles/Schaad.OpenData.Vehicles.csproj Schaad.OpenData.Vehicles/ 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 Schaad.OpenData.Watercraft/ Schaad.OpenData.Watercraft/ +COPY Schaad.OpenData.Vehicles/ Schaad.OpenData.Vehicles/ 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 @@ -27,7 +29,9 @@ 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 \n Watercraft__DataPath=/app/data + Traffic__DataPath=/app/data \ + Watercraft__DataPath=/app/data \ + Vehicles__DataPath=/app/data VOLUME /app/data EXPOSE 8080 ENTRYPOINT ["dotnet", "Schaad.OpenData.Server.dll"] diff --git a/OpenDataVisualizer.sln b/OpenDataVisualizer.sln index 8e00a32..5c770cf 100644 --- a/OpenDataVisualizer.sln +++ b/OpenDataVisualizer.sln @@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Tests", "Sc EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Watercraft", "Schaad.OpenData.Watercraft\Schaad.OpenData.Watercraft.csproj", "{2E246A08-6B29-450D-A2C5-997D14B38709}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Vehicles", "Schaad.OpenData.Vehicles\Schaad.OpenData.Vehicles.csproj", "{CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -69,6 +71,18 @@ Global {2E246A08-6B29-450D-A2C5-997D14B38709}.Release|x64.Build.0 = Release|Any CPU {2E246A08-6B29-450D-A2C5-997D14B38709}.Release|x86.ActiveCfg = Release|Any CPU {2E246A08-6B29-450D-A2C5-997D14B38709}.Release|x86.Build.0 = Release|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Debug|x64.ActiveCfg = Debug|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Debug|x64.Build.0 = Debug|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Debug|x86.ActiveCfg = Debug|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Debug|x86.Build.0 = Debug|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Release|Any CPU.Build.0 = Release|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Release|x64.ActiveCfg = Release|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Release|x64.Build.0 = Release|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Release|x86.ActiveCfg = Release|Any CPU + {CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/README.md b/README.md index fc064bc..9baa858 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,15 @@ The second visualization shows the boats registered with the Thurgau navigation - year controls to compare or play through the years - panel for the canton or a location: change against the previous year, median length and power, share requiring a licence, category table, trend over all years, length and power distribution +## Road vehicles in the canton of Thurgau + +The third visualization shows all road vehicles registered in Thurgau per municipality +([Strassenfahrzeugbestand nach Fahrzeuggruppe, Fahrzeugart, Marke und Politischer Gemeinde ab 2023](https://opendata.swiss/de/dataset/strassenfahrzeugbestand-nach-fahrzeuggruppe-fahrzeugart-marke-und-politischer-gemeinde-ab-2023), CC BY 4.0), combined with the resident population per municipality from the Thurgau statistics office: + +- choropleth map of the 80 municipalities (outlines from swisstopo swissBOUNDARIES3D): vehicles per 1000 inhabitants for all vehicles or one vehicle group, or the share of a car brand among all passenger cars +- year controls to compare or play through the years, with a colour scale that stays fixed across years +- panel for the canton or a municipality: change against the previous year, population, density and rank, vehicle groups, most common car brands and vehicle types, trend over all years + ## Run ```bash diff --git a/Schaad.OpenData.Server/Program.cs b/Schaad.OpenData.Server/Program.cs index b8f5a40..18ccca9 100644 --- a/Schaad.OpenData.Server/Program.cs +++ b/Schaad.OpenData.Server/Program.cs @@ -1,12 +1,15 @@ using Schaad.OpenData.Server.Traffic; +using Schaad.OpenData.Server.Vehicles; using Schaad.OpenData.Server.Watercraft; using Schaad.OpenData.Traffic; +using Schaad.OpenData.Vehicles; using Schaad.OpenData.Watercraft; var builder = WebApplication.CreateBuilder(args); builder.Services.AddTraffic(builder.Configuration); builder.Services.AddWatercraft(builder.Configuration); +builder.Services.AddVehicles(builder.Configuration); builder.Services.AddResponseCompression(options => options.EnableForHttps = true); var app = builder.Build(); @@ -16,6 +19,7 @@ app.UseDefaultFiles(); app.UseStaticFiles(); app.MapTrafficEndpoints(); app.MapWatercraftEndpoints(); +app.MapVehicleEndpoints(); app.MapFallbackToFile("index.html"); app.Run(); diff --git a/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj b/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj index 802b3b0..4ab20dc 100644 --- a/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj +++ b/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj @@ -2,6 +2,7 @@ + diff --git a/Schaad.OpenData.Server/Vehicles/VehicleEndpoints.cs b/Schaad.OpenData.Server/Vehicles/VehicleEndpoints.cs new file mode 100644 index 0000000..148ad2f --- /dev/null +++ b/Schaad.OpenData.Server/Vehicles/VehicleEndpoints.cs @@ -0,0 +1,35 @@ +using Schaad.OpenData.Vehicles.Analysis; +using Schaad.OpenData.Vehicles.Storage; + +namespace Schaad.OpenData.Server.Vehicles; + +public static class VehicleEndpoints +{ + public static IEndpointRouteBuilder MapVehicleEndpoints(this IEndpointRouteBuilder endpoints) + { + var group = endpoints.MapGroup("/api/vehicles"); + + group.MapGet("/meta", (VehicleDataStore store) => + { + var snapshot = store.Current; + var overview = VehicleAnalysis.BuildOverview(snapshot); + return new VehicleMetaResponse( + "Strassenfahrzeugbestand nach Fahrzeuggruppe, Fahrzeugart, Marke und Politischer Gemeinde ab 2023", + "Strassenverkehrsamt Kanton Thurgau (data.tg.ch / opendata.swiss)", + "https://opendata.swiss/de/dataset/strassenfahrzeugbestand-nach-fahrzeuggruppe-fahrzeugart-marke-und-politischer-gemeinde-ab-2023", + "CC BY 4.0", + "https://data.tg.ch/explore/dataset/sk-stat-56/", + overview.Years, + overview.Groups, + overview.Types, + overview.Brands, + snapshot.LastRefresh); + }); + + group.MapGet("/years", (VehicleDataStore store) => VehicleAnalysis.BuildYears(store.Current)); + + group.MapGet("/municipalities", (VehicleDataStore store) => VehicleAnalysis.BuildShapes(store.Current)); + + return endpoints; + } +} diff --git a/Schaad.OpenData.Server/Vehicles/VehicleMetaResponse.cs b/Schaad.OpenData.Server/Vehicles/VehicleMetaResponse.cs new file mode 100644 index 0000000..f9cad7f --- /dev/null +++ b/Schaad.OpenData.Server/Vehicles/VehicleMetaResponse.cs @@ -0,0 +1,15 @@ +using Schaad.OpenData.Vehicles.Analysis; + +namespace Schaad.OpenData.Server.Vehicles; + +public sealed record VehicleMetaResponse( + string Title, + string Publisher, + string SourceUrl, + string License, + string PopulationSourceUrl, + IReadOnlyList Years, + IReadOnlyList Groups, + IReadOnlyList Types, + IReadOnlyList Brands, + DateTimeOffset? LastRefresh); diff --git a/Schaad.OpenData.Server/appsettings.json b/Schaad.OpenData.Server/appsettings.json index 4fa3e37..d691e90 100644 --- a/Schaad.OpenData.Server/appsettings.json +++ b/Schaad.OpenData.Server/appsettings.json @@ -14,5 +14,9 @@ "Watercraft": { "DataPath": "../data", "RefreshInterval": "1.00:00:00" + }, + "Vehicles": { + "DataPath": "../data", + "RefreshInterval": "1.00:00:00" } } diff --git a/Schaad.OpenData.Tests/MunicipalityBoundaryClientTestShould.cs b/Schaad.OpenData.Tests/MunicipalityBoundaryClientTestShould.cs new file mode 100644 index 0000000..7f87d5a --- /dev/null +++ b/Schaad.OpenData.Tests/MunicipalityBoundaryClientTestShould.cs @@ -0,0 +1,62 @@ +using System.Net; +using System.Text; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Vehicles; +using Schaad.OpenData.Vehicles.Source; + +namespace Schaad.OpenData.Tests; + +public class MunicipalityBoundaryClientTestShould +{ + private sealed class StubHandler(HttpStatusCode status, string body) : HttpMessageHandler + { + public List Requests { get; } = []; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request.RequestUri!); + return Task.FromResult(new HttpResponseMessage(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }); + } + } + + private static MunicipalityBoundaryClient Client(StubHandler handler) => + new(new HttpClient(handler), Options.Create(new VehicleOptions { BoundaryUrl = "https://geo.example/boundaries" })); + + [Fact] + public async Task ReturnRoundedPolygonsWhenFeatureIsMultiPolygon() + { + var body = """ + {"feature":{"type":"Feature","id":"4566","geometry":{"type":"MultiPolygon","coordinates":[ + [[[8.887602,47.528387],[8.88636,47.527927],[8.886348,47.527906],[8.887602,47.528387]]], + [[[8.9,47.5],[8.91,47.5],[8.91,47.51],[8.9,47.5]]] + ]}}} + """; + var handler = new StubHandler(HttpStatusCode.OK, body); + + var outline = await Client(handler).FetchAsync("4566", CancellationToken.None); + + handler.Requests.ShouldHaveSingleItem().AbsoluteUri.ShouldBe("https://geo.example/boundaries/4566?geometryFormat=geojson&sr=4326"); + outline.ShouldNotBeNull(); + outline.Id.ShouldBe("4566"); + outline.Polygons.Length.ShouldBe(2); + outline.Polygons[0][0][0].ShouldBe([8.8876, 47.52839]); + } + + [Fact] + public async Task ReturnSinglePolygonWhenFeatureIsPolygon() + { + var body = """{"feature":{"geometry":{"type":"Polygon","coordinates":[[[8.9,47.5],[8.91,47.5],[8.91,47.51],[8.9,47.5]]]}}}"""; + + var outline = await Client(new StubHandler(HttpStatusCode.OK, body)).FetchAsync("4401", CancellationToken.None); + + outline.ShouldNotBeNull().Polygons.ShouldHaveSingleItem().ShouldHaveSingleItem().Length.ShouldBe(4); + } + + [Fact] + public async Task ReturnNullWhenMunicipalityIsUnknown() + { + var outline = await Client(new StubHandler(HttpStatusCode.NotFound, "{}")).FetchAsync("1", CancellationToken.None); + + outline.ShouldBeNull(); + } +} diff --git a/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj b/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj index 45c8530..d3630ab 100644 --- a/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj +++ b/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj @@ -20,6 +20,7 @@ + diff --git a/Schaad.OpenData.Tests/ThurgauVehicleClientTestShould.cs b/Schaad.OpenData.Tests/ThurgauVehicleClientTestShould.cs new file mode 100644 index 0000000..e6a5a1c --- /dev/null +++ b/Schaad.OpenData.Tests/ThurgauVehicleClientTestShould.cs @@ -0,0 +1,81 @@ +using System.Net; +using System.Text; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Vehicles; +using Schaad.OpenData.Vehicles.Models; +using Schaad.OpenData.Vehicles.Source; + +namespace Schaad.OpenData.Tests; + +public class ThurgauVehicleClientTestShould +{ + private sealed class StubHandler(string body) : HttpMessageHandler + { + public List Requests { get; } = []; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request.RequestUri!); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, "application/json") }); + } + } + + private static ThurgauVehicleClient Client(StubHandler handler) => + new(new HttpClient(handler), Options.Create(new VehicleOptions + { + CatalogUrl = "https://data.example/catalog/datasets", + StockDatasetId = "djs-stv-17", + PopulationDatasetId = "sk-stat-56", + })); + + [Fact] + public async Task ReadModifiedDateWhenGettingVersion() + { + var handler = new StubHandler("""{"dataset_id":"djs-stv-17","metas":{"default":{"title":"Strassenfahrzeugbestand","modified":"2026-09-17T16:54:34+00:00"}}}"""); + + var version = await Client(handler).GetVersionAsync("djs-stv-17", CancellationToken.None); + + version.ShouldBe(new DatasetVersion("djs-stv-17", new DateTimeOffset(2026, 9, 17, 16, 54, 34, TimeSpan.Zero))); + handler.Requests.ShouldHaveSingleItem().AbsoluteUri.ShouldBe("https://data.example/catalog/datasets/djs-stv-17"); + } + + [Fact] + public async Task MapRecordsAndSkipEmptyRowsWhenFetchingStock() + { + var body = """ + [ + {"jahr":"2023","bfs_nr_gemeinde":"4401","gemeinde":"Arbon","bfs_nr_bezirk":"2011","bezirk":"Arbon","fahrzeuggruppe":"Personenwagen","fahrzeugart":"Personenwagen","code_fz_art":1,"marke":"TESLA","anzahl":12}, + {"jahr":"2024-01-01","bfs_nr_gemeinde":"4401","gemeinde":"Arbon","bezirk":"Arbon","fahrzeuggruppe":"Anhänger","fahrzeugart":"Wohnanhänger","marke":" ","anzahl":3}, + {"jahr":"2024","bfs_nr_gemeinde":"4401","gemeinde":"Arbon","fahrzeuggruppe":"Anhänger","fahrzeugart":"Wohnanhänger","marke":"KNAUS","anzahl":0}, + {"jahr":null,"bfs_nr_gemeinde":"4401","anzahl":5} + ] + """; + var handler = new StubHandler(body); + + var stock = await Client(handler).FetchStockAsync(CancellationToken.None); + + handler.Requests.ShouldHaveSingleItem().AbsoluteUri.ShouldBe("https://data.example/catalog/datasets/djs-stv-17/exports/json"); + stock.ShouldBe( + [ + new StockEntry(2023, "4401", "Arbon", "Arbon", "Personenwagen", "Personenwagen", "TESLA", 12), + new StockEntry(2024, "4401", "Arbon", "Arbon", "Anhänger", "Wohnanhänger", "Andere", 3), + ]); + } + + [Fact] + public async Task ParseTextCountsWhenFetchingPopulation() + { + var body = """ + [ + {"bfs_nr_gemeinde":"4406","gemeinde_name":"Dozwil","jahr":"2025","anzahl_personen":"717"}, + {"bfs_nr_gemeinde":"4421","gemeinde_name":"Horn","jahr":"2025","anzahl_personen":""} + ] + """; + var handler = new StubHandler(body); + + var population = await Client(handler).FetchPopulationAsync(CancellationToken.None); + + handler.Requests.ShouldHaveSingleItem().AbsoluteUri.ShouldBe("https://data.example/catalog/datasets/sk-stat-56/exports/json"); + population.ShouldBe([new PopulationEntry(2025, "4406", 717)]); + } +} diff --git a/Schaad.OpenData.Tests/VehicleAnalysisTestShould.cs b/Schaad.OpenData.Tests/VehicleAnalysisTestShould.cs new file mode 100644 index 0000000..f98ea61 --- /dev/null +++ b/Schaad.OpenData.Tests/VehicleAnalysisTestShould.cs @@ -0,0 +1,95 @@ +using System.Text.Json; +using Schaad.OpenData.Vehicles.Analysis; +using Schaad.OpenData.Vehicles.Models; +using Schaad.OpenData.Vehicles.Storage; +using static Schaad.OpenData.Tests.VehicleTestData; + +namespace Schaad.OpenData.Tests; + +public class VehicleAnalysisTestShould +{ + private static VehicleSnapshot Snapshot(IReadOnlyList stock, IReadOnlyList? population = null) => + new(stock, population ?? [], [Outline("4566"), Outline("4671"), Outline("9999")], null, null, null); + + [Fact] + public void OrderGroupsTypesAndBrandsByFrequencyWhenBuildingOverview() + { + var snapshot = Snapshot( + [ + Entry(brand: "Andere", count: 50), + Entry(brand: "VW", count: 20), + Entry(brand: "TESLA", count: 30), + Entry(group: "Motorräder", type: "Motorrad", brand: "HONDA", count: 25), + Entry(group: "Motorräder", type: "Kleinmotorrad", brand: "Andere", count: 5), + ]); + + var overview = VehicleAnalysis.BuildOverview(snapshot); + + overview.Groups.ShouldBe(["Personenwagen", "Motorräder"]); + overview.Types.ShouldBe([new("Personenwagen", "Personenwagen"), new("Motorrad", "Motorräder"), new("Kleinmotorrad", "Motorräder")]); + overview.Brands.ShouldBe(["TESLA", "VW", "Andere"]); + } + + [Fact] + public void SumCountsAndPopulationPerYearWhenBuildingOverview() + { + var snapshot = Snapshot( + [Entry(2023, count: 10), Entry(2024, count: 12), Entry(2024, "4671", "Kreuzlingen", count: 8)], + [new(2023, "4566", 26000), new(2023, "4671", 22000), new(2024, "4566", 26500)]); + + var overview = VehicleAnalysis.BuildOverview(snapshot); + + overview.Years.ShouldBe( + [ + new(2023, new DateOnly(2023, 12, 31), 10, 48000), + new(2024, new DateOnly(2024, 12, 31), 20, 48500), + ]); + } + + [Fact] + public void CountGroupsTypesAndPassengerCarBrandsPerMunicipalityWhenBuildingYears() + { + var snapshot = Snapshot( + [ + Entry(brand: "VW", count: 30), + Entry(brand: "TESLA", count: 5), + Entry(group: "Motorräder", type: "Motorrad", brand: "VW", count: 4), + Entry(id: "4671", municipality: "Kreuzlingen", brand: "VW", count: 7), + ], + [new(2024, "4566", 1000), new(2024, "4671", 700)]); + + var year = VehicleAnalysis.BuildYears(snapshot).ShouldHaveSingleItem(); + + year.Year.ShouldBe(2024); + year.Municipalities.Select(m => m.Name).ShouldBe(["Frauenfeld", "Kreuzlingen"]); + var frauenfeld = year.Municipalities[0]; + frauenfeld.Population.ShouldBe(1000); + frauenfeld.Count.ShouldBe(39); + frauenfeld.Groups.ShouldBe([35, 4]); + frauenfeld.Types.ShouldBe([35, 4]); + frauenfeld.Brands.ShouldBe([30, 5]); + year.Canton.Name.ShouldBe(VehicleAnalysis.CantonName); + year.Canton.Population.ShouldBe(1700); + year.Canton.Count.ShouldBe(46); + year.Canton.Brands.ShouldBe([37, 5]); + } + + [Fact] + public void UseLatestEarlierPopulationWhenYearIsMissing() + { + var snapshot = Snapshot([Entry(2025)], [new(2023, "4566", 900), new(2024, "4566", 1000)]); + + VehicleAnalysis.BuildYears(snapshot).ShouldHaveSingleItem().Municipalities[0].Population.ShouldBe(1000); + } + + [Fact] + public void ReturnShapesOnlyForMunicipalitiesInStockWhenBuildingShapes() + { + var snapshot = Snapshot([Entry(2023, municipality: "Frauenfeld alt"), Entry(2024), Entry(id: "4671", municipality: "Kreuzlingen")]); + + var shapes = VehicleAnalysis.BuildShapes(snapshot); + + shapes.Select(s => (s.Id, s.Name)).ShouldBe([("4566", "Frauenfeld"), ("4671", "Kreuzlingen")]); + JsonSerializer.Serialize(shapes[0].Polygons).ShouldBe(JsonSerializer.Serialize(Outline("4566").Polygons)); + } +} diff --git a/Schaad.OpenData.Tests/VehicleCacheStorageTestShould.cs b/Schaad.OpenData.Tests/VehicleCacheStorageTestShould.cs new file mode 100644 index 0000000..cafca05 --- /dev/null +++ b/Schaad.OpenData.Tests/VehicleCacheStorageTestShould.cs @@ -0,0 +1,62 @@ +using System.Text.Json; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Vehicles; +using Schaad.OpenData.Vehicles.Models; +using Schaad.OpenData.Vehicles.Storage; +using static Schaad.OpenData.Tests.VehicleTestData; + +namespace Schaad.OpenData.Tests; + +public sealed class VehicleCacheStorageTestShould : IDisposable +{ + private readonly string dataPath = Path.Combine(Path.GetTempPath(), "odv-tests-" + Guid.NewGuid().ToString("N")); + private readonly VehicleCacheStorage storage; + + public VehicleCacheStorageTestShould() + { + storage = new VehicleCacheStorage(Options.Create(new VehicleOptions { 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.Stock.ShouldBeEmpty(); + snapshot.Outlines.ShouldBeEmpty(); + snapshot.LastRefresh.ShouldBeNull(); + } + + [Fact] + public async Task RestoreSavedSnapshotWhenLoading() + { + var refreshedAt = new DateTimeOffset(2026, 11, 6, 12, 0, 0, TimeSpan.Zero); + var stockVersion = new DatasetVersion("djs-stv-17", refreshedAt.AddDays(-30)); + var snapshot = new VehicleSnapshot( + [Entry(2023, municipality: "Bürglen"), Entry(2024)], + [new PopulationEntry(2024, "4566", 27000)], + [Outline("4566")], + stockVersion, + null, + refreshedAt); + + await storage.SaveAsync(snapshot, CancellationToken.None); + var loaded = await storage.LoadAsync(CancellationToken.None); + + loaded.Stock.ShouldBe(snapshot.Stock); + loaded.Population.ShouldBe(snapshot.Population); + JsonSerializer.Serialize(loaded.Outlines.ShouldHaveSingleItem().Polygons).ShouldBe(JsonSerializer.Serialize(Outline("4566").Polygons)); + loaded.StockVersion.ShouldBe(stockVersion); + loaded.PopulationVersion.ShouldBeNull(); + loaded.LastRefresh.ShouldBe(refreshedAt); + loaded.Years.ShouldBe([2023, 2024]); + } +} diff --git a/Schaad.OpenData.Tests/VehicleRefresherTestShould.cs b/Schaad.OpenData.Tests/VehicleRefresherTestShould.cs new file mode 100644 index 0000000..876d011 --- /dev/null +++ b/Schaad.OpenData.Tests/VehicleRefresherTestShould.cs @@ -0,0 +1,88 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; +using Schaad.OpenData.Vehicles; +using Schaad.OpenData.Vehicles.Models; +using Schaad.OpenData.Vehicles.Source; +using Schaad.OpenData.Vehicles.Storage; +using static Schaad.OpenData.Tests.VehicleTestData; + +namespace Schaad.OpenData.Tests; + +public class VehicleRefresherTestShould +{ + private static readonly DateTimeOffset Now = new(2026, 11, 6, 12, 0, 0, TimeSpan.Zero); + private static readonly IOptions Options = Microsoft.Extensions.Options.Options.Create(new VehicleOptions()); + private static readonly DatasetVersion StockVersion = new("djs-stv-17", Now.AddDays(-50)); + private static readonly DatasetVersion PopulationVersion = new("sk-stat-56", Now.AddDays(-120)); + + private readonly ThurgauVehicleClient client = Substitute.For(new HttpClient(), Options); + private readonly MunicipalityBoundaryClient boundaryClient = Substitute.For(new HttpClient(), Options); + private readonly VehicleCacheStorage storage = Substitute.For(Options); + private readonly VehicleDataStore store = new(); + private readonly TimeProvider timeProvider = Substitute.For(); + private readonly VehicleRefresher refresher; + + public VehicleRefresherTestShould() + { + timeProvider.GetUtcNow().Returns(Now); + client.GetVersionAsync("djs-stv-17", Arg.Any()).Returns(StockVersion); + client.GetVersionAsync("sk-stat-56", Arg.Any()).Returns(PopulationVersion); + boundaryClient.FetchAsync(Arg.Any(), Arg.Any()).Returns(call => Outline(call.Arg())); + refresher = new VehicleRefresher(client, boundaryClient, storage, store, Options, timeProvider, NullLogger.Instance); + } + + [Fact] + public async Task FetchEverythingWhenCacheIsEmpty() + { + client.FetchStockAsync(Arg.Any()).Returns([Entry(id: "4566"), Entry(id: "4671", municipality: "Kreuzlingen")]); + client.FetchPopulationAsync(Arg.Any()).Returns([new PopulationEntry(2024, "4566", 27000)]); + + await refresher.RefreshAsync(CancellationToken.None); + + var snapshot = store.Current; + snapshot.Stock.Count.ShouldBe(2); + snapshot.Population.Count.ShouldBe(1); + snapshot.Outlines.Select(o => o.Id).ShouldBe(["4566", "4671"]); + snapshot.StockVersion.ShouldBe(StockVersion); + snapshot.PopulationVersion.ShouldBe(PopulationVersion); + snapshot.LastRefresh.ShouldBe(Now); + await storage.Received(1).SaveAsync(snapshot, Arg.Any()); + } + + [Fact] + public async Task SkipUnchangedDatasetsAndKnownOutlinesWhenRefreshing() + { + store.Replace(new VehicleSnapshot([Entry()], [new PopulationEntry(2024, "4566", 27000)], [Outline("4566")], StockVersion, PopulationVersion, Now.AddDays(-1))); + + await refresher.RefreshAsync(CancellationToken.None); + + await client.DidNotReceive().FetchStockAsync(Arg.Any()); + await client.DidNotReceive().FetchPopulationAsync(Arg.Any()); + await boundaryClient.DidNotReceive().FetchAsync(Arg.Any(), Arg.Any()); + store.Current.LastRefresh.ShouldBe(Now); + } + + [Fact] + public async Task FetchStockAgainWhenDatasetWasModified() + { + store.Replace(new VehicleSnapshot([Entry()], [new PopulationEntry(2024, "4566", 27000)], [Outline("4566")], StockVersion with { Modified = Now.AddDays(-400) }, PopulationVersion, null)); + client.FetchStockAsync(Arg.Any()).Returns([Entry(2025), Entry(2025, "4401", "Arbon")]); + + await refresher.RefreshAsync(CancellationToken.None); + + store.Current.Years.ShouldBe([2025]); + store.Current.Outlines.Select(o => o.Id).ShouldBe(["4566", "4401"]); + await client.DidNotReceive().FetchPopulationAsync(Arg.Any()); + await boundaryClient.Received(1).FetchAsync("4401", Arg.Any()); + } + + [Fact] + public void RequireRefreshWhenLastRefreshIsOlderThanInterval() + { + store.Replace(new VehicleSnapshot([], [], [], null, null, Now.AddHours(-25))); + + refresher.IsRefreshDue(TimeSpan.FromDays(1)).ShouldBeTrue(); + refresher.IsRefreshDue(TimeSpan.FromDays(2)).ShouldBeFalse(); + } +} diff --git a/Schaad.OpenData.Tests/VehicleTestData.cs b/Schaad.OpenData.Tests/VehicleTestData.cs new file mode 100644 index 0000000..d5bf7c9 --- /dev/null +++ b/Schaad.OpenData.Tests/VehicleTestData.cs @@ -0,0 +1,19 @@ +using Schaad.OpenData.Vehicles.Models; + +namespace Schaad.OpenData.Tests; + +internal static class VehicleTestData +{ + public static StockEntry Entry( + int year = 2024, + string id = "4566", + string municipality = "Frauenfeld", + string group = "Personenwagen", + string type = "Personenwagen", + string brand = "VW", + int count = 10) => + new(year, id, municipality, "Frauenfeld", group, type, brand, count); + + public static MunicipalityOutline Outline(string id) => + new(id, [[[[8.9, 47.55], [8.91, 47.55], [8.91, 47.56], [8.9, 47.55]]]]); +} diff --git a/Schaad.OpenData.Vehicles/Analysis/AreaSummary.cs b/Schaad.OpenData.Vehicles/Analysis/AreaSummary.cs new file mode 100644 index 0000000..c7d38e5 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Analysis/AreaSummary.cs @@ -0,0 +1,11 @@ +namespace Schaad.OpenData.Vehicles.Analysis; + +public sealed record AreaSummary( + string Id, + string Name, + string? District, + int Population, + int Count, + int[] Groups, + int[] Types, + int[] Brands); diff --git a/Schaad.OpenData.Vehicles/Analysis/MunicipalityShape.cs b/Schaad.OpenData.Vehicles/Analysis/MunicipalityShape.cs new file mode 100644 index 0000000..d211f12 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Analysis/MunicipalityShape.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Vehicles.Analysis; + +public sealed record MunicipalityShape(string Id, string Name, string District, double[][][][] Polygons); diff --git a/Schaad.OpenData.Vehicles/Analysis/VehicleAnalysis.cs b/Schaad.OpenData.Vehicles/Analysis/VehicleAnalysis.cs new file mode 100644 index 0000000..182abd7 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Analysis/VehicleAnalysis.cs @@ -0,0 +1,139 @@ +using Schaad.OpenData.Vehicles.Models; +using Schaad.OpenData.Vehicles.Source; +using Schaad.OpenData.Vehicles.Storage; + +namespace Schaad.OpenData.Vehicles.Analysis; + +public static class VehicleAnalysis +{ + public const string CantonId = "TG"; + public const string CantonName = "Kanton Thurgau"; + public const string PassengerCarGroup = "Personenwagen"; + + public static VehicleOverview BuildOverview(VehicleSnapshot snapshot) + { + var population = new PopulationLookup(snapshot.Population); + var municipalityIds = snapshot.Stock.Select(e => e.MunicipalityId).Distinct(StringComparer.Ordinal).ToList(); + var years = snapshot.Years + .Select(year => new VehicleYearInfo( + year, + ReferenceDate(year), + snapshot.Stock.Where(e => e.Year == year).Sum(e => e.Count), + municipalityIds.Sum(id => population.Find(year, id)))) + .ToList(); + + return new VehicleOverview(years, OrderedGroups(snapshot), OrderedTypes(snapshot), OrderedBrands(snapshot)); + } + + public static IReadOnlyList BuildYears(VehicleSnapshot snapshot) + { + var population = new PopulationLookup(snapshot.Population); + var groups = IndexOf(OrderedGroups(snapshot)); + var types = IndexOf(OrderedTypes(snapshot).Select(t => t.Name)); + var brands = IndexOf(OrderedBrands(snapshot)); + + return snapshot.Years + .Select(year => + { + var entries = snapshot.Stock.Where(e => e.Year == year).ToList(); + var municipalities = entries + .GroupBy(e => e.MunicipalityId, StringComparer.Ordinal) + .Select(g => + { + var first = g.First(); + return Summarize(first.MunicipalityId, first.Municipality, first.District, population.Find(year, g.Key), g, groups, types, brands); + }) + .OrderBy(m => m.Name, StringComparer.Ordinal) + .ToList(); + var canton = Summarize(CantonId, CantonName, null, municipalities.Sum(m => m.Population), entries, groups, types, brands); + return new VehicleYearView(year, ReferenceDate(year), canton, municipalities); + }) + .ToList(); + } + + public static IReadOnlyList BuildShapes(VehicleSnapshot snapshot) + { + var names = snapshot.Stock + .GroupBy(e => e.MunicipalityId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.MaxBy(e => e.Year)!, StringComparer.Ordinal); + + return snapshot.Outlines + .Where(o => names.ContainsKey(o.Id)) + .Select(o => new MunicipalityShape(o.Id, names[o.Id].Municipality, names[o.Id].District, o.Polygons)) + .OrderBy(s => s.Name, StringComparer.Ordinal) + .ToList(); + } + + private static AreaSummary Summarize( + string id, + string name, + string? district, + int population, + IEnumerable entries, + Dictionary groups, + Dictionary types, + Dictionary brands) + { + var groupCounts = new int[groups.Count]; + var typeCounts = new int[types.Count]; + var brandCounts = new int[brands.Count]; + var count = 0; + foreach (var entry in entries) + { + count += entry.Count; + groupCounts[groups[entry.Group]] += entry.Count; + typeCounts[types[entry.Type]] += entry.Count; + if (entry.Group == PassengerCarGroup) + { + brandCounts[brands[entry.Brand]] += entry.Count; + } + } + + return new AreaSummary(id, name, district, population, count, groupCounts, typeCounts, brandCounts); + } + + private static List OrderedGroups(VehicleSnapshot snapshot) => + ByFrequency(snapshot.Stock, e => e.Group).ToList(); + + private static List OrderedTypes(VehicleSnapshot snapshot) + { + var groupOfType = snapshot.Stock + .GroupBy(e => e.Type, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => ByFrequency(g, e => e.Group).First(), StringComparer.Ordinal); + return ByFrequency(snapshot.Stock, e => e.Type).Select(type => new VehicleTypeInfo(type, groupOfType[type])).ToList(); + } + + private static List OrderedBrands(VehicleSnapshot snapshot) => + ByFrequency(snapshot.Stock.Where(e => e.Group == PassengerCarGroup), e => e.Brand) + .OrderBy(brand => brand == ThurgauVehicleMapper.OtherBrand) + .ToList(); + + private static IEnumerable ByFrequency(IEnumerable entries, Func key) => + entries + .GroupBy(key, StringComparer.Ordinal) + .OrderByDescending(g => g.Sum(e => e.Count)) + .ThenBy(g => g.Key, StringComparer.Ordinal) + .Select(g => g.Key); + + private static Dictionary IndexOf(IEnumerable keys) => + keys.Select((key, index) => (key, index)).ToDictionary(p => p.key, p => p.index, StringComparer.Ordinal); + + private static DateOnly ReferenceDate(int year) => new(year, 12, 31); + + private sealed class PopulationLookup(IEnumerable entries) + { + private readonly Dictionary> byMunicipality = entries + .GroupBy(e => e.MunicipalityId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.OrderBy(e => e.Year).ToList(), StringComparer.Ordinal); + + public int Find(int year, string municipalityId) + { + if (!byMunicipality.TryGetValue(municipalityId, out var list)) + { + return 0; + } + + return (list.LastOrDefault(e => e.Year <= year) ?? list[0]).Population; + } + } +} diff --git a/Schaad.OpenData.Vehicles/Analysis/VehicleOverview.cs b/Schaad.OpenData.Vehicles/Analysis/VehicleOverview.cs new file mode 100644 index 0000000..ee829d9 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Analysis/VehicleOverview.cs @@ -0,0 +1,7 @@ +namespace Schaad.OpenData.Vehicles.Analysis; + +public sealed record VehicleOverview( + IReadOnlyList Years, + IReadOnlyList Groups, + IReadOnlyList Types, + IReadOnlyList Brands); diff --git a/Schaad.OpenData.Vehicles/Analysis/VehicleTypeInfo.cs b/Schaad.OpenData.Vehicles/Analysis/VehicleTypeInfo.cs new file mode 100644 index 0000000..b891d6e --- /dev/null +++ b/Schaad.OpenData.Vehicles/Analysis/VehicleTypeInfo.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Vehicles.Analysis; + +public sealed record VehicleTypeInfo(string Name, string Group); diff --git a/Schaad.OpenData.Vehicles/Analysis/VehicleYearInfo.cs b/Schaad.OpenData.Vehicles/Analysis/VehicleYearInfo.cs new file mode 100644 index 0000000..04ecb57 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Analysis/VehicleYearInfo.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Vehicles.Analysis; + +public sealed record VehicleYearInfo(int Year, DateOnly ReferenceDate, int Count, int Population); diff --git a/Schaad.OpenData.Vehicles/Analysis/VehicleYearView.cs b/Schaad.OpenData.Vehicles/Analysis/VehicleYearView.cs new file mode 100644 index 0000000..456114f --- /dev/null +++ b/Schaad.OpenData.Vehicles/Analysis/VehicleYearView.cs @@ -0,0 +1,7 @@ +namespace Schaad.OpenData.Vehicles.Analysis; + +public sealed record VehicleYearView( + int Year, + DateOnly ReferenceDate, + AreaSummary Canton, + IReadOnlyList Municipalities); diff --git a/Schaad.OpenData.Vehicles/Models/DatasetVersion.cs b/Schaad.OpenData.Vehicles/Models/DatasetVersion.cs new file mode 100644 index 0000000..36369e1 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Models/DatasetVersion.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Vehicles.Models; + +public sealed record DatasetVersion(string DatasetId, DateTimeOffset? Modified); diff --git a/Schaad.OpenData.Vehicles/Models/MunicipalityOutline.cs b/Schaad.OpenData.Vehicles/Models/MunicipalityOutline.cs new file mode 100644 index 0000000..6dbf402 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Models/MunicipalityOutline.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Vehicles.Models; + +public sealed record MunicipalityOutline(string Id, double[][][][] Polygons); diff --git a/Schaad.OpenData.Vehicles/Models/PopulationEntry.cs b/Schaad.OpenData.Vehicles/Models/PopulationEntry.cs new file mode 100644 index 0000000..45d4a2c --- /dev/null +++ b/Schaad.OpenData.Vehicles/Models/PopulationEntry.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Vehicles.Models; + +public sealed record PopulationEntry(int Year, string MunicipalityId, int Population); diff --git a/Schaad.OpenData.Vehicles/Models/StockEntry.cs b/Schaad.OpenData.Vehicles/Models/StockEntry.cs new file mode 100644 index 0000000..5b2e27d --- /dev/null +++ b/Schaad.OpenData.Vehicles/Models/StockEntry.cs @@ -0,0 +1,11 @@ +namespace Schaad.OpenData.Vehicles.Models; + +public sealed record StockEntry( + int Year, + string MunicipalityId, + string Municipality, + string District, + string Group, + string Type, + string Brand, + int Count); diff --git a/Schaad.OpenData.Vehicles/Schaad.OpenData.Vehicles.csproj b/Schaad.OpenData.Vehicles/Schaad.OpenData.Vehicles.csproj new file mode 100644 index 0000000..66bf7e7 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Schaad.OpenData.Vehicles.csproj @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/Schaad.OpenData.Vehicles/Source/MunicipalityBoundaryClient.cs b/Schaad.OpenData.Vehicles/Source/MunicipalityBoundaryClient.cs new file mode 100644 index 0000000..53dd824 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Source/MunicipalityBoundaryClient.cs @@ -0,0 +1,50 @@ +using System.Text.Json; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Vehicles.Models; + +namespace Schaad.OpenData.Vehicles.Source; + +public class MunicipalityBoundaryClient(HttpClient httpClient, IOptions options) +{ + private const int Decimals = 5; + + public virtual async Task FetchAsync(string municipalityId, CancellationToken cancellationToken) + { + var url = $"{options.Value.BoundaryUrl}/{Uri.EscapeDataString(municipalityId)}?geometryFormat=geojson&sr=4326"; + using var response = await httpClient.GetAsync(url, cancellationToken); + if (!response.IsSuccessStatusCode) + { + return null; + } + + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken); + if (!document.RootElement.TryGetProperty("feature", out var feature) + || !feature.TryGetProperty("geometry", out var geometry) + || !geometry.TryGetProperty("type", out var typeElement) + || !geometry.TryGetProperty("coordinates", out var coordinates)) + { + return null; + } + + double[][][][] polygons = typeElement.GetString() switch + { + "Polygon" => [ReadPolygon(coordinates)], + "MultiPolygon" => coordinates.EnumerateArray().Select(ReadPolygon).ToArray(), + _ => [], + }; + + return polygons.Length == 0 ? null : new MunicipalityOutline(municipalityId, polygons); + } + + private static double[][][] ReadPolygon(JsonElement polygon) => + polygon.EnumerateArray() + .Select(ring => ring.EnumerateArray() + .Select(point => new[] + { + Math.Round(point[0].GetDouble(), Decimals), + Math.Round(point[1].GetDouble(), Decimals), + }) + .ToArray()) + .ToArray(); +} diff --git a/Schaad.OpenData.Vehicles/Source/ThurgauPopulationRecord.cs b/Schaad.OpenData.Vehicles/Source/ThurgauPopulationRecord.cs new file mode 100644 index 0000000..f2f13e2 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Source/ThurgauPopulationRecord.cs @@ -0,0 +1,15 @@ +using System.Text.Json.Serialization; + +namespace Schaad.OpenData.Vehicles.Source; + +public sealed class ThurgauPopulationRecord +{ + [JsonPropertyName("jahr")] + public string? Year { get; init; } + + [JsonPropertyName("bfs_nr_gemeinde")] + public string? MunicipalityId { get; init; } + + [JsonPropertyName("anzahl_personen")] + public string? Population { get; init; } +} diff --git a/Schaad.OpenData.Vehicles/Source/ThurgauStockRecord.cs b/Schaad.OpenData.Vehicles/Source/ThurgauStockRecord.cs new file mode 100644 index 0000000..0490bc1 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Source/ThurgauStockRecord.cs @@ -0,0 +1,30 @@ +using System.Text.Json.Serialization; + +namespace Schaad.OpenData.Vehicles.Source; + +public sealed class ThurgauStockRecord +{ + [JsonPropertyName("jahr")] + public string? Year { get; init; } + + [JsonPropertyName("bfs_nr_gemeinde")] + public string? MunicipalityId { get; init; } + + [JsonPropertyName("gemeinde")] + public string? Municipality { get; init; } + + [JsonPropertyName("bezirk")] + public string? District { get; init; } + + [JsonPropertyName("fahrzeuggruppe")] + public string? Group { get; init; } + + [JsonPropertyName("fahrzeugart")] + public string? Type { get; init; } + + [JsonPropertyName("marke")] + public string? Brand { get; init; } + + [JsonPropertyName("anzahl")] + public double? Count { get; init; } +} diff --git a/Schaad.OpenData.Vehicles/Source/ThurgauVehicleClient.cs b/Schaad.OpenData.Vehicles/Source/ThurgauVehicleClient.cs new file mode 100644 index 0000000..d064f22 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Source/ThurgauVehicleClient.cs @@ -0,0 +1,53 @@ +using System.Globalization; +using System.Text.Json; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Vehicles.Models; + +namespace Schaad.OpenData.Vehicles.Source; + +public class ThurgauVehicleClient(HttpClient httpClient, IOptions options) +{ + public virtual async Task GetVersionAsync(string datasetId, CancellationToken cancellationToken) + { + var url = $"{options.Value.CatalogUrl}/{Uri.EscapeDataString(datasetId)}"; + using var response = await httpClient.GetAsync(url, cancellationToken); + response.EnsureSuccessStatusCode(); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken); + + DateTimeOffset? modified = document.RootElement.TryGetProperty("metas", out var metas) + && metas.TryGetProperty("default", out var meta) + && meta.TryGetProperty("modified", out var modifiedElement) + && modifiedElement.ValueKind == JsonValueKind.String + && DateTimeOffset.TryParse(modifiedElement.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var parsed) + ? parsed + : null; + + return new DatasetVersion(datasetId, modified); + } + + public virtual async Task> FetchStockAsync(CancellationToken cancellationToken) => + ThurgauVehicleMapper.MapStock(await ExportAsync(options.Value.StockDatasetId, cancellationToken)); + + public virtual async Task> FetchPopulationAsync(CancellationToken cancellationToken) => + ThurgauVehicleMapper.MapPopulation(await ExportAsync(options.Value.PopulationDatasetId, cancellationToken)); + + private async Task> ExportAsync(string datasetId, CancellationToken cancellationToken) + { + var url = $"{options.Value.CatalogUrl}/{Uri.EscapeDataString(datasetId)}/exports/json"; + using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + response.EnsureSuccessStatusCode(); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + + var records = new List(); + await foreach (var record in JsonSerializer.DeserializeAsyncEnumerable(stream, cancellationToken: cancellationToken)) + { + if (record is not null) + { + records.Add(record); + } + } + + return records; + } +} diff --git a/Schaad.OpenData.Vehicles/Source/ThurgauVehicleMapper.cs b/Schaad.OpenData.Vehicles/Source/ThurgauVehicleMapper.cs new file mode 100644 index 0000000..348e807 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Source/ThurgauVehicleMapper.cs @@ -0,0 +1,42 @@ +using System.Globalization; +using Schaad.OpenData.Vehicles.Models; + +namespace Schaad.OpenData.Vehicles.Source; + +public static class ThurgauVehicleMapper +{ + public const string OtherBrand = "Andere"; + public const string Unknown = "Unbekannt"; + + public static IReadOnlyList MapStock(IEnumerable records) => + records + .Select(r => (Record: r, Year: ParseYear(r.Year), Id: Clean(r.MunicipalityId))) + .Where(r => r.Year is not null && r.Id is not null && r.Record.Count > 0) + .Select(r => new StockEntry( + r.Year!.Value, + r.Id!, + Clean(r.Record.Municipality) ?? r.Id!, + Clean(r.Record.District) ?? Unknown, + Clean(r.Record.Group) ?? Unknown, + Clean(r.Record.Type) ?? Unknown, + Clean(r.Record.Brand) ?? OtherBrand, + (int)Math.Round(r.Record.Count!.Value))) + .ToList(); + + public static IReadOnlyList MapPopulation(IEnumerable records) => + records + .Select(r => (Year: ParseYear(r.Year), Id: Clean(r.MunicipalityId), Population: ParseInt(r.Population))) + .Where(r => r.Year is not null && r.Id is not null && r.Population > 0) + .Select(r => new PopulationEntry(r.Year!.Value, r.Id!, r.Population!.Value)) + .ToList(); + + private static int? ParseYear(string? value) => + value is { Length: >= 4 } && int.TryParse(value.AsSpan(0, 4), NumberStyles.None, CultureInfo.InvariantCulture, out var year) + ? year + : null; + + private static int? ParseInt(string? value) => + double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) ? (int)Math.Round(number) : null; + + private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); +} diff --git a/Schaad.OpenData.Vehicles/Storage/VehicleCacheMeta.cs b/Schaad.OpenData.Vehicles/Storage/VehicleCacheMeta.cs new file mode 100644 index 0000000..c43ea75 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Storage/VehicleCacheMeta.cs @@ -0,0 +1,5 @@ +using Schaad.OpenData.Vehicles.Models; + +namespace Schaad.OpenData.Vehicles.Storage; + +public sealed record VehicleCacheMeta(DatasetVersion? StockVersion, DatasetVersion? PopulationVersion, DateTimeOffset? LastRefresh); diff --git a/Schaad.OpenData.Vehicles/Storage/VehicleCacheStorage.cs b/Schaad.OpenData.Vehicles/Storage/VehicleCacheStorage.cs new file mode 100644 index 0000000..8a37545 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Storage/VehicleCacheStorage.cs @@ -0,0 +1,65 @@ +using System.Text.Json; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Vehicles.Models; + +namespace Schaad.OpenData.Vehicles.Storage; + +public class VehicleCacheStorage(IOptions options) +{ + private const string MetaFileName = "meta.json"; + private const string StockFileName = "stock.json"; + private const string PopulationFileName = "population.json"; + private const string OutlinesFileName = "outlines-v1.json"; + + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + private string RootPath => Path.Combine(Path.GetFullPath(options.Value.DataPath), "vehicles", "thurgau"); + + public virtual async Task LoadAsync(CancellationToken cancellationToken) + { + var meta = await ReadAsync(MetaFileName, cancellationToken); + var stock = await ReadAsync>(StockFileName, cancellationToken) ?? []; + var population = await ReadAsync>(PopulationFileName, cancellationToken) ?? []; + var outlines = await ReadAsync>(OutlinesFileName, cancellationToken) ?? []; + + return stock.Count == 0 + ? new VehicleSnapshot([], [], outlines, null, null, null) + : new VehicleSnapshot(stock, population, outlines, meta?.StockVersion, meta?.PopulationVersion, meta?.LastRefresh); + } + + public virtual async Task SaveAsync(VehicleSnapshot snapshot, CancellationToken cancellationToken) + { + await WriteAsync(StockFileName, snapshot.Stock, cancellationToken); + await WriteAsync(PopulationFileName, snapshot.Population, cancellationToken); + await WriteAsync(OutlinesFileName, snapshot.Outlines, cancellationToken); + await WriteAsync( + MetaFileName, + new VehicleCacheMeta(snapshot.StockVersion, snapshot.PopulationVersion, snapshot.LastRefresh), + cancellationToken); + } + + private async Task ReadAsync(string fileName, CancellationToken cancellationToken) + { + var path = Path.Combine(RootPath, fileName); + if (!File.Exists(path)) + { + return default; + } + + await using var stream = File.OpenRead(path); + return await JsonSerializer.DeserializeAsync(stream, JsonOptions, cancellationToken); + } + + private async Task WriteAsync(string fileName, T value, CancellationToken cancellationToken) + { + var path = Path.Combine(RootPath, fileName); + Directory.CreateDirectory(RootPath); + var tempPath = path + ".tmp"; + await using (var stream = File.Create(tempPath)) + { + await JsonSerializer.SerializeAsync(stream, value, JsonOptions, cancellationToken); + } + + File.Move(tempPath, path, true); + } +} diff --git a/Schaad.OpenData.Vehicles/Storage/VehicleDataStore.cs b/Schaad.OpenData.Vehicles/Storage/VehicleDataStore.cs new file mode 100644 index 0000000..e616a43 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Storage/VehicleDataStore.cs @@ -0,0 +1,10 @@ +namespace Schaad.OpenData.Vehicles.Storage; + +public sealed class VehicleDataStore +{ + private volatile VehicleSnapshot current = VehicleSnapshot.Empty; + + public VehicleSnapshot Current => current; + + public void Replace(VehicleSnapshot snapshot) => current = snapshot; +} diff --git a/Schaad.OpenData.Vehicles/Storage/VehicleSnapshot.cs b/Schaad.OpenData.Vehicles/Storage/VehicleSnapshot.cs new file mode 100644 index 0000000..3775c68 --- /dev/null +++ b/Schaad.OpenData.Vehicles/Storage/VehicleSnapshot.cs @@ -0,0 +1,16 @@ +using Schaad.OpenData.Vehicles.Models; + +namespace Schaad.OpenData.Vehicles.Storage; + +public sealed record VehicleSnapshot( + IReadOnlyList Stock, + IReadOnlyList Population, + IReadOnlyList Outlines, + DatasetVersion? StockVersion, + DatasetVersion? PopulationVersion, + DateTimeOffset? LastRefresh) +{ + public static readonly VehicleSnapshot Empty = new([], [], [], null, null, null); + + public IReadOnlyList Years { get; } = Stock.Select(e => e.Year).Distinct().Order().ToList(); +} diff --git a/Schaad.OpenData.Vehicles/VehicleOptions.cs b/Schaad.OpenData.Vehicles/VehicleOptions.cs new file mode 100644 index 0000000..d4f2f88 --- /dev/null +++ b/Schaad.OpenData.Vehicles/VehicleOptions.cs @@ -0,0 +1,19 @@ +namespace Schaad.OpenData.Vehicles; + +public sealed class VehicleOptions +{ + public const string SectionName = "Vehicles"; + + public string DataPath { get; set; } = "data"; + + public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromDays(1); + + public string CatalogUrl { get; set; } = "https://data.tg.ch/api/explore/v2.1/catalog/datasets"; + + public string StockDatasetId { get; set; } = "djs-stv-17"; + + public string PopulationDatasetId { get; set; } = "sk-stat-56"; + + public string BoundaryUrl { get; set; } = + "https://api3.geo.admin.ch/rest/services/api/MapServer/ch.swisstopo.swissboundaries3d-gemeinde-flaeche.fill"; +} diff --git a/Schaad.OpenData.Vehicles/VehicleRefreshService.cs b/Schaad.OpenData.Vehicles/VehicleRefreshService.cs new file mode 100644 index 0000000..62825c7 --- /dev/null +++ b/Schaad.OpenData.Vehicles/VehicleRefreshService.cs @@ -0,0 +1,42 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Schaad.OpenData.Vehicles; + +public sealed class VehicleRefreshService( + VehicleRefresher refresher, + IOptions options, + ILogger logger) : BackgroundService +{ + private static readonly TimeSpan CheckInterval = TimeSpan.FromMinutes(30); + + 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 vehicle cache"); + } + + while (!stoppingToken.IsCancellationRequested) + { + try + { + if (refresher.IsRefreshDue(options.Value.RefreshInterval)) + { + await refresher.RefreshAsync(stoppingToken); + } + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError(exception, "Vehicle refresh failed"); + } + + await Task.Delay(CheckInterval, stoppingToken); + } + } +} diff --git a/Schaad.OpenData.Vehicles/VehicleRefresher.cs b/Schaad.OpenData.Vehicles/VehicleRefresher.cs new file mode 100644 index 0000000..e68b3f3 --- /dev/null +++ b/Schaad.OpenData.Vehicles/VehicleRefresher.cs @@ -0,0 +1,75 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Vehicles.Models; +using Schaad.OpenData.Vehicles.Source; +using Schaad.OpenData.Vehicles.Storage; + +namespace Schaad.OpenData.Vehicles; + +public class VehicleRefresher( + ThurgauVehicleClient client, + MunicipalityBoundaryClient boundaryClient, + VehicleCacheStorage storage, + VehicleDataStore store, + IOptions options, + TimeProvider timeProvider, + ILogger logger) +{ + public async Task LoadCacheAsync(CancellationToken cancellationToken) + { + var snapshot = await storage.LoadAsync(cancellationToken); + store.Replace(snapshot); + logger.LogInformation( + "Loaded vehicle cache with {Entries} stock entries for {Years} years", + snapshot.Stock.Count, + snapshot.Years.Count); + } + + 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; + var stockVersion = await client.GetVersionAsync(options.Value.StockDatasetId, cancellationToken); + var populationVersion = await client.GetVersionAsync(options.Value.PopulationDatasetId, cancellationToken); + + var stockChanged = current.Stock.Count == 0 || current.StockVersion != stockVersion; + var populationChanged = current.Population.Count == 0 || current.PopulationVersion != populationVersion; + var stock = stockChanged ? await client.FetchStockAsync(cancellationToken) : current.Stock; + var population = populationChanged ? await client.FetchPopulationAsync(cancellationToken) : current.Population; + var outlines = await CompleteOutlinesAsync(current.Outlines, stock, cancellationToken); + + var updated = new VehicleSnapshot(stock, population, outlines, stockVersion, populationVersion, timeProvider.GetUtcNow()); + await storage.SaveAsync(updated, cancellationToken); + store.Replace(updated); + logger.LogInformation( + "Vehicle refresh: stock {StockState} ({Entries} entries), population {PopulationState}, {Outlines} municipality outlines", + stockChanged ? "imported" : "unchanged", + stock.Count, + populationChanged ? "imported" : "unchanged", + outlines.Count); + } + + private async Task> CompleteOutlinesAsync( + IReadOnlyList cached, + IReadOnlyList stock, + CancellationToken cancellationToken) + { + var outlines = cached.ToList(); + var known = outlines.Select(o => o.Id).ToHashSet(StringComparer.Ordinal); + foreach (var id in stock.Select(e => e.MunicipalityId).Distinct(StringComparer.Ordinal).Where(id => !known.Contains(id))) + { + if (await boundaryClient.FetchAsync(id, cancellationToken) is { } outline) + { + outlines.Add(outline); + } + else + { + logger.LogWarning("No boundary found for municipality {MunicipalityId}", id); + } + } + + return outlines; + } +} diff --git a/Schaad.OpenData.Vehicles/VehicleServiceCollectionExtensions.cs b/Schaad.OpenData.Vehicles/VehicleServiceCollectionExtensions.cs new file mode 100644 index 0000000..29d067a --- /dev/null +++ b/Schaad.OpenData.Vehicles/VehicleServiceCollectionExtensions.cs @@ -0,0 +1,35 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Schaad.OpenData.Vehicles.Source; +using Schaad.OpenData.Vehicles.Storage; + +namespace Schaad.OpenData.Vehicles; + +public static class VehicleServiceCollectionExtensions +{ + private const string UserAgent = "OpenDataVisualizer/1.0"; + + public static IServiceCollection AddVehicles(this IServiceCollection services, IConfiguration configuration) + { + services.Configure(configuration.GetSection(VehicleOptions.SectionName)); + services.TryAddSingleton(TimeProvider.System); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(); + + services.AddHttpClient(client => + { + client.Timeout = TimeSpan.FromMinutes(2); + client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent); + }); + services.AddHttpClient(client => + { + client.Timeout = TimeSpan.FromSeconds(30); + client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent); + }); + + return services; + } +} diff --git a/client/public/previews/vehicles-thurgau.svg b/client/public/previews/vehicles-thurgau.svg new file mode 100644 index 0000000..08e61c7 --- /dev/null +++ b/client/public/previews/vehicles-thurgau.svg @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/src/App.tsx b/client/src/App.tsx index 91860fe..1d7e00a 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,6 +1,7 @@ import { Navigate, Route, Routes } from 'react-router-dom'; import { HomePage } from './pages/HomePage'; import { TrafficThurgauPage } from './pages/TrafficThurgauPage'; +import { VehiclesThurgauPage } from './pages/VehiclesThurgauPage'; import { WatercraftThurgauPage } from './pages/WatercraftThurgauPage'; export function App() { @@ -9,6 +10,7 @@ export function App() { } /> } /> } /> + } /> } /> ); diff --git a/client/src/api/vehicles.ts b/client/src/api/vehicles.ts new file mode 100644 index 0000000..b5ed84a --- /dev/null +++ b/client/src/api/vehicles.ts @@ -0,0 +1,64 @@ +export interface VehicleYearInfo { + year: number; + referenceDate: string; + count: number; + population: number; +} + +export interface VehicleType { + name: string; + group: string; +} + +export interface VehicleMeta { + title: string; + publisher: string; + sourceUrl: string; + license: string; + populationSourceUrl: string; + years: VehicleYearInfo[]; + groups: string[]; + types: VehicleType[]; + brands: string[]; + lastRefresh: string | null; +} + +export interface AreaSummary { + id: string; + name: string; + district: string | null; + population: number; + count: number; + groups: number[]; + types: number[]; + brands: number[]; +} + +export interface VehicleYearView { + year: number; + referenceDate: string; + canton: AreaSummary; + municipalities: AreaSummary[]; +} + +export interface MunicipalityShape { + id: string; + name: string; + district: string; + polygons: number[][][][]; +} + +async function getJson(url: string): Promise { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`${response.status} ${response.statusText}`); + } + return (await response.json()) as T; +} + +export const fetchVehicleMeta = () => getJson('/api/vehicles/meta'); + +export const fetchVehicleYears = () => getJson('/api/vehicles/years'); + +export const fetchMunicipalityShapes = () => + getJson('/api/vehicles/municipalities'); diff --git a/client/src/components/vehicles/MetricControls.tsx b/client/src/components/vehicles/MetricControls.tsx new file mode 100644 index 0000000..bef6c96 --- /dev/null +++ b/client/src/components/vehicles/MetricControls.tsx @@ -0,0 +1,147 @@ +import type { AreaSummary, VehicleMeta } from '../../api/vehicles'; +import { formatNumber } from '../../traffic/format'; +import { + OTHER_BRAND, + formatMetric, + groupColor, + metricUnit, + metricValue, + type ColorScale, + type Metric, +} from '../../vehicles/metrics'; + +interface MetricControlsProps { + meta: VehicleMeta; + canton: AreaSummary; + metric: Metric; + scale: ColorScale; + onMetricChange: (metric: Metric) => void; +} + +const QUICK_BRANDS = 8; + +export function MetricControls({ + meta, + canton, + metric, + scale, + onMetricChange, +}: MetricControlsProps) { + const brandOrder = meta.brands + .map((name, index) => ({ name, index, count: canton.brands[index] ?? 0 })) + .filter((brand) => brand.name !== OTHER_BRAND && brand.count > 0) + .sort((a, b) => b.count - a.count); + const selectedBrand = metric.kind === 'brand' ? metric.brand : null; + const quickBrands = brandOrder.slice(0, QUICK_BRANDS); + const brandValue = metric.kind === 'brand' ? metricValue(canton, metric) : null; + + return ( +
+
+ + +
+ + {metric.kind === 'density' ? ( +
+ + {meta.groups.map((group, index) => ( + + ))} +
+ ) : ( +
+ {quickBrands.map((brand) => ( + + ))} + +
+ )} + +
+ + {metricUnit(metric)} + {brandValue !== null && ` · Kanton ${formatMetric(brandValue, metric)}`} + +
+ {scale.colors.map((color, i) => ( +
+ + + {i === 0 + ? `< ${formatMetric(scale.breaks[0] ?? null, metric)}` + : `≥ ${formatMetric(scale.breaks[i - 1], metric)}`} + +
+ ))} +
+
+
+ ); +} diff --git a/client/src/components/vehicles/MunicipalityPanel.tsx b/client/src/components/vehicles/MunicipalityPanel.tsx new file mode 100644 index 0000000..0538952 --- /dev/null +++ b/client/src/components/vehicles/MunicipalityPanel.tsx @@ -0,0 +1,323 @@ +import { + BarElement, + CategoryScale, + Chart as ChartJS, + Legend, + LinearScale, + Tooltip, + type ChartOptions, +} from 'chart.js'; +import { Bar } from 'react-chartjs-2'; +import type { AreaSummary, VehicleMeta, VehicleYearView } from '../../api/vehicles'; +import { formatDate, formatNumber } from '../../traffic/format'; +import { + OTHER_BRAND, + formatMetric, + groupColor, + metricLabel, + metricValue, + rankOf, + type Metric, +} from '../../vehicles/metrics'; + +ChartJS.register(CategoryScale, LinearScale, BarElement, Tooltip, Legend); + +const BRAND_COLOR = '#2a78d6'; +const BRAND_SELECTED_COLOR = '#eb6834'; +const GRID_COLOR = '#e2e8f0'; +const TOP_BRANDS = 12; +const TOP_TYPES = 8; + +interface MunicipalityPanelProps { + meta: VehicleMeta; + years: VehicleYearView[]; + id: string | null; + year: number; + metric: Metric; + metricTitle: string; + onClose: () => void; +} + +function findArea(view: VehicleYearView | undefined, id: string | null): AreaSummary | null { + if (!view) { + return null; + } + return id === null ? view.canton : (view.municipalities.find((m) => m.id === id) ?? null); +} + +export function MunicipalityPanel({ + meta, + years, + id, + year, + metric, + metricTitle, + onClose, +}: MunicipalityPanelProps) { + const yearIndex = years.findIndex((y) => y.year === year); + const view = years[yearIndex]; + const area = findArea(view, id); + const previous = yearIndex > 0 ? findArea(years[yearIndex - 1], id) : null; + + if (!view || !area) { + return ( + + ); + } + + const delta = previous ? area.count - previous.count : null; + const carIndex = meta.groups.indexOf('Personenwagen'); + const showsCarDensity = metric.kind === 'density' && metric.group === carIndex; + const densityMetric: Metric = { kind: 'density', group: showsCarDensity ? null : carIndex }; + const density = carIndex >= 0 ? metricValue(area, densityMetric) : null; + const value = metricValue(area, metric); + const rank = id !== null ? rankOf(view.municipalities, id, metric) : null; + const cars = area.brands.reduce((sum, count) => sum + count, 0); + const selectedBrand = metric.kind === 'brand' ? meta.brands[metric.brand] : null; + + const brands = meta.brands + .map((name, index) => ({ name, count: area.brands[index] ?? 0 })) + .filter((brand) => brand.name !== OTHER_BRAND && brand.count > 0) + .sort((a, b) => b.count - a.count); + const topBrands = brands.slice(0, TOP_BRANDS); + if (selectedBrand && !topBrands.some((b) => b.name === selectedBrand)) { + const selected = brands.find((b) => b.name === selectedBrand); + if (selected) { + topBrands.push(selected); + } + } + + const types = meta.types + .map((type, index) => ({ ...type, count: area.types[index] ?? 0 })) + .filter((type) => type.count > 0) + .sort((a, b) => b.count - a.count) + .slice(0, TOP_TYPES); + + const trendOptions: ChartOptions<'bar'> = { + responsive: true, + maintainAspectRatio: false, + animation: false, + interaction: { mode: 'index', intersect: false }, + plugins: { + legend: { position: 'bottom', labels: { boxWidth: 10, boxHeight: 10 } }, + tooltip: { + callbacks: { + label: (context) => ` ${context.dataset.label}: ${formatNumber(Number(context.raw))}`, + footer: (items) => + `Total: ${formatNumber(items.reduce((sum, item) => sum + Number(item.raw), 0))}`, + }, + }, + }, + scales: { + x: { stacked: true, grid: { display: false } }, + y: { + stacked: true, + beginAtZero: true, + grid: { color: GRID_COLOR }, + title: { display: true, text: 'Fahrzeuge' }, + }, + }, + }; + + const brandOptions: ChartOptions<'bar'> = { + indexAxis: 'y', + responsive: true, + maintainAspectRatio: false, + animation: false, + plugins: { + legend: { display: false }, + tooltip: { + callbacks: { + label: (context) => + ` ${formatNumber(Number(context.raw))} Personenwagen (${percent(Number(context.raw), cars)})`, + }, + }, + }, + scales: { + x: { beginAtZero: true, grid: { color: GRID_COLOR } }, + y: { grid: { display: false }, ticks: { autoSkip: false, font: { size: 10 } } }, + }, + }; + + return ( + + ); +} + +function percent(value: number, total: number): string { + if (total <= 0) { + return '–'; + } + const share = (value / total) * 100; + return `${share < 10 && share > 0 ? share.toFixed(1) : Math.round(share)} %`; +} diff --git a/client/src/components/vehicles/VehicleMap.tsx b/client/src/components/vehicles/VehicleMap.tsx new file mode 100644 index 0000000..5a4a8ea --- /dev/null +++ b/client/src/components/vehicles/VehicleMap.tsx @@ -0,0 +1,139 @@ +import 'leaflet/dist/leaflet.css'; +import L from 'leaflet'; +import { useEffect, useRef } from 'react'; +import type { AreaSummary, MunicipalityShape } from '../../api/vehicles'; +import { addSwisstopoBaseLayers, escapeHtml } from '../../map/baseLayers'; +import { formatNumber } from '../../traffic/format'; +import { + formatMetric, + metricLabel, + metricValue, + scaleColor, + type ColorScale, + type Metric, +} from '../../vehicles/metrics'; + +interface VehicleMapProps { + shapes: MunicipalityShape[]; + areas: AreaSummary[]; + metric: Metric; + metricTitle: string; + scale: ColorScale; + selectedId: string | null; + onSelect: (id: string) => void; +} + +const THURGAU_CENTER: L.LatLngTuple = [47.57, 9.1]; +const DATA_ATTRIBUTION = + 'Strassenverkehrsamt Thurgau, ' + + 'swissBOUNDARIES3D'; +const BORDER_COLOR = '#ffffff'; +const SELECTED_BORDER_COLOR = '#0f172a'; + +export function VehicleMap({ + shapes, + areas, + metric, + metricTitle, + scale, + selectedId, + onSelect, +}: VehicleMapProps) { + const containerRef = useRef(null); + const mapRef = useRef(null); + const layersRef = useRef>(new Map()); + const onSelectRef = useRef(onSelect); + onSelectRef.current = onSelect; + + useEffect(() => { + if (!containerRef.current) { + return; + } + + const map = L.map(containerRef.current, { zoomSnap: 0.5 }).setView(THURGAU_CENTER, 10); + addSwisstopoBaseLayers(map, DATA_ATTRIBUTION); + mapRef.current = map; + + const resizeObserver = new ResizeObserver(() => map.invalidateSize()); + resizeObserver.observe(containerRef.current); + const layers = layersRef.current; + + return () => { + resizeObserver.disconnect(); + map.remove(); + mapRef.current = null; + layers.clear(); + }; + }, []); + + useEffect(() => { + const map = mapRef.current; + if (!map || shapes.length === 0 || layersRef.current.size > 0) { + return; + } + + for (const shape of shapes) { + const latLngs = shape.polygons.map((polygon) => + polygon.map((ring) => ring.map(([lon, lat]) => [lat, lon] as L.LatLngTuple)), + ); + const layer = L.polygon(latLngs, { + color: BORDER_COLOR, + weight: 1, + fillOpacity: 0.78, + smoothFactor: 0.5, + }) + .on('click', () => onSelectRef.current(shape.id)) + .on('mouseover', () => layer.setStyle({ fillOpacity: 0.95 })) + .on('mouseout', () => layer.setStyle({ fillOpacity: 0.78 })) + .addTo(map); + layersRef.current.set(shape.id, layer); + } + + const bounds = L.latLngBounds([]); + layersRef.current.forEach((layer) => bounds.extend(layer.getBounds())); + map.fitBounds(bounds, { paddingTopLeft: [20, 20], paddingBottomRight: [20, 150] }); + }, [shapes]); + + useEffect(() => { + const byId = new Map(areas.map((area) => [area.id, area])); + layersRef.current.forEach((layer, id) => { + const area = byId.get(id); + const value = area ? metricValue(area, metric) : null; + const selected = id === selectedId; + layer.setStyle({ + fillColor: scaleColor(scale, value), + color: selected ? SELECTED_BORDER_COLOR : BORDER_COLOR, + weight: selected ? 3 : 1, + }); + if (selected) { + layer.bringToFront(); + } + const name = area?.name ?? shapes.find((s) => s.id === id)?.name ?? id; + layer.bindTooltip(tooltipHtml(name, area, metric, metricTitle, value), { + sticky: true, + direction: 'top', + offset: [0, -8], + }); + }); + }, [areas, metric, metricTitle, scale, selectedId, shapes]); + + return
; +} + +function tooltipHtml( + name: string, + area: AreaSummary | undefined, + metric: Metric, + metricTitle: string, + value: number | null, +): string { + if (!area) { + return `${escapeHtml(name)}
keine Daten`; + } + return ( + `${escapeHtml(name)} · Bezirk ${escapeHtml(area.district ?? '')}
` + + `
${escapeHtml(metricLabel(metric, metricTitle))}` + + `${formatMetric(value, metric)}
` + + `
${formatNumber(area.count)} Fahrzeuge · ${formatNumber(area.population)} Einwohner
` + ); +} diff --git a/client/src/components/watercraft/YearControls.tsx b/client/src/components/watercraft/YearControls.tsx index f6120f4..f935084 100644 --- a/client/src/components/watercraft/YearControls.tsx +++ b/client/src/components/watercraft/YearControls.tsx @@ -1,8 +1,7 @@ -import type { YearInfo } from '../../api/watercraft'; import { formatDate } from '../../traffic/format'; interface YearControlsProps { - years: YearInfo[]; + years: { year: number; referenceDate: string | null }[]; year: number; playing: boolean; onYearChange: (year: number) => void; diff --git a/client/src/maps.ts b/client/src/maps.ts index 4bff4aa..f203417 100644 --- a/client/src/maps.ts +++ b/client/src/maps.ts @@ -29,4 +29,14 @@ export const MAPS: MapEntry[] = [ tags: ['Schifffahrt', 'Jahresbestand', 'Standorte'], preview: '/previews/watercraft-thurgau.svg', }, + { + path: '/fahrzeuge/thurgau', + title: 'Fahrzeugbestand', + region: 'Kanton Thurgau', + description: + 'Alle eingelösten Strassenfahrzeuge der 80 Gemeinden – Fahrzeugdichte pro Einwohner nach Fahrzeuggruppe oder Anteil einer Automarke, mit Jahresvergleich seit 2023.', + source: 'Strassenverkehrsamt Kanton Thurgau', + tags: ['Fahrzeuge', 'Gemeinden', 'Automarken'], + preview: '/previews/vehicles-thurgau.svg', + }, ]; diff --git a/client/src/pages/VehiclesThurgauPage.tsx b/client/src/pages/VehiclesThurgauPage.tsx new file mode 100644 index 0000000..0759fb8 --- /dev/null +++ b/client/src/pages/VehiclesThurgauPage.tsx @@ -0,0 +1,210 @@ +import { useQuery } from '@tanstack/react-query'; +import { memo, useCallback, useEffect, useMemo, useState } from 'react'; +import { Link, useSearchParams } from 'react-router-dom'; +import { fetchMunicipalityShapes, fetchVehicleMeta, fetchVehicleYears } from '../api/vehicles'; +import { MetricControls } from '../components/vehicles/MetricControls'; +import { MunicipalityPanel } from '../components/vehicles/MunicipalityPanel'; +import { VehicleMap } from '../components/vehicles/VehicleMap'; +import { YearControls } from '../components/watercraft/YearControls'; +import { formatNumber } from '../traffic/format'; +import { buildScale, metricTitle, metricValue, type Metric } from '../vehicles/metrics'; + +const MemoMunicipalityPanel = memo(MunicipalityPanel); + +const PLAY_INTERVAL_MS = 1600; + +export function VehiclesThurgauPage() { + const metaQuery = useQuery({ + queryKey: ['vehicle-meta'], + queryFn: fetchVehicleMeta, + refetchInterval: (query) => (query.state.data?.years.length ? false : 15_000), + }); + const ready = !!metaQuery.data?.years.length; + const lastRefresh = metaQuery.data?.lastRefresh ?? null; + const yearsQuery = useQuery({ + queryKey: ['vehicle-years', lastRefresh], + queryFn: fetchVehicleYears, + enabled: ready, + staleTime: Infinity, + }); + const shapesQuery = useQuery({ + queryKey: ['vehicle-shapes', lastRefresh], + queryFn: fetchMunicipalityShapes, + enabled: ready, + staleTime: Infinity, + }); + + const [searchParams, setSearchParams] = useSearchParams(); + const [metric, setMetric] = useState({ kind: 'density', group: 0 }); + const [selectedId, setSelectedId] = useState(null); + const [playing, setPlaying] = useState(false); + + useEffect(() => { + document.title = 'Fahrzeugbestand Thurgau – OpenDataVisualizer'; + }, []); + + const meta = metaQuery.data; + const years = useMemo(() => yearsQuery.data ?? [], [yearsQuery.data]); + const shapes = useMemo(() => shapesQuery.data ?? [], [shapesQuery.data]); + const requestedYear = Number(searchParams.get('jahr')); + const year = years.some((y) => y.year === requestedYear) + ? requestedYear + : (years[years.length - 1]?.year ?? null); + const view = years.find((y) => y.year === year) ?? null; + + const setYear = useCallback( + (value: number) => + setSearchParams( + (params) => { + params.set('jahr', String(value)); + return params; + }, + { replace: true }, + ), + [setSearchParams], + ); + + useEffect(() => { + if (!playing || years.length < 2 || year === null) { + return; + } + const timer = window.setTimeout(() => { + const index = years.findIndex((y) => y.year === year); + setYear(years[(index + 1) % years.length].year); + }, PLAY_INTERVAL_MS); + return () => window.clearTimeout(timer); + }, [playing, years, year, setYear]); + + const scale = useMemo(() => buildScale(years, metric), [years, metric]); + const title = meta ? metricTitle(metric, meta) : ''; + + const handleClose = useCallback(() => setSelectedId(null), []); + const handleSelect = useCallback( + (id: string) => setSelectedId((current) => (current === id ? null : id)), + [], + ); + + const previousView = view ? years[years.indexOf(view) - 1] : undefined; + const delta = view && previousView ? view.canton.count - previousView.canton.count : null; + const carIndex = meta?.groups.indexOf('Personenwagen') ?? -1; + const carDensity = + view && carIndex >= 0 ? metricValue(view.canton, { kind: 'density', group: carIndex }) : null; + + const error = metaQuery.error ?? yearsQuery.error ?? shapesQuery.error; + const loading = metaQuery.isLoading || (meta && meta.years.length === 0) || yearsQuery.isLoading; + + return ( +
+
+
+ + ← + +
+

+ + OpenDataVisualizer + {' '} + / Fahrzeugbestand Thurgau +

+ + Eingelöste Strassenfahrzeuge nach Gemeinde, Fahrzeuggruppe und Marke + +
+
+ {view && ( +
+
+ {formatNumber(view.canton.count)} + Fahrzeuge {view.year} +
+ {delta !== null && previousView && ( +
+ + {delta > 0 ? '+' : delta < 0 ? '−' : '±'} + {formatNumber(Math.abs(delta))} + + gegenüber {previousView.year} +
+ )} + {carDensity !== null && ( +
+ {formatNumber(carDensity)} + Personenwagen pro 1000 Einw. +
+ )} +
+ )} +
+ +
+ + +
+ {meta && year !== null && ( + + )} + {meta && view && ( + + )} +
+ + {loading && ( +
+ Fahrzeugdaten werden geladen… (erster Start lädt die Daten von data.tg.ch und die + Gemeindegrenzen von swisstopo) +
+ )} + {error &&
Fehler beim Laden: {String(error.message)}
} +
+ + {meta && year !== null && years.length > 0 ? ( + + ) : ( +
+ ); +} diff --git a/client/src/styles.css b/client/src/styles.css index a3c5e71..38bf331 100644 --- a/client/src/styles.css +++ b/client/src/styles.css @@ -802,3 +802,68 @@ select { .chart-small { height: 170px; } + +.metric-controls .category-chip.selected { + border-color: var(--accent); + background: #e8f1fb; + font-weight: 600; +} + +.brand-select { + font: inherit; + font-size: 12px; + border: 1px solid var(--border); + border-radius: 999px; + padding: 2px 8px; + background: white; + color: var(--text); +} + +.color-scale { + display: flex; + align-items: center; + justify-content: center; + flex-wrap: wrap; + gap: 4px 10px; + border-top: 1px solid var(--border); + padding-top: 6px; +} + +.color-scale-title { + color: var(--muted); + font-size: 11px; +} + +.color-scale-steps { + display: flex; +} + +.color-scale-step { + display: flex; + flex-direction: column; + align-items: flex-start; + width: 64px; +} + +.color-scale-swatch { + width: 100%; + height: 10px; + border-right: 1px solid white; +} + +.color-scale-label { + font-size: 10px; + color: var(--muted); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.class-table tr.highlight td { + font-weight: 600; +} + +.panel-note { + margin: 6px 0 0; + font-size: 11px; + color: var(--muted); +} diff --git a/client/src/vehicles/metrics.ts b/client/src/vehicles/metrics.ts new file mode 100644 index 0000000..d583749 --- /dev/null +++ b/client/src/vehicles/metrics.ts @@ -0,0 +1,111 @@ +import type { AreaSummary, VehicleMeta, VehicleYearView } from '../api/vehicles'; + +export type Metric = { kind: 'density'; group: number | null } | { kind: 'brand'; brand: number }; + +export interface ColorScale { + breaks: number[]; + colors: string[]; +} + +export const GROUP_COLORS = [ + '#2a78d6', + '#eb6834', + '#1baf7a', + '#eda100', + '#e87ba4', + '#008300', + '#7c5cc4', +]; +export const NO_DATA_COLOR = '#e2e8f0'; +export const OTHER_BRAND = 'Andere'; + +const SCALE_COLORS = ['#eef4fb', '#cfe0f4', '#a4c6ea', '#73a6dd', '#4785cd', '#2763ad', '#16447d']; + +export function groupColor(index: number): string { + return GROUP_COLORS[index % GROUP_COLORS.length]; +} + +export function metricValue(area: AreaSummary, metric: Metric): number | null { + if (metric.kind === 'density') { + const count = metric.group === null ? area.count : (area.groups[metric.group] ?? 0); + return area.population > 0 ? (count / area.population) * 1000 : null; + } + const cars = area.brands.reduce((sum, count) => sum + count, 0); + return cars > 0 ? ((area.brands[metric.brand] ?? 0) / cars) * 100 : null; +} + +export function metricTitle(metric: Metric, meta: VehicleMeta): string { + if (metric.kind === 'density') { + return metric.group === null ? 'Fahrzeuge' : meta.groups[metric.group]; + } + return meta.brands[metric.brand]; +} + +export function metricUnit(metric: Metric): string { + return metric.kind === 'density' ? 'pro 1000 Einwohner' : 'Anteil an den Personenwagen'; +} + +export function metricLabel(metric: Metric, title: string): string { + return metric.kind === 'density' + ? `${title} pro 1000 Einwohner` + : `Anteil ${title} an den Personenwagen`; +} + +export function formatMetric(value: number | null, metric: Metric): string { + if (value === null) { + return '–'; + } + if (metric.kind === 'brand') { + return `${value.toLocaleString('de-CH', { maximumFractionDigits: value < 10 ? 1 : 0 })} %`; + } + return value.toLocaleString('de-CH', { maximumFractionDigits: value < 10 ? 1 : 0 }); +} + +export function buildScale(years: VehicleYearView[], metric: Metric): ColorScale { + const values = years + .flatMap((y) => y.municipalities.map((m) => metricValue(m, metric))) + .filter((v): v is number => v !== null) + .sort((a, b) => a - b); + if (values.length === 0) { + return { breaks: [], colors: [SCALE_COLORS[3]] }; + } + + const breaks: number[] = []; + for (let i = 1; i < SCALE_COLORS.length; i++) { + const value = niceRound(values[Math.floor((values.length * i) / SCALE_COLORS.length)]); + if (value > values[0] && (breaks.length === 0 || value > breaks[breaks.length - 1])) { + breaks.push(value); + } + } + const offset = Math.floor((SCALE_COLORS.length - breaks.length - 1) / 2); + return { breaks, colors: SCALE_COLORS.slice(offset, offset + breaks.length + 1) }; +} + +export function scaleColor(scale: ColorScale, value: number | null): string { + if (value === null) { + return NO_DATA_COLOR; + } + const index = scale.breaks.findIndex((limit) => value < limit); + return scale.colors[index === -1 ? scale.colors.length - 1 : index]; +} + +export function rankOf( + areas: AreaSummary[], + id: string, + metric: Metric, +): { rank: number; total: number } | null { + const ranked = areas + .map((area) => ({ id: area.id, value: metricValue(area, metric) })) + .filter((entry): entry is { id: string; value: number } => entry.value !== null) + .sort((a, b) => b.value - a.value); + const index = ranked.findIndex((entry) => entry.id === id); + return index === -1 ? null : { rank: index + 1, total: ranked.length }; +} + +function niceRound(value: number): number { + if (value <= 0) { + return 0; + } + const magnitude = 10 ** (Math.floor(Math.log10(value)) - 1); + return Math.round(value / magnitude) * magnitude; +}