Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 56 additions & 2 deletions lib/utils/convertHdRouteToSimplifiedRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,60 @@ import { mapZToLayerName } from "./mapZToLayerName"

type Point = { x: number; y: number; z: number }

const POINT_EPSILON = 1e-3
const MICRO_DETOUR_MAX_CHORD = 0.06
const MICRO_DETOUR_MIN_TINY_EDGE = 0.01
const MICRO_DETOUR_MIN_LARGE_EDGE = 0.03
const MICRO_DETOUR_MAX_PERPENDICULAR = 0.01

const distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y)

const sanitizeLayerPoints = (points: Point[]) => {
if (points.length < 2) return points

const cleaned = [...points]
let changed = true

while (changed) {
changed = false

for (let i = 1; i < cleaned.length; i++) {
if (distance(cleaned[i - 1], cleaned[i]) < POINT_EPSILON) {
cleaned.splice(i, 1)
changed = true
break
}
}
if (changed) continue

for (let i = 1; i < cleaned.length - 1; i++) {
const a = cleaned[i - 1]
const b = cleaned[i]
const c = cleaned[i + 1]

const chord = distance(a, c)
if (chord >= MICRO_DETOUR_MAX_CHORD) continue

const distAB = distance(a, b)
const distBC = distance(b, c)
if (Math.min(distAB, distBC) >= MICRO_DETOUR_MIN_TINY_EDGE) continue
if (Math.max(distAB, distBC) <= MICRO_DETOUR_MIN_LARGE_EDGE) continue
Comment on lines +43 to +44
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic gap in micro-detour detection. When distAB = 0.005 (tiny) and distBC = 0.025 (medium), the conditions:

  • Line 43: Math.min(0.005, 0.025) = 0.005 < 0.01 ✓ (passes)
  • Line 44: Math.max(0.005, 0.025) = 0.025 <= 0.03 ✓ (skips removal)

This creates a gap where triangles with one very small edge (< 0.01) and one medium edge (between 0.01 and 0.03) are NOT removed, potentially leaving micro-detours in the output.

// Consider adjusting line 44 to:
if (Math.max(distAB, distBC) < MICRO_DETOUR_MIN_LARGE_EDGE) continue
// Or removing this check entirely if all micro-detours should be caught

This may cause the regression test to pass while still allowing some micro-triangular detours through, as the test only checks chord < 0.08 without the edge size constraints.

Spotted by Graphite

Fix in Graphite


Is this helpful? React 👍 or 👎 to let us know.


const doubledArea = Math.abs(
(b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x),
)
const perpendicularDistance = doubledArea / Math.max(chord, 1e-9)
if (perpendicularDistance >= MICRO_DETOUR_MAX_PERPENDICULAR) continue

cleaned.splice(i, 1)
changed = true
break
}
}

return cleaned
}

/**
* Extended HD route type that may contain jumpers (from HighDensitySolver)
*/
Expand All @@ -30,7 +84,7 @@ export const convertHdRouteToSimplifiedRoute = (
if (point.z !== currentZ) {
// Add all wire segments for the current layer
const layerName = mapZToLayerName(currentZ, layerCount)
for (const layerPoint of currentLayerPoints) {
for (const layerPoint of sanitizeLayerPoints(currentLayerPoints)) {
result.push({
route_type: "wire",
x: layerPoint.x,
Expand Down Expand Up @@ -72,7 +126,7 @@ export const convertHdRouteToSimplifiedRoute = (

// Add the final layer's wire segments
const layerName = mapZToLayerName(currentZ, layerCount)
for (const layerPoint of currentLayerPoints) {
for (const layerPoint of sanitizeLayerPoints(currentLayerPoints)) {
result.push({
route_type: "wire",
x: layerPoint.x,
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"vercel-build": "cosmos-export",
"repomix:lib": "repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib",
"bug-report": "bun run scripts/download-bug-report.ts",
"bug-report-with-test": "bun run scripts/create-bug-report-test.ts"
"bug-report-with-test": "bun run scripts/create-bug-report-test.ts",
"debug:dataset01:circuit011:solver3": "bun scripts/debug-dataset01-circuit011-solver3.ts"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
Expand Down
122 changes: 122 additions & 0 deletions scripts/debug-dataset01-circuit011-solver3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import * as dataset01 from "@tscircuit/autorouting-dataset-01"
import { AutoroutingPipelineSolver3_HgPortPointPathing } from "../lib/autorouter-pipelines/AutoroutingPipeline2_PortPointPathing/AutoroutingPipelineSolver3_HgPortPointPathing"

type Point2D = { x: number; y: number }

type RoutePoint = Point2D & { z?: number; layer?: string; route_type?: string }

const EPS = 1e-6

const distance = (a: Point2D, b: Point2D) => Math.hypot(a.x - b.x, a.y - b.y)

const triangleArea2 = (a: Point2D, b: Point2D, c: Point2D) =>
Math.abs((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x))

const describePoint = (p: RoutePoint) =>
`(${p.x.toFixed(6)}, ${p.y.toFixed(6)}${typeof p.z === "number" ? `, z=${p.z}` : ""}${p.layer ? `, layer=${p.layer}` : ""})`

const srj = dataset01.circuit011
const solver = new AutoroutingPipelineSolver3_HgPortPointPathing(srj)
solver.solve()

console.log("=== dataset01 / circuit011 / Solver3 debug ===")
console.log("trace count:", solver.getOutputSimpleRouteJson().traces.length)

const node25 = solver.capacityNodes?.find((n) => n.capacityMeshNodeId === "cmn_25")
if (!node25) {
console.log("cmn_25 not found in capacity nodes")
process.exit(0)
}

const node25Bounds = {
minX: node25.center.x - node25.width / 2,
maxX: node25.center.x + node25.width / 2,
minY: node25.center.y - node25.height / 2,
maxY: node25.center.y + node25.height / 2,
}

console.log("cmn_25 bounds:", node25Bounds)

const solvedRoutes = solver.portPointPathingSolver?.solvedRoutes ?? []
const routesThrough25 = solvedRoutes.filter((route) =>
route.path.some((step) => step.nextRegion?.regionId === "cmn_25"),
)

console.log("connections whose hypergraph path traverses cmn_25:")
for (const route of routesThrough25) {
const name = route.connection.simpleRouteConnection.name
const regionPath = route.path
.map((step) => step.nextRegion?.regionId)
.filter(Boolean)
.join(" -> ")
console.log(`- ${name}: ${regionPath}`)
}

const traces = solver.getOutputSimpleRouteJson().traces

const tinyTriangleCandidates: Array<{
traceId: string
index: number
points: [RoutePoint, RoutePoint, RoutePoint]
chordLength: number
area2: number
}> = []

for (const trace of traces) {
const wirePoints = trace.route.filter((p) => p.route_type === "wire") as RoutePoint[]

for (let i = 0; i < wirePoints.length - 2; i++) {
const a = wirePoints[i]
const b = wirePoints[i + 1]
const c = wirePoints[i + 2]

const chordLength = distance(a, c)
const area2 = triangleArea2(a, b, c)

const hasSmallDetour = chordLength < 0.08 && area2 > EPS
if (hasSmallDetour) {
tinyTriangleCandidates.push({
traceId: trace.pcb_trace_id,
index: i,
points: [a, b, c],
chordLength,
area2,
})
}
}
}

console.log("tiny triangle candidates in final simplified traces:", tinyTriangleCandidates.length)
for (const candidate of tinyTriangleCandidates) {
const [a, b, c] = candidate.points
console.log(
`- ${candidate.traceId} at i=${candidate.index}, chord=${candidate.chordLength.toFixed(6)}, area2=${candidate.area2.toExponential(2)}`,
)
console.log(` a=${describePoint(a)}`)
console.log(` b=${describePoint(b)}`)
console.log(` c=${describePoint(c)}`)
}

// Determine at which stage the most obvious kink appears.
const target = { x: 0.75, y: -4.205 }
const stageRoutes: Array<[string, Array<{ connectionName: string; route: RoutePoint[] }>]> = [
["highDensityRouteSolver", solver.highDensityRouteSolver?.routes ?? []],
["highDensityStitchSolver", solver.highDensityStitchSolver?.mergedHdRoutes ?? []],
["traceSimplificationSolver", solver.traceSimplificationSolver?.simplifiedHdRoutes ?? []],
["traceWidthSolver", solver.traceWidthSolver?.getHdRoutesWithWidths() ?? []],
]

console.log("stage presence of kink point (0.75, -4.205):")
for (const [stageName, routes] of stageRoutes) {
const hits = routes.filter((route) =>
route.route.some(
(point) => Math.abs(point.x - target.x) < EPS && Math.abs(point.y - target.y) < EPS,
),
)
console.log(`- ${stageName}: ${hits.length} route(s)`)
for (const hit of hits) {
console.log(` -> ${hit.connectionName}`)
}
}

console.log("Conclusion: the detour is already present in raw intra-node output from highDensityRouteSolver, not introduced by later stitching/simplification.")
41 changes: 41 additions & 0 deletions tests/bugs/dataset01-circuit011-solver3-no-micro-triangle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { expect, test } from "bun:test"
import * as dataset01 from "@tscircuit/autorouting-dataset-01"
import { AutoroutingPipelineSolver3_HgPortPointPathing } from "../../lib/autorouter-pipelines/AutoroutingPipeline2_PortPointPathing/AutoroutingPipelineSolver3_HgPortPointPathing"

const EPS = 1e-6

const distance = (a: { x: number; y: number }, b: { x: number; y: number }) =>
Math.hypot(a.x - b.x, a.y - b.y)

const triangleArea2 = (
a: { x: number; y: number },
b: { x: number; y: number },
c: { x: number; y: number },
) => Math.abs((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x))

test("dataset01 circuit011 solver3 output should not contain tiny wire triangle detours", () => {
const solver = new AutoroutingPipelineSolver3_HgPortPointPathing(dataset01.circuit011)
solver.solve()

const traces = solver.getOutputSimpleRouteJson().traces
const tinyTriangles: Array<{ traceId: string; index: number }> = []

for (const trace of traces) {
const wirePoints = trace.route.filter((p) => p.route_type === "wire")
for (let i = 0; i < wirePoints.length - 2; i++) {
const a = wirePoints[i]
const b = wirePoints[i + 1]
const c = wirePoints[i + 2]

if (a.layer !== b.layer || b.layer !== c.layer) continue

const chord = distance(a, c)
const area2 = triangleArea2(a, b, c)
if (chord < 0.08 && area2 > EPS) {
tinyTriangles.push({ traceId: trace.pcb_trace_id, index: i })
}
}
}

expect(tinyTriangles).toEqual([])
})
Loading