diff --git a/CLAUDE.md b/CLAUDE.md index bfa245f..bcecc55 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,11 +56,11 @@ The cache accumulates history beyond the source's two-week window; refreshes onl The source has one point per station and directions as text (`nach X`, `von X`, or just `X`). `StationGeometryService` turns that into a road polyline per direction, oriented in driving direction: -1. `SwisstopoClient.GetRoadSegmentsAsync` loads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200). `verkehrsbedeutung != 999998` marks main roads, `objektart <= 11` drivable roads (higher values are paths and lane markings). +1. `SwisstopoClient.GetRoadSegmentsAsync` loads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200) with their street name. `verkehrsbedeutung != 999998` marks main roads; `objektart` 12–19 are paths and lane markings (15/16 seen in practice), everything else is a road — note that 20 is a regular road type. 2. `RoadPathBuilder.BuildRoadPath` snaps to a main road within 60 m (else the nearest drivable road), stitches connected segments (≤ 60° turn, penalty for changing road class) and trims to ±300 m. -3. Stations named `… Kreisel …` sit on a roundabout arm: `BuildArmPath` follows every road segment within 80 m outward (600 m) and keeps the one that gets furthest toward the target town (a roundabout ring loops back and loses); it falls back to `BuildRoadPath`. -4. `SwisstopoClient.FindPlaceAsync` geocodes the target town (SearchServer, municipalities + gazetteer, label must contain the name with ä→ae etc., nearest candidate wins — "Landquart" is also a place in Arbon). Names with `/` are split, since the SearchServer returns 503 for slashes. -5. `RoadPathBuilder.Orient` points each direction toward (`nach`) or away from (`von`) its target; the two directions of a station are always opposite. +3. Stations named `… Kreisel …` sit on a roundabout arm. The roundabout centre is the average position of all stations sharing the name part before ` - ` (e.g. the four `WEINFELDEN Kreisel West` stations), and the arm target is a point 3 km outward from that centre through the station (`StationGeometryService.OutwardTarget`), so no geocoding is needed. `BuildArmPath` follows every segment within 80 m outward for 600 m, preferring segments named like the station's address (the arm's street), and keeps the arm that gets furthest outward; a ring loops back and is rejected. A roundabout with a single station falls back to the geocoded target. +4. Otherwise `SwisstopoClient.FindPlaceAsync` geocodes the target town (SearchServer, municipalities + gazetteer, label must contain the name with ä→ae etc., nearest candidate wins — "Landquart" is also a place in Arbon). Names with `/` are split, since the SearchServer returns 503 for slashes. Directions can be `nach`/`zur`/`zum`/`Richtung X` (toward) or `von`/`vom X` (from); targets like `Umfahrung`, `Zentrum` or street names cannot be geocoded. +5. `RoadPathBuilder.Orient` points each direction toward or away from its target; the two directions of a station are always opposite. When the geometry algorithm changes, bump `GeometryFileName` in `TrafficCacheStorage` so all stations are rebuilt. diff --git a/Schaad.OpenData.Tests/DirectionTargetTestShould.cs b/Schaad.OpenData.Tests/DirectionTargetTestShould.cs index b2d9891..5f17af9 100644 --- a/Schaad.OpenData.Tests/DirectionTargetTestShould.cs +++ b/Schaad.OpenData.Tests/DirectionTargetTestShould.cs @@ -16,6 +16,12 @@ public class DirectionTargetTestShould DirectionTarget.Parse("von Frauenfeld").ShouldBe(new DirectionTarget("Frauenfeld", false)); } + [Fact] + public void ParseDestinationWhenDirectionStartsWithZur() + { + DirectionTarget.Parse("zur Umfahrung").ShouldBe(new DirectionTarget("Umfahrung", true)); + } + [Fact] public void TreatPlainNameAsDestinationWhenDirectionHasNoPrefix() { diff --git a/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs b/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs index c7ce702..b9a8efe 100644 --- a/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs +++ b/Schaad.OpenData.Tests/StationGeometryServiceTestShould.cs @@ -21,18 +21,74 @@ public class StationGeometryServiceTestShould swisstopoClient.FindPlaceAsync("Wilen", Arg.Any(), Arg.Any()).Returns((GeoPoint?)null); swisstopoClient.FindPlaceAsync("Busswil", Arg.Any(), Arg.Any()).Returns(TestData.Meters(0, 2000)); - var geometry = await service.BuildAsync(TestData.Station(413, "Wilen/Busswil", "Gloten"), CancellationToken.None); + var geometry = await service.BuildAsync(TestData.Station(413, "Wilen/Busswil", "Gloten"), [], CancellationToken.None); await swisstopoClient.DidNotReceive().FindPlaceAsync("Wilen/Busswil", Arg.Any(), Arg.Any()); geometry.Directions[0].Path[^1].Lat.ShouldBeGreaterThan(TestData.Origin.Lat); } + private static Station Arm(int code, string name, (double East, double North) offset, string address, params string[] directions) => + TestData.Station(code, directions) with + { + Name = name, + Address = address, + Location = TestData.Meters(offset.East, offset.North), + }; + + private static Station[] KreiselWest() => + [ + Arm(1, "WEINFELDEN Kreisel West - Weinfelden", (30, 0), "Frauenfelderstrasse", "nach Weinfelden", "von Weinfelden"), + Arm(2, "WEINFELDEN Kreisel West - Umfahrung", (0, -30), "Dunantstrasse", "von Umfahrung", "zur Umfahrung"), + Arm(3, "WEINFELDEN Kreisel West - Märstetten", (-30, 0), "Frauenfelderstrasse", "nach Maerstetten", "von Maerstetten"), + Arm(4, "WEINFELDEN Kreisel West - Egelseestrasse", (0, 30), "Egelseestrasse", "von Egelseestrasse", "zur Egelseestrasse"), + ]; + + [Fact] + public void PointAwayFromRoundaboutCenterWhenComputingOutwardTarget() + { + var stations = KreiselWest(); + + var target = StationGeometryService.OutwardTarget(stations[1], stations)!.Value; + + target.Lat.ShouldBeLessThan(TestData.Meters(0, -2900).Lat); + target.Lon.ShouldBe(TestData.Origin.Lon, 1e-6); + } + + [Fact] + public void ReturnNoOutwardTargetWhenRoundaboutHasSingleStation() + { + var station = KreiselWest()[0]; + + StationGeometryService.OutwardTarget(station, [station]).ShouldBeNull(); + } + + [Fact] + public async Task FollowArmNamedLikeStationAddressWhenTargetIsNotAPlace() + { + var stations = KreiselWest(); + swisstopoClient.GetRoadSegmentsAsync(default, default, default).ReturnsForAnyArgs( + [ + new RoadSegment([TestData.Meters(0, -28), TestData.Meters(-80, 60)], true, true, null), + new RoadSegment([TestData.Meters(0, -10), TestData.Meters(0, -200)], true, true, "Dunantstrasse"), + new RoadSegment([TestData.Meters(0, -200), TestData.Meters(0, -700)], true, true, "Dunantstrasse"), + ]); + + var geometry = await service.BuildAsync(stations[1], stations, CancellationToken.None); + + await swisstopoClient.DidNotReceiveWithAnyArgs().FindPlaceAsync(default!, default, default); + var outward = geometry.Directions.Single(d => d.Direction == "zur Umfahrung").Path; + var inward = geometry.Directions.Single(d => d.Direction == "von Umfahrung").Path; + outward[^1].Lat.ShouldBeLessThan(outward[0].Lat); + outward[^1].Lon.ShouldBe(TestData.Origin.Lon, 1e-6); + inward[^1].ShouldBe(outward[0]); + } + [Fact] public async Task UseStraightPathWhenNoRoadIsFound() { swisstopoClient.FindPlaceAsync(default!, default, default).ReturnsForAnyArgs(TestData.Meters(1000, 0)); - var geometry = await service.BuildAsync(TestData.Station(1, "nach A", "von A"), CancellationToken.None); + var geometry = await service.BuildAsync(TestData.Station(1, "nach A", "von A"), [], CancellationToken.None); geometry.FollowsRoad.ShouldBeFalse(); geometry.Directions.Count.ShouldBe(2); diff --git a/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs b/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs index 5c3ea47..726cf8c 100644 --- a/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs +++ b/Schaad.OpenData.Tests/SwisstopoClientTestShould.cs @@ -97,15 +97,17 @@ public class SwisstopoClientTestShould { var body = """ {"results":[ - {"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{"objektart":9}}, - {"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"objektart":15}} + {"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{"objektart":9,"strassenname":"Dunantstrasse"}}, + {"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"objektart":15}}, + {"geometry":{"type":"LineString","coordinates":[[9.1,47.7],[9.2,47.7]]},"properties":{"objektart":20}} ]} """; var client = Client(new StubHandler((HttpStatusCode.OK, body))); var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None); - segments.Select(s => s.IsDrivable).ShouldBe([true, false]); + segments.Select(s => s.IsDrivable).ShouldBe([true, false, true]); + segments.Select(s => s.Name).ShouldBe(["Dunantstrasse", null, null]); } [Fact] diff --git a/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs b/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs index 99a33a2..97245a3 100644 --- a/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs +++ b/Schaad.OpenData.Traffic/Geometry/DirectionTarget.cs @@ -2,17 +2,26 @@ namespace Schaad.OpenData.Traffic.Geometry; public sealed record DirectionTarget(string Place, bool IsDestination) { + private static readonly string[] DestinationPrefixes = ["nach ", "zur ", "zum ", "richtung "]; + private static readonly string[] OriginPrefixes = ["von ", "vom "]; + public static DirectionTarget Parse(string direction) { var text = direction.Trim(); - if (text.StartsWith("nach ", StringComparison.OrdinalIgnoreCase)) + foreach (var prefix in OriginPrefixes) { - return new DirectionTarget(text[5..].Trim(), true); + if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + return new DirectionTarget(text[prefix.Length..].Trim(), false); + } } - if (text.StartsWith("von ", StringComparison.OrdinalIgnoreCase)) + foreach (var prefix in DestinationPrefixes) { - return new DirectionTarget(text[4..].Trim(), false); + if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + return new DirectionTarget(text[prefix.Length..].Trim(), true); + } } return new DirectionTarget(text, true); diff --git a/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs b/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs index cd8ec1d..d7bc16c 100644 --- a/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs +++ b/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs @@ -13,15 +13,16 @@ public static class RoadPathBuilder private const double ArmSearchMeters = 80; private const float ArmDistancePenalty = 2f; + private const float MinimumArmProgressMeters = 30f; - private sealed record RoadLine(List Points, bool IsMainRoad); + private sealed record RoadLine(List Points, bool IsMainRoad, string? Name); private static List ToLines(IReadOnlyList segments, LocalProjection projection) { var usable = segments.Where(s => s.Points.Count >= 2).ToList(); var drivable = usable.Where(s => s.IsDrivable).ToList(); return (drivable.Count > 0 ? drivable : usable) - .Select(s => new RoadLine(s.Points.Select(projection.ToLocal).ToList(), s.IsMainRoad)) + .Select(s => new RoadLine(s.Points.Select(projection.ToLocal).ToList(), s.IsMainRoad, s.Name)) .ToList(); } @@ -54,7 +55,12 @@ public static class RoadPathBuilder return trimmed.Count >= 2 ? trimmed.Select(projection.ToGeo).ToList() : null; } - public static IReadOnlyList? BuildArmPath(GeoPoint station, IReadOnlyList segments, GeoPoint target, double lengthMeters) + public static IReadOnlyList? BuildArmPath( + GeoPoint station, + IReadOnlyList segments, + GeoPoint target, + double lengthMeters, + string? roadName = null) { var projection = new LocalProjection(station); var toward = projection.ToLocal(target); @@ -65,22 +71,33 @@ public static class RoadPathBuilder toward = Vector2.Normalize(toward); var lines = ToLines(segments, projection); - var best = lines - .Select((line, index) => (Index: index, Distance: DistanceToPolyline(Vector2.Zero, line.Points))) + var nearby = lines + .Select((line, index) => (Index: index, Distance: DistanceToPolyline(Vector2.Zero, line.Points), line.Name)) .Where(c => c.Distance <= ArmSearchMeters) + .ToList(); + var named = nearby + .Where(c => !string.IsNullOrEmpty(roadName) && string.Equals(c.Name, roadName, StringComparison.OrdinalIgnoreCase)) + .Select(c => (c.Index, c.Distance)) + .ToList(); + var all = nearby.Select(c => (c.Index, c.Distance)).ToList(); + + var arm = BestArm(lines, named, toward, lengthMeters) ?? BestArm(lines, all, toward, lengthMeters); + return arm?.Select(projection.ToGeo).ToList(); + } + + private static List? BestArm(List lines, List<(int Index, double Distance)> candidates, Vector2 toward, double lengthMeters) => + candidates .Select(c => { var arm = FollowArm(lines, c.Index, toward, lengthMeters); - var progress = arm.Count >= 2 && Length(arm) >= MinimumSideLengthMeters ? Vector2.Dot(arm[^1], toward) : float.MinValue; - return (Arm: arm, Score: progress - ArmDistancePenalty * c.Distance); + var isValid = arm.Count >= 2 && Length(arm) >= MinimumSideLengthMeters && Vector2.Dot(arm[^1], toward) >= MinimumArmProgressMeters; + return (Arm: arm, IsValid: isValid, Score: Vector2.Dot(arm.Count > 0 ? arm[^1] : Vector2.Zero, toward) - ArmDistancePenalty * c.Distance); }) - .Where(c => c.Score > float.MinValue / 2) + .Where(c => c.IsValid) .OrderByDescending(c => c.Score) + .Select(c => c.Arm) .FirstOrDefault(); - return best.Arm?.Select(projection.ToGeo).ToList(); - } - private static List FollowArm(List lines, int start, Vector2 toward, double lengthMeters) { var chain = new List(lines[start].Points); diff --git a/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs b/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs index f00f3c5..03c2ed7 100644 --- a/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs +++ b/Schaad.OpenData.Traffic/Geometry/RoadSegment.cs @@ -2,4 +2,4 @@ using Schaad.OpenData.Traffic.Models; namespace Schaad.OpenData.Traffic.Geometry; -public sealed record RoadSegment(IReadOnlyList Points, bool IsMainRoad, bool IsDrivable = true); +public sealed record RoadSegment(IReadOnlyList Points, bool IsMainRoad, bool IsDrivable = true, string? Name = null); diff --git a/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs b/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs index 38b7394..5ee3cb9 100644 --- a/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs +++ b/Schaad.OpenData.Traffic/Geometry/StationGeometryService.cs @@ -6,22 +6,28 @@ public class StationGeometryService(SwisstopoClient swisstopoClient) { private const double HalfPathLengthMeters = 300; private const double SearchRadiusMeters = 650; + private const double MetersPerDegreeLat = 111_320; + private const double MinimumArmOffsetMeters = 3; + private const double OutwardTargetMeters = 3000; + private const string RoundaboutMarker = "Kreisel"; - public virtual async Task BuildAsync(Station station, CancellationToken cancellationToken) + public virtual async Task BuildAsync(Station station, IReadOnlyList stations, CancellationToken cancellationToken) { + var isRoundaboutArm = station.Name.Contains(RoundaboutMarker, StringComparison.OrdinalIgnoreCase); + var outwardTarget = isRoundaboutArm ? OutwardTarget(station, stations) : null; + var directions = new List(); foreach (var direction in station.Directions) { var target = DirectionTarget.Parse(direction); - directions.Add(new ResolvedDirection(direction, target, await FindPlaceAsync(target.Place, station.Location, cancellationToken))); + var location = outwardTarget ?? await FindPlaceAsync(target.Place, station.Location, cancellationToken); + directions.Add(new ResolvedDirection(direction, target, location)); } var targetLocation = directions.Select(d => d.TargetLocation).FirstOrDefault(l => l is not null); - var isRoundaboutArm = station.Name.Contains("Kreisel", StringComparison.OrdinalIgnoreCase) && targetLocation is not null; - var segments = await swisstopoClient.GetRoadSegmentsAsync(station.Location, SearchRadiusMeters, cancellationToken); - var roadPath = (isRoundaboutArm - ? RoadPathBuilder.BuildArmPath(station.Location, segments, targetLocation!.Value, 2 * HalfPathLengthMeters) + var roadPath = (isRoundaboutArm && targetLocation is { } armTarget + ? RoadPathBuilder.BuildArmPath(station.Location, segments, armTarget, 2 * HalfPathLengthMeters, station.Address) : null) ?? RoadPathBuilder.BuildRoadPath(station.Location, segments, HalfPathLengthMeters); @@ -30,6 +36,32 @@ public class StationGeometryService(SwisstopoClient swisstopoClient) return new StationGeometry(station.Code, roadPath is not null, RoadPathBuilder.Orient(station.Location, path, directions)); } + internal static GeoPoint? OutwardTarget(Station station, IReadOnlyList stations) + { + var key = RoundaboutKey(station.Name); + var siblings = stations.Where(s => RoundaboutKey(s.Name) == key).ToList(); + if (siblings.Count < 2) + { + return null; + } + + var center = new GeoPoint(siblings.Average(s => s.Location.Lat), siblings.Average(s => s.Location.Lon)); + var deltaLat = station.Location.Lat - center.Lat; + var deltaLon = station.Location.Lon - center.Lon; + var meters = Math.Sqrt( + Math.Pow(deltaLat * MetersPerDegreeLat, 2) + + Math.Pow(deltaLon * MetersPerDegreeLat * Math.Cos(center.Lat * Math.PI / 180), 2)); + if (meters < MinimumArmOffsetMeters) + { + return null; + } + + var scale = OutwardTargetMeters / meters; + return new GeoPoint(center.Lat + deltaLat * scale, center.Lon + deltaLon * scale); + } + + private static string RoundaboutKey(string name) => name.Split(" - ", 2)[0].Trim(); + private async Task FindPlaceAsync(string place, GeoPoint near, CancellationToken cancellationToken) { foreach (var part in place.Split('/', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) diff --git a/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs b/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs index 327abb0..f811b1f 100644 --- a/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs +++ b/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs @@ -13,7 +13,8 @@ public partial class SwisstopoClient(HttpClient httpClient) private const int MaxRetries = 2; private const int PageSize = 200; private const int MaxPages = 5; - private const int MaxDrivableObjectKind = 11; + private const int FirstNonRoadObjectKind = 12; + private const int LastNonRoadObjectKind = 19; public virtual async Task> GetRoadSegmentsAsync(GeoPoint center, double radiusMeters, CancellationToken cancellationToken) { @@ -61,7 +62,10 @@ public partial class SwisstopoClient(HttpClient httpClient) var isDrivable = !hasProperties || !properties.TryGetProperty("objektart", out var kind) || kind.ValueKind != JsonValueKind.Number - || kind.GetInt32() <= MaxDrivableObjectKind; + || kind.GetInt32() is < FirstNonRoadObjectKind or > LastNonRoadObjectKind; + var name = hasProperties && properties.TryGetProperty("strassenname", out var streetName) && streetName.ValueKind == JsonValueKind.String + ? streetName.GetString() + : null; var coordinates = geometry.GetProperty("coordinates"); var parts = geometry.GetProperty("type").GetString() switch @@ -74,7 +78,8 @@ public partial class SwisstopoClient(HttpClient httpClient) return parts.Select(part => new RoadSegment( part.EnumerateArray().Select(p => new GeoPoint(p[1].GetDouble(), p[0].GetDouble())).ToList(), isMainRoad, - isDrivable)); + isDrivable, + name)); } public virtual async Task FindPlaceAsync(string name, GeoPoint near, CancellationToken cancellationToken) diff --git a/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs b/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs index a7aca15..f38de5d 100644 --- a/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs +++ b/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs @@ -8,7 +8,7 @@ namespace Schaad.OpenData.Traffic.Storage; public class TrafficCacheStorage(IOptions options) { private const string DayFormat = "yyyy-MM-dd"; - private const string GeometryFileName = "geometry-v5.json"; + private const string GeometryFileName = "geometry-v7.json"; private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true }; diff --git a/Schaad.OpenData.Traffic/TrafficRefresher.cs b/Schaad.OpenData.Traffic/TrafficRefresher.cs index 2783a94..922ef7a 100644 --- a/Schaad.OpenData.Traffic/TrafficRefresher.cs +++ b/Schaad.OpenData.Traffic/TrafficRefresher.cs @@ -38,7 +38,8 @@ public class TrafficRefresher( public async Task BuildMissingGeometryAsync(CancellationToken cancellationToken) { var snapshot = store.Current; - var missing = snapshot.Stations.Values.Where(s => !snapshot.Geometry.ContainsKey(s.Code)).ToList(); + var stations = snapshot.Stations.Values.ToList(); + var missing = stations.Where(s => !snapshot.Geometry.ContainsKey(s.Code)).ToList(); if (missing.Count == 0) { return; @@ -49,7 +50,7 @@ public class TrafficRefresher( { try { - built.Add(await geometryService.BuildAsync(station, cancellationToken)); + built.Add(await geometryService.BuildAsync(station, stations, cancellationToken)); } catch (HttpRequestException exception) {