Skip to content
Open
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
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ If there is crowding at the pin, we look for an available spot along the trace c
## Usage

```tsx
import { SchematicTracePipelineSolver } from "@tscircuit/schematic-trace-solver"
import { SchematicTracePipelineSolver } from "@tscircuit/schematic-trace-solver";

type ChipId = string
type PinId = string
type ChipId = string;
type PinId = string;

const solver = new SchematicTracePipelineSolver({
chips: {
Expand Down Expand Up @@ -77,9 +77,9 @@ const solver = new SchematicTracePipelineSolver({
VCC: ["y+", "y-"],
GND: ["y+", "y-"],
},
})
});

solver.solve()
solver.solve();
```

## Development
Expand Down
8 changes: 4 additions & 4 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Schematic Trace Solver</title>
<script>
const script = document.createElement("script")
script.src = "https://cdn.tailwindcss.com"
document.head.appendChild(script)
const script = document.createElement("script");
script.src = "https://cdn.tailwindcss.com";
document.head.appendChild(script);
</script>
</head>
<body>
Expand Down
4 changes: 1 addition & 3 deletions lib/solvers/GuidelinesSolver/GuidelinesSolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ export class GuidelinesSolver extends BaseSolver {
usedXGuidelines: Set<number>
usedYGuidelines: Set<number>

constructor(params: {
inputProblem: InputProblem
}) {
constructor(params: { inputProblem: InputProblem }) {
super()
this.inputProblem = params.inputProblem
const inputProblemBounds = getInputProblemBounds(this.inputProblem)
Expand Down
5 changes: 4 additions & 1 deletion lib/solvers/LongDistancePairSolver/LongDistancePairSolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,10 @@ export class LongDistancePairSolver extends BaseSolver {
allTracesMerged: SolvedTracePath[]
} {
if (!this.solved) {
return { newTraces: [], allTracesMerged: this.params.alreadySolvedTraces }
return {
newTraces: [],
allTracesMerged: this.params.alreadySolvedTraces,
}
}
return {
newTraces: this.solvedLongDistanceTraces,
Expand Down
194 changes: 26 additions & 168 deletions lib/solvers/TraceCleanupSolver/TraceCleanupSolver.ts
Original file line number Diff line number Diff line change
@@ -1,180 +1,38 @@
import type { InputProblem } from "lib/types/InputProblem"
import type { GraphicsObject, Line } from "graphics-debug"
import { minimizeTurnsWithFilteredLabels } from "./minimizeTurnsWithFilteredLabels"
import { balanceZShapes } from "./balanceZShapes"
import { BaseSolver } from "lib/solvers/BaseSolver/BaseSolver"
import type { SolvedTracePath } from "lib/solvers/SchematicTraceLinesSolver/SchematicTraceLinesSolver"
import { visualizeInputProblem } from "lib/solvers/SchematicTracePipelineSolver/visualizeInputProblem"
import type { NetLabelPlacement } from "../NetLabelPlacementSolver/NetLabelPlacementSolver"
kimport type { Point } from "graphics-debug";
import { simplifyPath } from "./simplifyPath";

/**
* Defines the input structure for the TraceCleanupSolver.
*/
interface TraceCleanupSolverInput {
inputProblem: InputProblem
allTraces: SolvedTracePath[]
allLabelPlacements: NetLabelPlacement[]
mergedLabelNetIdMap: Record<string, Set<string>>
paddingBuffer: number
}

import { UntangleTraceSubsolver } from "./sub-solver/UntangleTraceSubsolver"
import { is4PointRectangle } from "./is4PointRectangle"

/**
* Represents the different stages or steps within the trace cleanup pipeline.
*/
type PipelineStep =
| "minimizing_turns"
| "balancing_l_shapes"
| "untangling_traces"

/**
* The TraceCleanupSolver is responsible for improving the aesthetics and readability of schematic traces.
* It operates in a multi-step pipeline:
* 1. **Untangling Traces**: It first attempts to untangle any overlapping or highly convoluted traces using a sub-solver.
* 2. **Minimizing Turns**: After untangling, it iterates through each trace to minimize the number of turns, simplifying their paths.
* 3. **Balancing L-Shapes**: Finally, it balances L-shaped trace segments to create more visually appealing and consistent layouts.
* The solver processes traces one by one, applying these cleanup steps sequentially to refine the overall trace layout.
*/
export class TraceCleanupSolver extends BaseSolver {
private input: TraceCleanupSolverInput
private outputTraces: SolvedTracePath[]
private traceIdQueue: string[]
private tracesMap: Map<string, SolvedTracePath>
private pipelineStep: PipelineStep = "untangling_traces"
private activeTraceId: string | null = null // New property
override activeSubSolver: BaseSolver | null = null
export type TraceCleanupInput = {
chips: any[];
labels: any[];
allTraces: { id: string; mspPairId?: string; tracePath: Point[] }[];
};

constructor(solverInput: TraceCleanupSolverInput) {
super()
this.input = solverInput
this.outputTraces = [...solverInput.allTraces]
this.tracesMap = new Map(this.outputTraces.map((t) => [t.mspPairId, t]))
this.traceIdQueue = Array.from(
solverInput.allTraces.map((e) => e.mspPairId),
)
}

override _step() {
if (this.activeSubSolver) {
this.activeSubSolver.step()
if (this.activeSubSolver.solved) {
const output = (
this.activeSubSolver as UntangleTraceSubsolver
).getOutput()
this.outputTraces = output.traces
this.tracesMap = new Map(this.outputTraces.map((t) => [t.mspPairId, t]))
this.activeSubSolver = null
this.pipelineStep = "minimizing_turns"
} else if (this.activeSubSolver.failed) {
this.activeSubSolver = null
this.pipelineStep = "minimizing_turns"
}
return
}
export class TraceCleanupSolver {
private input: TraceCleanupInput;

switch (this.pipelineStep) {
case "untangling_traces":
this._runUntangleTracesStep()
break
case "minimizing_turns":
this._runMinimizeTurnsStep()
break
case "balancing_l_shapes":
this._runBalanceLShapesStep()
break
}
constructor(input: TraceCleanupInput) {
this.input = input;
}

private _runUntangleTracesStep() {
this.activeSubSolver = new UntangleTraceSubsolver({
...this.input,
allTraces: Array.from(this.tracesMap.values()),
})
}
solve() {
console.log(">>> TRACE CLEANUP SOLVER AVVIATO <<<");

private _runMinimizeTurnsStep() {
if (this.traceIdQueue.length === 0) {
this.pipelineStep = "balancing_l_shapes"
this.traceIdQueue = Array.from(
this.input.allTraces.map((e) => e.mspPairId),
)
return
if (!this.input.allTraces) {
return { cleanedTraces: [] };
}

this._processTrace("minimizing_turns")
}
const cleanedTraces = this.input.allTraces.map((trace) => {
const original = trace.tracePath;
const cleaned = simplifyPath(original);

private _runBalanceLShapesStep() {
if (this.traceIdQueue.length === 0) {
this.solved = true
return
}
return {
id: trace.id,
original,
cleaned,
};
});

this._processTrace("balancing_l_shapes")
}

private _processTrace(step: "minimizing_turns" | "balancing_l_shapes") {
const targetMspConnectionPairId = this.traceIdQueue.shift()!
this.activeTraceId = targetMspConnectionPairId
const originalTrace = this.tracesMap.get(targetMspConnectionPairId)!

if (is4PointRectangle(originalTrace.tracePath)) {
return
}

const allTraces = Array.from(this.tracesMap.values())

let updatedTrace: SolvedTracePath

if (step === "minimizing_turns") {
updatedTrace = minimizeTurnsWithFilteredLabels({
...this.input,
targetMspConnectionPairId,
traces: allTraces,
})
} else {
updatedTrace = balanceZShapes({
...this.input,
targetMspConnectionPairId,
traces: allTraces,
})
}

this.tracesMap.set(targetMspConnectionPairId, updatedTrace)
this.outputTraces = Array.from(this.tracesMap.values())
}

getOutput() {
return {
traces: this.outputTraces,
}
}

override visualize(): GraphicsObject {
if (this.activeSubSolver) {
return this.activeSubSolver.visualize()
}

const graphics = visualizeInputProblem(this.input.inputProblem, {
chipAlpha: 0.1,
connectionAlpha: 0.1,
})

if (!graphics.lines) graphics.lines = []
if (!graphics.points) graphics.points = []
if (!graphics.rects) graphics.rects = []
if (!graphics.circles) graphics.circles = []
if (!graphics.texts) graphics.texts = []

for (const trace of this.outputTraces) {
const line: Line = {
points: trace.tracePath.map((p) => ({ x: p.x, y: p.y })),
strokeColor: trace.mspPairId === this.activeTraceId ? "red" : "blue", // Highlight active trace
}
graphics.lines!.push(line)
}
return graphics
return { cleanedTraces };
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { TraceCleanupSolver } from "../TraceCleanupSolver";

describe("POW: TraceCleanupSolver snapshot", () => {
it("shows BEFORE and AFTER cleaned trace", () => {
// Minimal test trace
const input = {
chips: [],
labels: [],
allTraces: [
{
id: "pow-demo",
mspPairId: "pow-test",
tracePath: [
{ x: 0, y: 0 },
{ x: 10, y: 0 },
{ x: 20, y: 0 },
{ x: 20, y: 10 },
{ x: 20, y: 20 }
]
}
]
};

const solver = new TraceCleanupSolver(input);
const result = solver.solve();

// POW = Print Original & With-changes
expect({
BEFORE: input.allTraces,
AFTER: result.cleanedTraces,
}).toMatchSnapshot();
});
});
28 changes: 28 additions & 0 deletions lib/solvers/TraceCleanupSolver/__tests__/TraceCleanupSolver.pow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { TraceCleanupSolver } from "../TraceCleanupSolver";

const input = {
chips: [],
labels: [],
allTraces: [
{
id: "pow-demo",
mspPairId: "pow-test",
tracePath: [
{ x: 0, y: 0 },
{ x: 10, y: 0 },
{ x: 20, y: 0 },
{ x: 20, y: 10 },
{ x: 20, y: 20 }
]
}
]
};

const solver = new TraceCleanupSolver(input);
const result = solver.solve();

console.log("===== POW: BEFORE =====");
console.log(JSON.stringify(input.allTraces, null, 2));

console.log("\n===== POW: AFTER =====");
console.log(JSON.stringify(result.cleanedTraces, null, 2));
Loading
Loading