Files
road-compiler/test/junction-build-plan-counterexamples.js
T

348 lines
15 KiB
JavaScript

'use strict';
// Source-independent counterexamples for the JunctionBuildPlan contract.
const assert = require('assert/strict');
const { resolveJunctionBuildPlan, stationAtDistanceFrom } = require('../src/compile/junction-build-plan');
const { buildJunctionBoundaryGraph, buildCoreClosure } = require('../src/compile/junction-boundary-graph');
const { classifyJunctionShape } = require('../src/compile/complex-junction');
const metersPerDegree = 111320;
const point = (east, north) => [east / metersPerDegree, north / metersPerDegree];
function heading(line) {
const [from, to] = line;
return (Math.atan2(to[0] - from[0], to[1] - from[1]) * 180) / Math.PI;
}
function distance(first, second) {
return Math.hypot((first[0] - second[0]) * metersPerDegree, (first[1] - second[1]) * metersPerDegree);
}
function length(line) {
return line.slice(1).reduce((total, item, index) => total + distance(line[index], item), 0);
}
function pointAtStation(line, station) {
let remaining = station;
for (let index = 1; index < line.length; index += 1) {
const segmentLength = distance(line[index - 1], line[index]);
if (remaining <= segmentLength) {
const ratio = remaining / segmentLength;
return [
line[index - 1][0] + (line[index][0] - line[index - 1][0]) * ratio,
line[index - 1][1] + (line[index][1] - line[index - 1][1]) * ratio,
];
}
remaining -= segmentLength;
}
return line.at(-1);
}
function fixture(name, entries) {
const nodeId = `${name}:node`;
const approaches = entries.map((entry, index) => ({
segmentId: `${name}:segment:${index + 1}`,
roadIds: [`${name}:road:${index + 1}`],
widthMeters: entry.widthMeters,
line: entry.line,
}));
return {
model: {
roads: entries.map((entry, index) => ({
id: `${name}:road:${index + 1}`,
segmentId: `${name}:segment:${index + 1}`,
sourceNodeIds: [nodeId, `${name}:outer:${index + 1}`],
laneCount: 1,
})),
},
cluster: { id: name, nodeIds: [nodeId, `${name}:internal`] },
helpers: {
junctionPlans: new Map([
[nodeId, { node: point(0, 0), approaches }],
[`${name}:internal`, { node: point(1, 1), approaches: [] }],
]),
headingAtEndpoint: heading,
lineLengthMeters: length,
distanceMeters: distance,
},
};
}
function topology(name, entries) {
const input = fixture(name, entries);
return { ...input, topology: resolveJunctionBuildPlan(input.model, input.cluster, input.helpers) };
}
// A divided approach keeps independently addressable entry sections even when
// both carriageways share an arm.
const divided = topology('divided', [
{ widthMeters: 4, line: [point(-5, 0), point(-5, 50)] },
{ widthMeters: 5, line: [point(5, 0), point(5, 50)] },
{ widthMeters: 7, line: [point(0, 0), point(50, 0)] },
{ widthMeters: 7, line: [point(0, 0), point(0, -50)] },
]);
assert.equal(divided.topology.carriageways.length, 4);
assert.equal(divided.topology.arms.length, 3);
assert.equal(divided.topology.arms.find((arm) => arm.members.length === 2)?.members.length, 2);
assert.equal(new Set(divided.topology.carriageways.map((item) => item.entrySection.carriagewayKey)).size, 4);
assert.ok(
divided.topology.carriageways.every(
(item) => item.entrySection.boundaryEndpoints.near.left[0] !== item.entrySection.boundaryEndpoints.near.right[0],
),
);
const dividedBoundaryGraph = buildJunctionBoundaryGraph(
divided.topology,
point(0, 0),
{ outerRadiusFor: () => 25, innerRadiusFor: () => 10 },
divided.helpers,
);
assert.equal(dividedBoundaryGraph.status, 'entry-sections-only');
assert.equal(dividedBoundaryGraph.sections.length, divided.topology.carriageways.length);
assert.equal(new Set(dividedBoundaryGraph.sections.map((section) => section.carriagewayKey)).size, 4);
assert.equal(dividedBoundaryGraph.edges.length, dividedBoundaryGraph.sections.length * 4);
assert.equal(
buildCoreClosure(divided.topology, dividedBoundaryGraph, point(0, 0)).reason,
'parallel-carriageway-closure-unresolved',
);
// A T junction has explicit, source-stable entry sections. Closure edges are a
// later BoundaryGraph concern and must not be fabricated by topology parsing.
const tee = topology('tee', [
{ widthMeters: 8, line: [point(0, 0), point(0, 45)] },
{ widthMeters: 4, line: [point(0, 0), point(45, 0)] },
{ widthMeters: 4, line: [point(0, 0), point(-45, 0)] },
]);
assert.equal(tee.topology.arms.length, 3);
assert.equal(classifyJunctionShape(tee.topology.arms, point(0, 0), tee.helpers).kind, 't-junction');
assert.ok(tee.topology.carriageways.every((item) => item.entrySection.feasibility === 'supported'));
const teeBoundaryGraph = buildJunctionBoundaryGraph(
tee.topology,
point(0, 0),
{ outerRadiusFor: () => 30, innerRadiusFor: () => 10 },
tee.helpers,
);
const teeCore = buildCoreClosure(tee.topology, teeBoundaryGraph, point(0, 0));
assert.equal(teeCore.status, 'supported');
assert.equal(teeCore.sharedEdgeRefs.length, teeBoundaryGraph.sections.length);
assert.ok(teeCore.ring.every((coordinate) => coordinate.every(Number.isFinite)));
const exclusionRing = [point(-1, -1), point(1, -1), point(1, 1), point(-1, 1), point(-1, -1)];
const teeWithIsland = buildJunctionBoundaryGraph(
tee.topology,
point(0, 0),
{ outerRadiusFor: () => 30, innerRadiusFor: () => 10 },
tee.helpers,
[{ id: 'island:known', ring: exclusionRing }],
);
assert.equal(buildCoreClosure(tee.topology, teeWithIsland, point(0, 0)).reason, 'known-exclusion-region');
const enclosingExclusion = [point(-30, -30), point(30, -30), point(30, 30), point(-30, 30), point(-30, -30)];
const teeInsideExclusion = buildJunctionBoundaryGraph(
tee.topology,
point(0, 0),
{ outerRadiusFor: () => 30, innerRadiusFor: () => 10 },
tee.helpers,
[{ id: 'island:enclosing', ring: enclosingExclusion }],
);
assert.equal(buildCoreClosure(tee.topology, teeInsideExclusion, point(0, 0)).reason, 'known-exclusion-region');
// Offset and unequal-width approaches preserve individual source sections and
// local section tangents rather than a single arm envelope.
const offsetUnequal = topology('offset-unequal', [
{ widthMeters: 12, line: [point(-8, 0), point(-8, 48)] },
{ widthMeters: 4, line: [point(0, 18), point(48, 18)] },
{ widthMeters: 6, line: [point(9, 0), point(9, -28)] },
{ widthMeters: 9, line: [point(0, -12), point(-48, -12)] },
]);
assert.equal(offsetUnequal.topology.arms.length, 4);
assert.equal(
classifyJunctionShape(offsetUnequal.topology.arms, point(0, 0), offsetUnequal.helpers).kind,
'offset-cross',
);
assert.deepEqual(
offsetUnequal.topology.carriageways.map((item) => item.entrySection.farStationMeters),
offsetUnequal.topology.carriageways.map((item) => item.length),
);
// A short curved approach reports bounded feasibility while retaining distinct
// local tangents at each end of its source polyline.
const curvedShort = topology('curved-short', [
{ widthMeters: 6, line: [point(0, 0), point(0, 3), point(7, 7)] },
{ widthMeters: 6, line: [point(0, 0), point(35, 0)] },
{ widthMeters: 6, line: [point(0, 0), point(0, -35)] },
]);
assert.equal(curvedShort.topology.carriageways[0].heading, 0, 'current heading samples only the first segment');
assert.ok(curvedShort.topology.carriageways[0].length < 12, 'fixture is shorter than the minimum complex core radius');
assert.equal(curvedShort.topology.carriageways[0].entrySection.feasibility, 'short-approach');
assert.equal(curvedShort.topology.carriageways[0].entrySection.reason, 'entry-section-too-short');
assert.notEqual(
curvedShort.topology.carriageways[0].entrySection.nearTangent,
curvedShort.topology.carriageways[0].entrySection.farTangent,
);
const curvedBoundaryGraph = buildJunctionBoundaryGraph(
curvedShort.topology,
point(0, 0),
{ outerRadiusFor: () => 8, innerRadiusFor: () => 2 },
curvedShort.helpers,
);
const curvedSection = curvedBoundaryGraph.sections.find(
(section) => section.carriagewayKey === curvedShort.topology.carriageways[0].key,
);
assert.notEqual(curvedSection.outer.tangent, curvedSection.inner.tangent);
const curvedBoundaryLine = [point(0, 0), point(0, 5), point(10, 10)];
const curvedBoundaryStation = stationAtDistanceFrom(curvedBoundaryLine, point(0, 0), 9, {
distanceMeters: distance,
});
assert.ok(Math.abs(distance(pointAtStation(curvedBoundaryLine, curvedBoundaryStation), point(0, 0)) - 9) < 0.01);
// Six-arm clusters remain within the supported matrix and keep semantic keys
// stable when the source geometry is rotated. Geometry may change with the
// transform, but identity and arm count must not depend on input orientation.
const sixArmEntries = [0, 60, 120, 180, 240, 300].map((angle) => ({
widthMeters: 6,
line: [point(0, 0), point(Math.sin((angle * Math.PI) / 180) * 45, Math.cos((angle * Math.PI) / 180) * 45)],
}));
const sixArm = topology('six-arm', sixArmEntries);
assert.equal(sixArm.topology.arms.length, 6);
assert.equal(classifyJunctionShape(sixArm.topology.arms, point(0, 0), sixArm.helpers).kind, 'multi-arm');
const sixArmGraph = buildJunctionBoundaryGraph(
sixArm.topology,
point(0, 0),
{ outerRadiusFor: () => 30, innerRadiusFor: () => 10 },
sixArm.helpers,
);
assert.equal(buildCoreClosure(sixArm.topology, sixArmGraph, point(0, 0)).status, 'supported');
const rotate = (coordinate, degrees) => {
const radians = (degrees * Math.PI) / 180;
return point(
coordinate[0] * metersPerDegree * Math.cos(radians) - coordinate[1] * metersPerDegree * Math.sin(radians),
coordinate[0] * metersPerDegree * Math.sin(radians) + coordinate[1] * metersPerDegree * Math.cos(radians),
);
};
const rotatedSixArmEntries = sixArmEntries.map((entry) => ({
...entry,
line: entry.line.map((coordinate) => rotate(coordinate, 37)),
}));
const rotatedSixArm = fixture('six-arm', rotatedSixArmEntries);
const rotatedTopology = resolveJunctionBuildPlan(rotatedSixArm.model, rotatedSixArm.cluster, rotatedSixArm.helpers);
assert.deepEqual(rotatedTopology.arms.map((arm) => arm.key).sort(), sixArm.topology.arms.map((arm) => arm.key).sort());
assert.equal(rotatedTopology.arms.length, sixArm.topology.arms.length);
console.log('junction build-plan counterexample tests passed');
function ringArea(ring) {
return Math.abs(
ring
.slice(1)
.reduce((area, coordinate, index) => area + ring[index][0] * coordinate[1] - coordinate[0] * ring[index][1], 0) /
2,
);
}
function ringHasSelfIntersection(ring) {
const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
const intersects = (a, b, c, d) => {
const abC = cross(a, b, c);
const abD = cross(a, b, d);
const cdA = cross(c, d, a);
const cdB = cross(c, d, b);
return ((abC > 0 && abD < 0) || (abC < 0 && abD > 0)) && ((cdA > 0 && cdB < 0) || (cdA < 0 && cdB > 0));
};
for (let first = 0; first < ring.length - 1; first += 1) {
for (let second = first + 2; second < ring.length - 1; second += 1) {
if (first === 0 && second === ring.length - 2) continue;
if (intersects(ring[first], ring[first + 1], ring[second], ring[second + 1])) return true;
}
}
return false;
}
function assertCoreGeometry(topologyValue, graphValue, centerValue) {
const closure = buildCoreClosure(topologyValue, graphValue, centerValue);
assert.equal(closure.status, 'supported');
assert.deepEqual(closure.ring[0], closure.ring.at(-1), 'core ring must be explicitly closed');
assert.ok(closure.ring.slice(0, -1).every((coordinate) => coordinate.every(Number.isFinite)));
assert.ok(ringArea(closure.ring) > 0, 'core ring must have positive area');
assert.equal(ringHasSelfIntersection(closure.ring), false, 'core ring must not self-intersect');
for (const section of graphValue.sections) {
const samePoint = (first, second) => first?.[0] === second?.[0] && first?.[1] === second?.[1];
const hasSeam = closure.ring.slice(0, -1).some((coordinate, index) => {
const next = closure.ring[index + 1];
return (
(samePoint(coordinate, section.inner.left) && samePoint(next, section.inner.right)) ||
(samePoint(coordinate, section.inner.right) && samePoint(next, section.inner.left))
);
});
assert.equal(hasSeam, true, `inner seam must remain a contiguous ring edge for ${section.carriagewayKey}`);
}
}
assertCoreGeometry(tee.topology, teeBoundaryGraph, point(0, 0));
assertCoreGeometry(sixArm.topology, sixArmGraph, point(0, 0));
const fiveArm = topology(
'five-arm',
[0, 72, 144, 216, 288].map((angle) => ({
widthMeters: 5,
line: [point(0, 0), point(Math.sin((angle * Math.PI) / 180) * 45, Math.cos((angle * Math.PI) / 180) * 45)],
})),
);
const fiveArmGraph = buildJunctionBoundaryGraph(
fiveArm.topology,
point(0, 0),
{ outerRadiusFor: () => 30, innerRadiusFor: () => 10 },
fiveArm.helpers,
);
assertCoreGeometry(fiveArm.topology, fiveArmGraph, point(0, 0));
// Reordering source approaches must not change semantic identity. The model
// keeps the same source IDs; only the resolver input order is changed.
const reorderedApproaches = [...sixArm.helpers.junctionPlans.values()][0].approaches.slice().reverse();
const reorderedHelpers = {
...sixArm.helpers,
junctionPlans: new Map([
['six-arm:node', { node: point(0, 0), approaches: reorderedApproaches }],
['six-arm:internal', { node: point(1, 1), approaches: [] }],
]),
};
const reorderedTopology = resolveJunctionBuildPlan(sixArm.model, sixArm.cluster, reorderedHelpers);
assert.deepEqual(
reorderedTopology.carriageways.map((item) => item.key).sort(),
sixArm.topology.carriageways.map((item) => item.key).sort(),
);
assert.deepEqual(
reorderedTopology.arms.map((arm) => arm.key).sort(),
sixArm.topology.arms.map((arm) => arm.key).sort(),
);
// A collapsed inner seam is a geometric failure even if the remaining ring
// still encloses a positive area. The closure must reject zero-length edges.
const collapsedGraph = JSON.parse(JSON.stringify(teeBoundaryGraph));
const collapsedSection = collapsedGraph.sections[0];
collapsedSection.inner.right = collapsedSection.inner.left;
assert.equal(buildCoreClosure(tee.topology, collapsedGraph, point(0, 0)).reason, 'core-closure-invalid');
// Width corrections are represented by one shared trapezoid: the outer seam
// remains source width, the inner seam carries the edited width, and the
// transition distance is explicit for downstream validators and editors.
const tapered = topology('tapered', [
{ widthMeters: 10, line: [point(0, 0), point(0, 50)] },
{ widthMeters: 4, line: [point(0, 0), point(50, 0)] },
{ widthMeters: 4, line: [point(0, 0), point(-50, 0)] },
]);
tapered.topology.carriageways[0].approach.sourceWidthMeters = 10;
tapered.topology.carriageways[0].approach.widthMeters = 6;
const taperedGraph = buildJunctionBoundaryGraph(
tapered.topology,
point(0, 0),
{ outerRadiusFor: () => 30, innerRadiusFor: () => 10 },
tapered.helpers,
);
const taperedSection = taperedGraph.sections.find(
(section) => section.carriagewayKey === tapered.topology.carriageways[0].key,
);
assert.equal(taperedSection.outerWidthMeters, 10);
assert.equal(taperedSection.innerWidthMeters, 6);
assert.ok(taperedSection.transitionMeters > 0);
assert.equal(taperedSection.transitionStatus, 'supported');