Skip to content

About

A recursively self-improving AI for PCB design: KiCad schematic in, placed & routed board out — getting measurably better on every iteration. Electron app + CLI.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

9 Commits

Folders and files

Repository files navigation

fieldratchet

A recursively self-improving AI for PCB design. Feed it a KiCad schematic (.kicad_sch); it parses, classifies, places, routes, and scores a real KiCad board (.kicad_pcb) — and gets measurably better on every iteration. It ships as both an Electron desktop app (with clickable example boards) and a CLI (batch mode), and it runs fully offline: no kicad-cli, no network, no API keys.

The core optimizer is a coupled-oscillator (Kuramoto) substrate. The netlist is compiled into a network of phase oscillators — components are nodes; shared nets become attractive (synchronizing) couplings (synchronized phase ⇒ nearby placement); noisy↔sensitive net pairs become anti-phase (repelling) couplings (separation). A conditioning block (board intent + thermal hotspots + feedback) modulates those couplings. Many random initial-phase seeds are raced; each synchronized phase field is decoded to coordinates via coord = boardSize · sigmoid(a·sinθ + b·cosθ), then a light de-overlap legalization runs. This substrate is what the RSI loop recursively improves. (The original simulated-annealing optimizer remains the documented baseline, selectable with --optimizer anneal.)

The substrate idea is borrowed from Un‑0, which generates images with a population of coupled oscillators steered by a class-conditioning block (blog, code). fieldratchet reuses the mechanism — coupled oscillators + a conditioning drive — as an optimizer substrate for placement, not for image generation: the oscillators encode component coordinates, and the "image" is a routed, scored PCB layout.

The whole thing is a ratchet. Each iteration the loop explores with fresh phase seeds, then mutates the substrate and only promotes the mutation if the canonical score improves and the independent EMI field check does not regress; it also synthesizes symbolic layout rules from hotspots under the same score gate. Because promotion is gated on the objective, the best score is monotonically non-increasing across iterations — the design can only get better or stay flat, never regress. And it is not vibes: the objective is a concrete geometric + field-risk score — ratsnest length, courtyard/DRC violations, buck switch-loop area, noisy↔sensitive coupling, antenna keepout, and thermal density. Lower is better, and that single number is the thing the loop drives down.


Gallery

Generated by the engine (see docs/gallery/; regenerate with npm run demo).

The coupled-oscillator optimizer Independent EMI field validation
oscillator emi
Coupling graph (cyan = attract/sync, orange = anti-phase repel), θx/θy phase wheels, and the global sync order parameter R(t). Progressive damped-wave field, refined 4→2→1 mm, with the hottest victim net flagged.
Placed & routed board Self-improvement curve
board curve
Real .kicad_pcb — F.Cu (red) / B.Cu (blue) traces, vias, courtyards, mounting holes. The substrate evolves v1→v3; the bright line (best score) is monotonic.

How it works

The pipeline runs in this order, all in TypeScript, all offline:

  1. Parse .kicad_sch (core/schematic.ts) — an S-expression reader for the raw symbol/wire/label tree.
  2. Offline netlister (core/schematic.ts) — recovers connectivity with union-find over wire endpoints, coincident symbol-pin positions, and label names (matching KiCad single-sheet behavior). Power symbols contribute a global label equal to their value. No kicad-cli required.
  3. Role / topology classifier (core/classify.ts) — assigns each component a role (mcu, regulator, inductor, imu, adc, motor_driver, rf, antenna, decap, input/output cap, usb, crystal, …), classifies each net (ground, power, high_current, noisy, usb, clock/sensitive, …), and groups parts into functional clusters (buck_converter, usb, rf, sensor, motor).
  4. Procedural footprint geometry (core/footprints.ts) — synthesizes real pad geometry from footprint ids (no KiCad libraries assumed present), with pad numbers that match schematic pins so nets bind correctly in the output board.
  5. Coupled-oscillator placement (core/osc.ts, default) — compiles the design into a signed-coupling Kuramoto graph (net adjacency ⇒ attraction, cluster cohesion ⇒ extra attraction, noisy↔sensitive ⇒ anti-phase repulsion, decap→IC ⇒ attraction), integrates the phases (optionally inertial / second-order) over a batch of random initial-phase seeds, decodes each synchronized phase field to coordinates, snaps edge-anchored parts (USB/connector→left, antenna/RF→right), and runs a light de-overlap legalization. The annealer (core/place.ts) is the selectable baseline (--optimizer anneal) and is also reused as the short legalization polish.
  6. Grid A* critical-net router (core/route.ts) — routes the top-priority non-ground nets over a coarse two-layer (F.Cu/B.Cu) occupancy grid with via costs; everything else is intentionally left as ratsnest for the scorer to penalize.
  7. Field-proxy scoring + hotspots (core/score.ts) — computes the canonical objective and emits ranked hotspots (e.g. "buck hot loop area 130mm²", "SW within 2.4mm of sensitive IMU_SCL") with suggested actions.
  8. Independent EMI validation (core/emi.ts, optional via --emi) — a progressive 2.5D damped-wave voxel solver estimates near-field coupling risk independently of the optimizer's objective (see EMI section).
  9. Rule + substrate synthesis (core/rules.ts, core/osc.ts) — turns hotspots (and any human feedback text) into candidate layout rules, and mutates the oscillator substrate itself.
  10. Promotion-gated ratchet (core/synth.ts) — re-optimizes with each candidate (rule or mutated substrate) and keeps it only if the canonical best improves and, when --emi is on, the field-risk check does not regress.

Why scores stay comparable (and why transfer is valid)

A ruleset carries weight deltas (and, for the oscillator path, the OscSubstrate) that bias the search. But success is always measured against a fixed canonical yardstick (DEFAULT_WEIGHTS), not the ruleset's own weights — and this holds for both optimizers:

// core/synth.ts — synthOnce()
// oscillator: race a batch of phase seeds, route + score each one canonically
const { layouts } = oscillatorPlace(design, ruleset, sub, { batch, seed }); // GUIDED by the substrate
const score = scoreLayout(design, refined, DEFAULT_WEIGHTS);                  // JUDGED canonically
// anneal (baseline): same canonical judgement
const placed = anneal(design, ruleset, rng, seed, …);
const score  = scoreLayout(design, placed, DEFAULT_WEIGHTS);

Because every layout — under every ruleset/substrate, on every board, under either optimizer — is graded on the same objective, scores are directly comparable across iterations, across optimizers, and across boards. That is exactly what makes the ratchet sound, what lets the oscillator and the annealer be benchmarked head-to-head (bench), and what makes a rule (or evolved substrate) learned on one board transferable to another.

The score (what "better" means)

The objective is a weighted sum of geometric and field-risk terms (lower = better):

Term What it penalizes
ratsnest Total MST wire length of unrouted nets
crossings Ratsnest edges of different nets crossing
courtyard Component courtyard overlaps
offboard Geometry pushed outside the board outline
decap Decoupling caps far from the IC they bypass
switchLoop Buck input-cap→regulator→inductor hot-loop area
noisySensitive Proximity of noisy/high-current nets to sensitive nets
usbPair USB diff-pair length and skew
antenna Objects inside antenna keepout / antenna off the board edge
highCurrent Length × current of high-current paths
thermal Heat-source (regulator/driver/MOSFET) density
returnPath Sensitive nets routed across noisy clusters
drc Proxy DRC errors (overlap + off-board)

The report also exposes normalized field scores (coupling, returnPath, switching, antenna, thermal) in [0,1].


EMI: independent field validation

The geometric score above is what the optimizer drives. To check it against something the optimizer can't game, fieldratchet ships a separate field validator (core/emi.ts) — and the two are deliberately not conflated:

Oscillator dynamics PROPOSE layouts; the voxel ODE pass VALIDATES field risk independently. The validator never proposes placements, and the optimizer never scores its own field safety.

The validator is a progressive, physics-inspired damped-wave 2.5D voxel solver. The board is discretized into a cols × rows grid with three z-layers:

z layer role
0 F.Cu signal sources (noisy / high-current nets) and probes (sensitive nets) live here
1 dielectric couples the two copper layers
2 B.Cu ground run with strong damping so it acts as an energy sink (return/shield plane)

A leapfrog damped-wave update is integrated over the volume; aggressor nets inject an oscillating drive, component courtyards act as lossy obstacles, and vias bleed energy from the signal layer into the ground sink. The pass is progressive: it refines through cell sizes [4, 2, 1] mm and runs a convergence check across refinement. It reports:

  • per-level { cellMm, risk, peak, probeEnergy },
  • converged? and convergenceDeltaPct (stable when the finest-vs-second-finest risk delta is < 12%),
  • the hottest victim net (sensitiveProbeMax) and a per-probe risk ranking,
  • a normalized field heatmap of max|u| over time on the finest grid.

Be honest about what this is: it is physics-inspired progressive validation, a relative, model-based estimate of how much energy a noisy/high-current net is likely to dump onto a sensitive victim — not certified EMC and not a substitute for a real field solver or compliance testing. When --emi is on, the validator acts as a promotion gate: a substrate mutation that lowers the canonical score but regresses field risk (beyond a small tolerance) is rejected.


Quick start

npm install
npm run build          # tsc → dist/
npm run gen-examples   # synthesize the bundled example schematics
npm start              # launch the Electron desktop app

Or do it all in one shot:

npm run app    # build + gen-examples + launch the desktop app
npm run demo   # build + gen-examples + run the CLI demo across all boards

npm run demo runs the self-improvement loop on all three example boards and then runs the transfer demo (evolve the oscillator substrate on the buck board, apply it as a better optimizer to a brand-new motor board with zero new feedback). All artifacts land in build/. Use node dist/cli.js bench for the oscillator-vs-annealing head-to-head.


CLI reference

fieldratchet inspect <board.kicad_sch>
fieldratchet synth   <board.kicad_sch> [--optimizer oscillator|anneal] [--emi]
                                       [--out out.kicad_pcb] [--iterations N]
                                       [--rules rules.json] [--feedback "..."] [--config cfg.json]
fieldratchet learn   <board.kicad_sch> --feedback "keep buck away from imu" [--out rules.json]
fieldratchet batch   <dir|file>        [--optimizer oscillator|anneal] [--emi] [--iterations N] [--out build/]
fieldratchet demo                       [--iterations N]
fieldratchet bench                      [--iterations N]   # oscillator vs annealing, head-to-head

Invoke via npm run cli -- <args> or directly with node dist/cli.js <args>.

Command Purpose
inspect Parse a schematic and print components, detected roles, clusters, and nets — no placement.
synth Run the full improve loop on one board; write the board, SVGs, report, and learned rules.
learn Compile human --feedback into reusable layout rules (a short 4-iteration run) and save them to JSON.
batch Run synth over every .kicad_sch under a directory (or a single file) and write a batch-summary.json.
demo Run all bundled examples plus the learn→transfer demonstration.
bench Run both optimizers (annealing vs coupled-oscillator) on every example board and print a head-to-head score/time table.

Flags

Flag Applies to Meaning
--optimizer <oscillator|anneal> synth / batch Which optimizer to drive the ratchet. Default oscillator (coupled-oscillator Kuramoto substrate); anneal selects the simulated-annealing baseline.
--emi synth / batch Run the progressive voxel damped-wave EMI validation pass and use it as a non-regression promotion gate.
--out <path> synth / learn / batch Output board path (synth), rules file (learn), or output root dir (batch).
--iterations <N> synth / batch / demo / bench Number of ratchet iterations (default 8).
--rules <file> synth / learn Load a previously learned ruleset (rules + evolved substrate) to start from.
--feedback "<text>" synth / learn Natural-language guidance compiled into rules (e.g. "keep the buck hot loop tight and away from the imu").
--config <file> synth / learn Board config (width/height/diffPairs); auto-detected as fieldratchet.json next to the schematic.
--seed <N> synth Deterministic RNG seed (default 1337).

Benchmark results

bench grades both optimizers on the same canonical yardstick, so the comparison is apples-to-apples. On the bundled boards the coupled-oscillator substrate beats the annealing baseline by ~21–70% (lower score is better). And the substrate the RSI loop evolves on one board transfers as a ~24% better optimizer to a brand-new board with zero new feedback (the demo transfer stage). Re-run fieldratchet bench / fieldratchet demo to reproduce the exact numbers on your machine.

Examples

# Inspect topology only
node dist/cli.js inspect examples/buck_imu/buck_imu.kicad_sch

# Full self-improvement run (oscillator substrate by default), writing a board out
node dist/cli.js synth examples/buck_imu/buck_imu.kicad_sch \
  --iterations 10 --out build/buck_imu.kicad_pcb

# Same board, with the independent EMI field validation gate on
node dist/cli.js synth examples/buck_imu/buck_imu.kicad_sch --emi

# Use the annealing baseline instead of the oscillator substrate
node dist/cli.js synth examples/buck_imu/buck_imu.kicad_sch --optimizer anneal

# Head-to-head: oscillator vs annealing across the example boards
node dist/cli.js bench

# Learn a transferable rule from feedback
node dist/cli.js learn examples/buck_imu/buck_imu.kicad_sch \
  --feedback "keep the buck hot loop tight and away from the imu" \
  --out build/emi.rules.json

# Apply learned rules to a different board
node dist/cli.js synth examples/motor_driver/motor_driver.kicad_sch \
  --rules build/emi.rules.json --out build/motor.kicad_pcb

# Batch every schematic in a tree
node dist/cli.js batch examples --out build

Output files (per board)

File Contents
<name>.kicad_pcb Placed & routed KiCad board (KiCad 7/8 style).
<name>.board.svg Rendered board view.
<name>.heatmap.svg Field-risk (geometric proxy) heatmap with hotspots.
<name>.oscillator.svg Coupled-oscillator view: phase field, signed couplings, and the Kuramoto sync order parameter over the seed race (oscillator runs only).
<name>.emi.svg Progressive damped-wave EMI field heatmap (finest level) with the hottest victim net.
<name>.curve.svg Learning curve (score per iteration).
<name>.report.json Scores, term breakdown, iteration history, learned rules, evolved substrate, EMI summary, improvement %.
<name>.rules.json The ruleset (promoted rules + weights + evolved OscSubstrate) for reuse / transfer.

batch additionally writes batch-summary.json.


Example boards

Three mixed-signal boards are bundled (see examples/index.json). Each is a real synthesized .kicad_sch with a fieldratchet.json board config.

Name Title The layout tension
buck_imu Buck + ESP32 + IMU sensor board ESP32-S3, TPS62160 buck, USB-C, ICM-42688 IMU, 40 MHz crystal — keep the buck switching node away from the sensitive IMU/USB nets.
motor_driver BLDC motor driver board STM32G0 + DRV8313 + buck + INA240 current sensor — keep high-current motor nets and the buck away from sense/logic.
rf_sensor BLE RF sensor board nRF52840 + chip antenna + buck + BME280 — give the antenna a clear board-edge keepout away from the switcher.

Learning and transfer

This is the headline behavior, exercised by npm run demo:

  1. Evolve the optimizer on buck_imu (with the feedback "keep the buck hot loop tight and away from the imu"). The RSI loop mutates the oscillator substrate and promotes only the mutations (and symbolic rules) that lower the canonical score — the substrate that comes out is a better optimizer, not just a better board.
  2. Transfer that evolved substrate (+ promoted rules), unchanged, to the brand-new motor_driver board — with zero new feedback. The motor board is optimized once from a default substrate and once from the evolved substrate, same seed and same small iteration budget.
  3. Measure the canonical score in both cases. The evolved substrate reaches a lower-risk layout under the same budget — in the bundled run, the substrate the system improved on one board makes it a ~24% better optimizer on a different board.

This is the whole thesis in miniature: the optimizer improves itself, mutations are kept only when they measurably help, and because everything is judged on one canonical objective, the lessons transfer.


Architecture / repo map

src/core/ — the engine

Module Responsibility
sexpr.ts S-expression parse/serialize for KiCad files.
schematic.ts .kicad_sch parser + offline union-find netlister.
classify.ts Component roles, net classes, functional clusters → Design IR.
footprints.ts Procedural footprint/pad geometry.
geometry.ts 2D math (points, boxes, areas, segment intersection).
layoututil.ts Shared pad/courtyard world-coordinate helpers.
oscTypes.ts Shared contracts: the promotable OscSubstrate, compiled OscGraph, viz payload, and EmiReport.
osc.ts Coupled-oscillator (Kuramoto) placement optimizer — graph compile, batched phase integration, phase→coordinate decode, legalization; defaultSubstrate / mutateSubstrate. The RSI substrate.
emi.ts Independent progressive damped-wave 2.5D voxel EMI validator (validateEmiProgressive).
place.ts Anchored seeding + simulated-annealing placement (baseline + legalization polish).
route.ts Grid A* critical-net router (two-layer).
score.ts Canonical objective + field-risk proxy + hotspot detection.
rules.ts Rule synthesis from hotspots/feedback; promotion + weight deltas.
synth.ts Orchestrator: designFromSchematic, synthOnce (oscillator/anneal), and the improve ratchet loop (substrate mutation + EMI gate).
board.ts Emit .kicad_pcb.
svg.ts Board / heatmap / learning-curve / oscillator / EMI-field renderers.
schemgen.ts Author valid .kicad_sch (used to build the examples).
rng.ts Seeded deterministic RNG.
types.ts Shared IR types.

Apps and assets

  • src/cli.ts — the command-line front end (inspect/synth/learn/batch/demo/bench).
  • src/electron/ — Electron main.ts (process bridge to the core) and preload.ts.
  • app/ — the renderer UI (index.html, renderer.js, styles.css) with the clickable example boards.
  • src/scripts/gen-examples.ts — generates the bundled schematics into examples/.
  • examples/ — the three example boards + index.json.
  • docs/ — design docs, including oscillator-architecture.md (the full propose-vs-validate / substrate-RSI walkthrough), and docs/gallery/ (curated engine renders shown above).
  • build/ — generated outputs (git-ignored; created by synth/batch/demo).
  • mojo/ — the optional Mojo GPU acceleration path (see below).

Mojo GPU path

The working optimizer is the TypeScript reference in src/core/osc.ts; fieldratchet runs fully without Mojo — placement, routing, scoring, the EMI field check, and the RSI loop all execute in TypeScript today. mojo/fieldratchet_kernels/kuramoto_place.mojo is an optional GPU acceleration kernel — a batched, sparse-CSR Kuramoto integrator that maps 1:1 to the TS path and is expected to produce the same layouts for the same seeds. If the Modular toolchain isn't installed, none of it is used. See mojo/README.md and docs/oscillator-architecture.md for depth.


What it is / isn't

It is a fast, fully-offline first-pass layout engine plus a learning-review loop for small 2-layer mixed-signal boards. It produces a real, placed and critically-routed .kicad_pcb, and it learns reusable EE layout heuristics that it proves out against a measurable objective before keeping them.

It isn't:

  • A certified EMC tool. Two field signals exist, neither is compliance. The optimizer's objective is a fast geometric proxy (switch-loop area, centroid coupling, keepout distances, thermal density). The optional --emi pass adds an independent physics-inspired damped-wave voxel solver that estimates relative near-field coupling and checks refinement convergence — a useful, model-based cross-check, but still not certified EMC and not a substitute for a real field solver (e.g. openEMS) or lab testing.
  • A full autorouter. Routing is critical-nets-first: it routes the top handful of high-priority nets and deliberately leaves the rest as ratsnest for the scorer to penalize and the placer to minimize.
  • A finishing tool. Think of the output as an excellent, measurable starting point — not a fab-ready board.

License

MIT.

About

A recursively self-improving AI for PCB design: KiCad schematic in, placed & routed board out — getting measurably better on every iteration. Electron app + CLI.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages