OpenDataVisualizer/Schaad.OpenData.Traffic/Geometry/RoadPathBuilder.cs
Claudio Schaad e729ea3403 Add Thurgau traffic visualizer with animated map
ASP.NET Core 10 API and React client that visualize the canton of
Thurgau's hourly traffic counts by vehicle class (data.tg.ch, CC0).

- Background refresh from data.tg.ch every 6 h into a per-day JSON
  cache, so history grows beyond the source's two-week window
- Road geometry per station direction from swisstopo swissTLM3D,
  oriented by geocoding the direction's target town; roundabout arms
  follow the road outward only
- Leaflet map with canvas animation: dots drive along the road in
  both directions, density by hourly count, colour by vehicle class,
  right-hand traffic; play/pause, time slider and day selection
- Station panel with per-class counts and Chart.js charts (hourly,
  weekday/weekend profile, daily totals, class mix)
- swisstopo base map switcher (grey, colour, aerial)
- Dockerfile and docker-compose with a data volume
- xUnit tests for mapping, cache, geometry, geocoding and analysis

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:33:58 +01:00

285 lines
10 KiB
C#

using System.Numerics;
using Schaad.OpenData.Traffic.Models;
namespace Schaad.OpenData.Traffic.Geometry;
public static class RoadPathBuilder
{
private const float JoinToleranceMeters = 2f;
private const double MaxTurnDegrees = 60;
private const double MinimumSideLengthMeters = 60;
private const double MainRoadSnapMeters = 60;
private const double RoadClassChangePenaltyDegrees = 25;
private const double ArmSearchMeters = 80;
private const float ArmDistancePenalty = 2f;
private sealed record RoadLine(List<Vector2> Points, bool IsMainRoad);
private static List<RoadLine> ToLines(IReadOnlyList<RoadSegment> segments, LocalProjection projection)
{
var usable = segments.Where(s => s.Points.Count >= 2).ToList();
var drivable = usable.Where(s => s.IsDrivable).ToList();
return (drivable.Count > 0 ? drivable : usable)
.Select(s => new RoadLine(s.Points.Select(projection.ToLocal).ToList(), s.IsMainRoad))
.ToList();
}
public static IReadOnlyList<GeoPoint>? BuildRoadPath(GeoPoint station, IReadOnlyList<RoadSegment> segments, double halfLengthMeters)
{
var projection = new LocalProjection(station);
var lines = ToLines(segments, projection);
if (lines.Count == 0)
{
return null;
}
var distances = lines.Select(l => DistanceToPolyline(Vector2.Zero, l.Points)).ToList();
var nearestMain = Enumerable.Range(0, lines.Count)
.Where(i => lines[i].IsMainRoad && distances[i] <= MainRoadSnapMeters)
.OrderBy(i => distances[i])
.Select(i => (int?)i)
.FirstOrDefault();
var start = nearestMain ?? Enumerable.Range(0, lines.Count).MinBy(i => distances[i]);
var chain = new List<Vector2>(lines[start].Points);
var used = new HashSet<int> { start };
var preferMain = lines[start].IsMainRoad;
ExtendAtEnd(chain, lines, used, preferMain, halfLengthMeters);
chain.Reverse();
ExtendAtEnd(chain, lines, used, preferMain, halfLengthMeters);
chain.Reverse();
var trimmed = Trim(chain, ArcPositionOf(Vector2.Zero, chain), halfLengthMeters);
return trimmed.Count >= 2 ? trimmed.Select(projection.ToGeo).ToList() : null;
}
public static IReadOnlyList<GeoPoint>? BuildArmPath(GeoPoint station, IReadOnlyList<RoadSegment> segments, GeoPoint target, double lengthMeters)
{
var projection = new LocalProjection(station);
var toward = projection.ToLocal(target);
if (toward.LengthSquared() < 1e-6f)
{
return null;
}
toward = Vector2.Normalize(toward);
var lines = ToLines(segments, projection);
var best = lines
.Select((line, index) => (Index: index, Distance: DistanceToPolyline(Vector2.Zero, line.Points)))
.Where(c => c.Distance <= ArmSearchMeters)
.Select(c =>
{
var arm = FollowArm(lines, c.Index, toward, lengthMeters);
var progress = arm.Count >= 2 && Length(arm) >= MinimumSideLengthMeters ? Vector2.Dot(arm[^1], toward) : float.MinValue;
return (Arm: arm, Score: progress - ArmDistancePenalty * c.Distance);
})
.Where(c => c.Score > float.MinValue / 2)
.OrderByDescending(c => c.Score)
.FirstOrDefault();
return best.Arm?.Select(projection.ToGeo).ToList();
}
private static List<Vector2> FollowArm(List<RoadLine> lines, int start, Vector2 toward, double lengthMeters)
{
var chain = new List<Vector2>(lines[start].Points);
if (Vector2.Dot(chain[^1] - chain[0], toward) < 0)
{
chain.Reverse();
}
ExtendAtEnd(chain, lines, [start], lines[start].IsMainRoad, lengthMeters);
var position = ArcPositionOf(Vector2.Zero, chain);
return Trim(chain, position + lengthMeters / 2, lengthMeters / 2);
}
public static IReadOnlyList<GeoPoint> BuildStraightPath(GeoPoint station, GeoPoint? toward, double halfLengthMeters)
{
var projection = new LocalProjection(station);
var direction = toward is { } target ? projection.ToLocal(target) : Vector2.UnitX;
direction = direction.LengthSquared() < 1e-6 ? Vector2.UnitX : Vector2.Normalize(direction);
var offset = direction * (float)halfLengthMeters;
return [projection.ToGeo(-offset), projection.ToGeo(offset)];
}
public static IReadOnlyList<DirectionGeometry> Orient(GeoPoint station, IReadOnlyList<GeoPoint> path, IReadOnlyList<ResolvedDirection> directions)
{
var projection = new LocalProjection(station);
var pathVector = projection.ToLocal(path[^1]) - projection.ToLocal(path[0]);
var forward = directions
.Select(d => d.TargetLocation is { } location
? (bool?)((Vector2.Dot(pathVector, projection.ToLocal(location)) > 0) == d.Target.IsDestination)
: null)
.ToList();
if (forward.Count == 2)
{
forward = (forward[0], forward[1]) switch
{
(null, null) => [true, false],
({ } first, null) => [first, !first],
(null, { } second) => [!second, second],
({ } first, { } second) when first == second => [first, !first],
_ => forward,
};
}
var reversed = path.Reverse().ToList();
return directions
.Select((d, i) => new DirectionGeometry(d.Direction, (forward[i] ?? i % 2 == 0) ? path : reversed))
.ToList();
}
private static void ExtendAtEnd(List<Vector2> chain, List<RoadLine> lines, HashSet<int> used, bool preferMain, double halfLengthMeters)
{
while (Length(chain) - ArcPositionOf(Vector2.Zero, chain) < halfLengthMeters)
{
var end = chain[^1];
var heading = Heading(chain[^2], end);
var best = -1;
var bestAngle = double.MaxValue;
List<Vector2>? bestLine = null;
for (var i = 0; i < lines.Count; i++)
{
if (used.Contains(i))
{
continue;
}
var line = lines[i].Points;
List<Vector2>? oriented = null;
if (Vector2.Distance(line[0], end) <= JoinToleranceMeters)
{
oriented = line;
}
else if (Vector2.Distance(line[^1], end) <= JoinToleranceMeters)
{
oriented = Enumerable.Reverse(line).ToList();
}
if (oriented is null)
{
continue;
}
var next = oriented.FirstOrDefault(p => Vector2.Distance(p, oriented[0]) > 0.5f, oriented[^1]);
var angle = Math.Acos(Math.Clamp(Vector2.Dot(heading, Heading(oriented[0], next)), -1f, 1f)) * 180 / Math.PI;
var score = angle + (lines[i].IsMainRoad == preferMain ? 0 : RoadClassChangePenaltyDegrees);
if (angle <= MaxTurnDegrees && score < bestAngle)
{
best = i;
bestAngle = score;
bestLine = oriented;
}
}
if (bestLine is null)
{
return;
}
used.Add(best);
chain.AddRange(bestLine.Skip(1));
}
}
private static List<Vector2> Trim(List<Vector2> chain, double center, double halfLengthMeters)
{
var from = center - halfLengthMeters;
var to = center + halfLengthMeters;
var result = new List<Vector2>();
var position = 0d;
for (var i = 0; i < chain.Count - 1; i++)
{
var a = chain[i];
var b = chain[i + 1];
var length = Vector2.Distance(a, b);
var start = position;
var end = position + length;
position = end;
if (end < from || start > to || length <= 0)
{
continue;
}
if (result.Count == 0)
{
result.Add(start >= from ? a : Vector2.Lerp(a, b, (float)((from - start) / length)));
}
if (end <= to)
{
result.Add(b);
}
else
{
result.Add(Vector2.Lerp(a, b, (float)((to - start) / length)));
break;
}
}
return result;
}
private static double ArcPositionOf(Vector2 point, List<Vector2> chain)
{
var bestDistance = double.MaxValue;
var bestPosition = 0d;
var position = 0d;
for (var i = 0; i < chain.Count - 1; i++)
{
var a = chain[i];
var b = chain[i + 1];
var length = Vector2.Distance(a, b);
var t = length > 0 ? Math.Clamp(Vector2.Dot(point - a, b - a) / (length * length), 0, 1) : 0;
var distance = Vector2.Distance(point, Vector2.Lerp(a, b, t));
if (distance < bestDistance)
{
bestDistance = distance;
bestPosition = position + t * length;
}
position += length;
}
return bestPosition;
}
private static double DistanceToPolyline(Vector2 point, List<Vector2> line)
{
var best = double.MaxValue;
for (var i = 0; i < line.Count - 1; i++)
{
var a = line[i];
var b = line[i + 1];
var lengthSquared = Vector2.DistanceSquared(a, b);
var t = lengthSquared > 0 ? Math.Clamp(Vector2.Dot(point - a, b - a) / lengthSquared, 0, 1) : 0;
best = Math.Min(best, Vector2.Distance(point, Vector2.Lerp(a, b, t)));
}
return best;
}
private static double Length(List<Vector2> chain)
{
var length = 0d;
for (var i = 0; i < chain.Count - 1; i++)
{
length += Vector2.Distance(chain[i], chain[i + 1]);
}
return length;
}
private static Vector2 Heading(Vector2 from, Vector2 to)
{
var delta = to - from;
return delta.LengthSquared() < 1e-6f ? Vector2.UnitX : Vector2.Normalize(delta);
}
}