Add Thurgau vehicle stock map (#3)

Choropleth of the 80 Thurgau municipalities from the road vehicle stock dataset (djs-stv-17), with population from sk-stat-56 and outlines from swisstopo. Also fixes the broken ENV line in the Dockerfile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
This commit is contained in:
Claudio Schaad 2026-11-06 21:43:23 +00:00 committed by clayschaad
parent 39a62255af
commit 688775e742
52 changed files with 2296 additions and 9 deletions

View file

@ -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 `<Subject>TestShould` class per subject, method names `DoThisWhenThat`, Shouldly assertions (no `Assert.*`). HTTP clients are tested with a stub `HttpMessageHandler`, storage with a temp directory cleaned up in `Dispose`.
- TypeScript: Prettier config in `client/.prettierrc.json` (single quotes, width 100).

View file

@ -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"]

View file

@ -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

View file

@ -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

View file

@ -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();

View file

@ -2,6 +2,7 @@
<ItemGroup>
<ProjectReference Include="..\Schaad.OpenData.Traffic\Schaad.OpenData.Traffic.csproj" />
<ProjectReference Include="..\Schaad.OpenData.Vehicles\Schaad.OpenData.Vehicles.csproj" />
<ProjectReference Include="..\Schaad.OpenData.Watercraft\Schaad.OpenData.Watercraft.csproj" />
</ItemGroup>

View file

@ -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;
}
}

View file

@ -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<VehicleYearInfo> Years,
IReadOnlyList<string> Groups,
IReadOnlyList<VehicleTypeInfo> Types,
IReadOnlyList<string> Brands,
DateTimeOffset? LastRefresh);

View file

@ -14,5 +14,9 @@
"Watercraft": {
"DataPath": "../data",
"RefreshInterval": "1.00:00:00"
},
"Vehicles": {
"DataPath": "../data",
"RefreshInterval": "1.00:00:00"
}
}

View file

@ -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<Uri> Requests { get; } = [];
protected override Task<HttpResponseMessage> 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();
}
}

View file

@ -20,6 +20,7 @@
<ItemGroup>
<ProjectReference Include="..\Schaad.OpenData.Traffic\Schaad.OpenData.Traffic.csproj" />
<ProjectReference Include="..\Schaad.OpenData.Vehicles\Schaad.OpenData.Vehicles.csproj" />
<ProjectReference Include="..\Schaad.OpenData.Watercraft\Schaad.OpenData.Watercraft.csproj" />
</ItemGroup>

View file

@ -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<Uri> Requests { get; } = [];
protected override Task<HttpResponseMessage> 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)]);
}
}

View file

@ -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<StockEntry> stock, IReadOnlyList<PopulationEntry>? 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));
}
}

View file

@ -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]);
}
}

View file

@ -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<VehicleOptions> 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<ThurgauVehicleClient>(new HttpClient(), Options);
private readonly MunicipalityBoundaryClient boundaryClient = Substitute.For<MunicipalityBoundaryClient>(new HttpClient(), Options);
private readonly VehicleCacheStorage storage = Substitute.For<VehicleCacheStorage>(Options);
private readonly VehicleDataStore store = new();
private readonly TimeProvider timeProvider = Substitute.For<TimeProvider>();
private readonly VehicleRefresher refresher;
public VehicleRefresherTestShould()
{
timeProvider.GetUtcNow().Returns(Now);
client.GetVersionAsync("djs-stv-17", Arg.Any<CancellationToken>()).Returns(StockVersion);
client.GetVersionAsync("sk-stat-56", Arg.Any<CancellationToken>()).Returns(PopulationVersion);
boundaryClient.FetchAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(call => Outline(call.Arg<string>()));
refresher = new VehicleRefresher(client, boundaryClient, storage, store, Options, timeProvider, NullLogger<VehicleRefresher>.Instance);
}
[Fact]
public async Task FetchEverythingWhenCacheIsEmpty()
{
client.FetchStockAsync(Arg.Any<CancellationToken>()).Returns([Entry(id: "4566"), Entry(id: "4671", municipality: "Kreuzlingen")]);
client.FetchPopulationAsync(Arg.Any<CancellationToken>()).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<CancellationToken>());
}
[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<CancellationToken>());
await client.DidNotReceive().FetchPopulationAsync(Arg.Any<CancellationToken>());
await boundaryClient.DidNotReceive().FetchAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
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<CancellationToken>()).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<CancellationToken>());
await boundaryClient.Received(1).FetchAsync("4401", Arg.Any<CancellationToken>());
}
[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();
}
}

View file

@ -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]]]]);
}

View file

@ -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);

View file

@ -0,0 +1,3 @@
namespace Schaad.OpenData.Vehicles.Analysis;
public sealed record MunicipalityShape(string Id, string Name, string District, double[][][][] Polygons);

View file

@ -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<VehicleYearView> 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<MunicipalityShape> 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<StockEntry> entries,
Dictionary<string, int> groups,
Dictionary<string, int> types,
Dictionary<string, int> 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<string> OrderedGroups(VehicleSnapshot snapshot) =>
ByFrequency(snapshot.Stock, e => e.Group).ToList();
private static List<VehicleTypeInfo> 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<string> OrderedBrands(VehicleSnapshot snapshot) =>
ByFrequency(snapshot.Stock.Where(e => e.Group == PassengerCarGroup), e => e.Brand)
.OrderBy(brand => brand == ThurgauVehicleMapper.OtherBrand)
.ToList();
private static IEnumerable<string> ByFrequency(IEnumerable<StockEntry> entries, Func<StockEntry, string> 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<string, int> IndexOf(IEnumerable<string> 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<PopulationEntry> entries)
{
private readonly Dictionary<string, List<PopulationEntry>> 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;
}
}
}

View file

@ -0,0 +1,7 @@
namespace Schaad.OpenData.Vehicles.Analysis;
public sealed record VehicleOverview(
IReadOnlyList<VehicleYearInfo> Years,
IReadOnlyList<string> Groups,
IReadOnlyList<VehicleTypeInfo> Types,
IReadOnlyList<string> Brands);

View file

@ -0,0 +1,3 @@
namespace Schaad.OpenData.Vehicles.Analysis;
public sealed record VehicleTypeInfo(string Name, string Group);

View file

@ -0,0 +1,3 @@
namespace Schaad.OpenData.Vehicles.Analysis;
public sealed record VehicleYearInfo(int Year, DateOnly ReferenceDate, int Count, int Population);

View file

@ -0,0 +1,7 @@
namespace Schaad.OpenData.Vehicles.Analysis;
public sealed record VehicleYearView(
int Year,
DateOnly ReferenceDate,
AreaSummary Canton,
IReadOnlyList<AreaSummary> Municipalities);

View file

@ -0,0 +1,3 @@
namespace Schaad.OpenData.Vehicles.Models;
public sealed record DatasetVersion(string DatasetId, DateTimeOffset? Modified);

View file

@ -0,0 +1,3 @@
namespace Schaad.OpenData.Vehicles.Models;
public sealed record MunicipalityOutline(string Id, double[][][][] Polygons);

View file

@ -0,0 +1,3 @@
namespace Schaad.OpenData.Vehicles.Models;
public sealed record PopulationEntry(int Year, string MunicipalityId, int Population);

View file

@ -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);

View file

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Http" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Options" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Schaad.OpenData.Tests" />
</ItemGroup>
</Project>

View file

@ -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<VehicleOptions> options)
{
private const int Decimals = 5;
public virtual async Task<MunicipalityOutline?> 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();
}

View file

@ -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; }
}

View file

@ -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; }
}

View file

@ -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<VehicleOptions> options)
{
public virtual async Task<DatasetVersion> 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<IReadOnlyList<StockEntry>> FetchStockAsync(CancellationToken cancellationToken) =>
ThurgauVehicleMapper.MapStock(await ExportAsync<ThurgauStockRecord>(options.Value.StockDatasetId, cancellationToken));
public virtual async Task<IReadOnlyList<PopulationEntry>> FetchPopulationAsync(CancellationToken cancellationToken) =>
ThurgauVehicleMapper.MapPopulation(await ExportAsync<ThurgauPopulationRecord>(options.Value.PopulationDatasetId, cancellationToken));
private async Task<List<T>> ExportAsync<T>(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<T>();
await foreach (var record in JsonSerializer.DeserializeAsyncEnumerable<T>(stream, cancellationToken: cancellationToken))
{
if (record is not null)
{
records.Add(record);
}
}
return records;
}
}

View file

@ -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<StockEntry> MapStock(IEnumerable<ThurgauStockRecord> 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<PopulationEntry> MapPopulation(IEnumerable<ThurgauPopulationRecord> 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();
}

View file

@ -0,0 +1,5 @@
using Schaad.OpenData.Vehicles.Models;
namespace Schaad.OpenData.Vehicles.Storage;
public sealed record VehicleCacheMeta(DatasetVersion? StockVersion, DatasetVersion? PopulationVersion, DateTimeOffset? LastRefresh);

View file

@ -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<VehicleOptions> 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<VehicleSnapshot> LoadAsync(CancellationToken cancellationToken)
{
var meta = await ReadAsync<VehicleCacheMeta>(MetaFileName, cancellationToken);
var stock = await ReadAsync<List<StockEntry>>(StockFileName, cancellationToken) ?? [];
var population = await ReadAsync<List<PopulationEntry>>(PopulationFileName, cancellationToken) ?? [];
var outlines = await ReadAsync<List<MunicipalityOutline>>(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<T?> ReadAsync<T>(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<T>(stream, JsonOptions, cancellationToken);
}
private async Task WriteAsync<T>(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);
}
}

View file

@ -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;
}

View file

@ -0,0 +1,16 @@
using Schaad.OpenData.Vehicles.Models;
namespace Schaad.OpenData.Vehicles.Storage;
public sealed record VehicleSnapshot(
IReadOnlyList<StockEntry> Stock,
IReadOnlyList<PopulationEntry> Population,
IReadOnlyList<MunicipalityOutline> Outlines,
DatasetVersion? StockVersion,
DatasetVersion? PopulationVersion,
DateTimeOffset? LastRefresh)
{
public static readonly VehicleSnapshot Empty = new([], [], [], null, null, null);
public IReadOnlyList<int> Years { get; } = Stock.Select(e => e.Year).Distinct().Order().ToList();
}

View file

@ -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";
}

View file

@ -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<VehicleOptions> options,
ILogger<VehicleRefreshService> 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);
}
}
}

View file

@ -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<VehicleOptions> options,
TimeProvider timeProvider,
ILogger<VehicleRefresher> 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<IReadOnlyList<MunicipalityOutline>> CompleteOutlinesAsync(
IReadOnlyList<MunicipalityOutline> cached,
IReadOnlyList<StockEntry> 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;
}
}

View file

@ -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<VehicleOptions>(configuration.GetSection(VehicleOptions.SectionName));
services.TryAddSingleton(TimeProvider.System);
services.AddSingleton<VehicleDataStore>();
services.AddSingleton<VehicleCacheStorage>();
services.AddSingleton<VehicleRefresher>();
services.AddHostedService<VehicleRefreshService>();
services.AddHttpClient<ThurgauVehicleClient>(client =>
{
client.Timeout = TimeSpan.FromMinutes(2);
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
});
services.AddHttpClient<MunicipalityBoundaryClient>(client =>
{
client.Timeout = TimeSpan.FromSeconds(30);
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
});
return services;
}
}

View file

@ -0,0 +1,40 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 450">
<defs>
<linearGradient id="land" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#eef2ec"/>
<stop offset="1" stop-color="#e3e8e1"/>
</linearGradient>
<filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
<feDropShadow dx="0" dy="2" stdDeviation="3" flood-color="#0f172a" flood-opacity="0.25"/>
</filter>
</defs>
<rect width="800" height="450" fill="url(#land)"/>
<path d="M800 20 C730 50 680 80 640 96 C700 70 760 50 800 46 Z" fill="#cfe0ee"/>
<g filter="url(#shadow)" stroke="#ffffff" stroke-width="3" stroke-linejoin="round">
<path d="M110 230 L170 168 L240 180 L262 250 L200 300 L130 288 Z" fill="#a4c6ea"/>
<path d="M170 168 L230 110 L310 118 L322 176 L240 180 Z" fill="#73a6dd"/>
<path d="M240 180 L322 176 L370 222 L340 290 L262 250 Z" fill="#4785cd"/>
<path d="M130 288 L200 300 L262 250 L340 290 L310 352 L210 366 L150 336 Z" fill="#cfe0f4"/>
<path d="M310 118 L400 100 L452 150 L420 210 L370 222 L322 176 Z" fill="#2763ad"/>
<path d="M370 222 L420 210 L490 238 L470 310 L400 330 L340 290 Z" fill="#73a6dd"/>
<path d="M310 352 L340 290 L400 330 L392 384 L330 396 Z" fill="#a4c6ea"/>
<path d="M400 100 L480 80 L540 112 L520 176 L452 150 Z" fill="#4785cd"/>
<path d="M452 150 L520 176 L560 220 L490 238 L420 210 Z" fill="#16447d"/>
<path d="M490 238 L560 220 L620 258 L600 320 L530 330 L470 310 Z" fill="#a4c6ea"/>
<path d="M540 112 L620 96 L680 130 L640 190 L560 220 L520 176 Z" fill="#73a6dd"/>
<path d="M560 220 L640 190 L700 214 L690 262 L620 258 Z" fill="#2763ad"/>
<path d="M400 330 L470 310 L530 330 L520 380 L450 396 L392 384 Z" fill="#cfe0f4"/>
</g>
<path d="M452 150 L520 176 L560 220 L490 238 L420 210 Z" fill="none" stroke="#0f172a" stroke-width="4" stroke-linejoin="round"/>
<g transform="translate(560 384)">
<rect x="-8" y="-14" width="212" height="48" rx="10" fill="#ffffff" fill-opacity="0.94" stroke="#e2e8f0"/>
<rect x="4" y="-4" width="28" height="12" fill="#eef4fb"/>
<rect x="32" y="-4" width="28" height="12" fill="#cfe0f4"/>
<rect x="60" y="-4" width="28" height="12" fill="#a4c6ea"/>
<rect x="88" y="-4" width="28" height="12" fill="#73a6dd"/>
<rect x="116" y="-4" width="28" height="12" fill="#4785cd"/>
<rect x="144" y="-4" width="28" height="12" fill="#2763ad"/>
<rect x="172" y="-4" width="24" height="12" fill="#16447d"/>
<rect x="4" y="16" width="120" height="6" rx="3" fill="#cbd5e1"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View file

@ -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() {
<Route path="/" element={<HomePage />} />
<Route path="/verkehr/thurgau" element={<TrafficThurgauPage />} />
<Route path="/schifffahrt/thurgau" element={<WatercraftThurgauPage />} />
<Route path="/fahrzeuge/thurgau" element={<VehiclesThurgauPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
);

View file

@ -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<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
return (await response.json()) as T;
}
export const fetchVehicleMeta = () => getJson<VehicleMeta>('/api/vehicles/meta');
export const fetchVehicleYears = () => getJson<VehicleYearView[]>('/api/vehicles/years');
export const fetchMunicipalityShapes = () =>
getJson<MunicipalityShape[]>('/api/vehicles/municipalities');

View file

@ -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 (
<div className="legend category-legend metric-controls">
<div className="dimension-tabs" role="tablist" aria-label="Kennzahl">
<button
type="button"
role="tab"
aria-selected={metric.kind === 'density'}
className={metric.kind === 'density' ? 'active' : ''}
onClick={() => metric.kind !== 'density' && onMetricChange({ kind: 'density', group: 0 })}
>
Fahrzeugdichte
</button>
<button
type="button"
role="tab"
aria-selected={metric.kind === 'brand'}
className={metric.kind === 'brand' ? 'active' : ''}
onClick={() =>
metric.kind !== 'brand' &&
brandOrder.length > 0 &&
onMetricChange({ kind: 'brand', brand: brandOrder[0].index })
}
>
Automarken
</button>
</div>
{metric.kind === 'density' ? (
<div className="category-chips">
<button
type="button"
className={`category-chip ${metric.group === null ? 'selected' : ''}`}
aria-pressed={metric.group === null}
onClick={() => onMetricChange({ kind: 'density', group: null })}
>
Alle Fahrzeuge
<span className="chip-count">{formatNumber(canton.count)}</span>
</button>
{meta.groups.map((group, index) => (
<button
key={group}
type="button"
className={`category-chip ${metric.group === index ? 'selected' : ''}`}
aria-pressed={metric.group === index}
onClick={() => onMetricChange({ kind: 'density', group: index })}
>
<span className="legend-dot small" style={{ background: groupColor(index) }} />
{group}
<span className="chip-count">{formatNumber(canton.groups[index] ?? 0)}</span>
</button>
))}
</div>
) : (
<div className="category-chips">
{quickBrands.map((brand) => (
<button
key={brand.name}
type="button"
className={`category-chip ${selectedBrand === brand.index ? 'selected' : ''}`}
aria-pressed={selectedBrand === brand.index}
onClick={() => onMetricChange({ kind: 'brand', brand: brand.index })}
>
{brand.name}
<span className="chip-count">{formatNumber(brand.count)}</span>
</button>
))}
<select
className="brand-select"
aria-label="Weitere Marken"
value={
selectedBrand !== null && !quickBrands.some((b) => b.index === selectedBrand)
? selectedBrand
: ''
}
onChange={(event) =>
event.target.value !== '' &&
onMetricChange({ kind: 'brand', brand: Number(event.target.value) })
}
>
<option value="">Weitere Marken…</option>
{brandOrder.slice(QUICK_BRANDS).map((brand) => (
<option key={brand.name} value={brand.index}>
{brand.name} ({formatNumber(brand.count)})
</option>
))}
</select>
</div>
)}
<div className="color-scale" aria-label="Farbskala">
<span className="color-scale-title">
{metricUnit(metric)}
{brandValue !== null && ` · Kanton ${formatMetric(brandValue, metric)}`}
</span>
<div className="color-scale-steps">
{scale.colors.map((color, i) => (
<div key={color} className="color-scale-step">
<span className="color-scale-swatch" style={{ background: color }} />
<span className="color-scale-label">
{i === 0
? `< ${formatMetric(scale.breaks[0] ?? null, metric)}`
: `≥ ${formatMetric(scale.breaks[i - 1], metric)}`}
</span>
</div>
))}
</div>
</div>
</div>
);
}

View file

@ -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 (
<aside className="station-panel">
<header className="station-panel-header">
<h2>Gemeinde</h2>
<button type="button" className="close-button" onClick={onClose} aria-label="Schliessen">
×
</button>
</header>
<p className="muted">Für {year} sind keine Fahrzeuge verzeichnet.</p>
</aside>
);
}
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 (
<aside className="station-panel">
<header className="station-panel-header">
<div>
<h2>{area.name}</h2>
<p>
{id === null
? `Alle ${view.municipalities.length} Gemeinden`
: `Politische Gemeinde · Bezirk ${area.district ?? '–'}`}
{` · Stichtag ${formatDate(view.referenceDate, { weekday: undefined })}`}
</p>
</div>
{id !== null && (
<button
type="button"
className="close-button"
onClick={onClose}
aria-label="Zurück zum Kanton"
title="Zurück zum Kanton"
>
×
</button>
)}
</header>
<section className="stat-tiles">
<div className="stat-tile">
<span className="stat-tile-value">{formatNumber(area.count)}</span>
<span className="stat-tile-label">
Fahrzeuge
{id !== null && ` · ${percent(area.count, view.canton.count)} des Kantons`}
</span>
{delta !== null && (
<span className={`stat-tile-delta ${delta > 0 ? 'up' : delta < 0 ? 'down' : ''}`}>
{delta > 0 ? '▲ +' : delta < 0 ? '▼ −' : '± '}
{formatNumber(Math.abs(delta))} gegenüber {years[yearIndex - 1].year}
</span>
)}
</div>
<div className="stat-tile">
<span className="stat-tile-value">{formatNumber(area.population)}</span>
<span className="stat-tile-label">Einwohner (ständige Wohnbevölkerung)</span>
</div>
<div className="stat-tile">
<span className="stat-tile-value">{density !== null ? formatNumber(density) : '–'}</span>
<span className="stat-tile-label">
{showsCarDensity ? 'Fahrzeuge' : 'Personenwagen'} pro 1000 Einwohner
</span>
</div>
<div className="stat-tile">
<span className="stat-tile-value">{formatMetric(value, metric)}</span>
<span className="stat-tile-label">
{metricLabel(metric, metricTitle)}
{rank && ` · Rang ${rank.rank} von ${rank.total}`}
</span>
</div>
</section>
<section>
<h3>Fahrzeuggruppen {year}</h3>
<table className="class-table category-table">
<thead>
<tr>
<th>Gruppe</th>
<th>Fahrzeuge</th>
<th>Anteil</th>
</tr>
</thead>
<tbody>
{meta.groups.map((group, i) => (
<tr
key={group}
className={metric.kind === 'density' && metric.group === i ? 'highlight' : ''}
>
<td>
<span className="legend-dot small" style={{ background: groupColor(i) }} />
{group}
</td>
<td>{formatNumber(area.groups[i] ?? 0)}</td>
<td className="share-cell">
<span
className="share-bar"
style={{
width: `${area.count > 0 ? ((area.groups[i] ?? 0) / area.count) * 100 : 0}%`,
background: groupColor(i),
}}
/>
<span>{percent(area.groups[i] ?? 0, area.count)}</span>
</td>
</tr>
))}
</tbody>
</table>
</section>
<section>
<h3>Häufigste Automarken {year}</h3>
<div className="chart" style={{ height: `${Math.max(140, topBrands.length * 20 + 40)}px` }}>
<Bar
options={brandOptions}
data={{
labels: topBrands.map((b) => b.name),
datasets: [
{
data: topBrands.map((b) => b.count),
backgroundColor: topBrands.map((b) =>
b.name === selectedBrand ? BRAND_SELECTED_COLOR : BRAND_COLOR,
),
borderRadius: 3,
borderSkipped: 'start',
},
],
}}
/>
</div>
<p className="panel-note">
Marken mit weniger als 5 Fahrzeugen pro Gemeinde und Fahrzeugart sind in der Quelle unter
«Andere» zusammengefasst ({formatNumber(cars - brands.reduce((s, b) => s + b.count, 0))}{' '}
Personenwagen).
</p>
</section>
<section>
<h3>Häufigste Fahrzeugarten {year}</h3>
<table className="class-table">
<tbody>
{types.map((type) => (
<tr key={type.name}>
<td>
<span
className="legend-dot small"
style={{ background: groupColor(meta.groups.indexOf(type.group)) }}
/>
{type.name}
</td>
<td>{formatNumber(type.count)}</td>
</tr>
))}
</tbody>
</table>
</section>
<section>
<h3>
Bestand {years[0].year}–{years[years.length - 1].year} nach Fahrzeuggruppe
</h3>
<div className="chart">
<Bar
options={trendOptions}
data={{
labels: years.map((y) => String(y.year)),
datasets: meta.groups.map((group, i) => ({
label: group,
data: years.map((y) => findArea(y, id)?.groups[i] ?? 0),
backgroundColor: groupColor(i),
borderColor: '#ffffff',
borderWidth: { top: 1 },
borderSkipped: false,
})),
}}
/>
</div>
</section>
</aside>
);
}
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)} %`;
}

View file

@ -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 =
'<a href="https://data.tg.ch/explore/dataset/djs-stv-17/">Strassenverkehrsamt Thurgau</a>, ' +
'<a href="https://www.swisstopo.admin.ch/de/landschaftsmodell-swissboundaries3d">swissBOUNDARIES3D</a>';
const BORDER_COLOR = '#ffffff';
const SELECTED_BORDER_COLOR = '#0f172a';
export function VehicleMap({
shapes,
areas,
metric,
metricTitle,
scale,
selectedId,
onSelect,
}: VehicleMapProps) {
const containerRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<L.Map | null>(null);
const layersRef = useRef<Map<string, L.Polygon>>(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 <div ref={containerRef} className="traffic-map" />;
}
function tooltipHtml(
name: string,
area: AreaSummary | undefined,
metric: Metric,
metricTitle: string,
value: number | null,
): string {
if (!area) {
return `<strong>${escapeHtml(name)}</strong><br/><span class="muted">keine Daten</span>`;
}
return (
`<strong>${escapeHtml(name)}</strong> · Bezirk ${escapeHtml(area.district ?? '')}<br/>` +
`<div class="tooltip-row">${escapeHtml(metricLabel(metric, metricTitle))}` +
`<span class="tooltip-value">${formatMetric(value, metric)}</span></div>` +
`<div class="tooltip-row muted">${formatNumber(area.count)} Fahrzeuge · ${formatNumber(area.population)} Einwohner</div>`
);
}

View file

@ -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;

View file

@ -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',
},
];

View file

@ -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<Metric>({ kind: 'density', group: 0 });
const [selectedId, setSelectedId] = useState<string | null>(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 (
<div className="app with-panel">
<header className="app-header">
<div className="title-row">
<Link to="/" className="back-link" aria-label="Zur Übersicht" title="Zur Übersicht">
←
</Link>
<div className="title">
<h1>
<Link to="/" className="brand-link">
OpenDataVisualizer
</Link>{' '}
<span className="title-separator">/</span> Fahrzeugbestand Thurgau
</h1>
<span className="subtitle">
Eingelöste Strassenfahrzeuge nach Gemeinde, Fahrzeuggruppe und Marke
</span>
</div>
</div>
{view && (
<div className="stats">
<div>
<span className="stat-value">{formatNumber(view.canton.count)}</span>
<span className="stat-label">Fahrzeuge {view.year}</span>
</div>
{delta !== null && previousView && (
<div>
<span className="stat-value">
{delta > 0 ? '+' : delta < 0 ? '−' : '±'}
{formatNumber(Math.abs(delta))}
</span>
<span className="stat-label">gegenüber {previousView.year}</span>
</div>
)}
{carDensity !== null && (
<div>
<span className="stat-value">{formatNumber(carDensity)}</span>
<span className="stat-label">Personenwagen pro 1000 Einw.</span>
</div>
)}
</div>
)}
</header>
<main className="map-area">
<VehicleMap
shapes={shapes}
areas={view?.municipalities ?? []}
metric={metric}
metricTitle={title}
scale={scale}
selectedId={selectedId}
onSelect={handleSelect}
/>
<div className="overlay-bottom">
{meta && year !== null && (
<YearControls
years={meta.years}
year={year}
playing={playing}
onYearChange={setYear}
onPlayingChange={setPlaying}
/>
)}
{meta && view && (
<MetricControls
meta={meta}
canton={view.canton}
metric={metric}
scale={scale}
onMetricChange={setMetric}
/>
)}
</div>
{loading && (
<div className="notice">
Fahrzeugdaten werden geladen… (erster Start lädt die Daten von data.tg.ch und die
Gemeindegrenzen von swisstopo)
</div>
)}
{error && <div className="notice error">Fehler beim Laden: {String(error.message)}</div>}
</main>
{meta && year !== null && years.length > 0 ? (
<MemoMunicipalityPanel
meta={meta}
years={years}
id={selectedId}
year={year}
metric={metric}
metricTitle={title}
onClose={handleClose}
/>
) : (
<aside className="station-panel" />
)}
<footer className="app-footer">
Quelle:{' '}
<a href={meta?.sourceUrl} target="_blank" rel="noreferrer">
{meta?.publisher ?? 'Strassenverkehrsamt Kanton Thurgau'}
</a>{' '}
· Lizenz {meta?.license ?? 'CC BY 4.0'} ·{' '}
<a href={meta?.populationSourceUrl} target="_blank" rel="noreferrer">
Bevölkerung: Dienststelle für Statistik Thurgau
</a>{' '}
· Gemeindegrenzen: swisstopo
{meta?.lastRefresh &&
` · aktualisiert ${new Date(meta.lastRefresh).toLocaleString('de-CH')}`}
</footer>
</div>
);
}

View file

@ -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);
}

View file

@ -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;
}