From 2e433fcd0d1afadd8ab786dd30d7d4546bdee43d Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 11 Nov 2026 10:08:41 +0100 Subject: hw-toolchain: placer, routers and KiCad helpers for agent-driven hardware work Rust placer (simulated annealing) and negotiated-congestion router for 2-layer KiCad boards, pnr.sh to place, route, DRC-check and install candidates, Python KiCad helpers, repo conventions (AGENTS.md) and the tool documentation under knowledge/. Konnect (KiCad MCP, AGPL) as a submodule. Co-Authored-By: Claude Opus 5.5 --- tools/placer/src/anneal.rs | 461 +++++++++++++++++++++++++++++ tools/placer/src/congest.rs | 321 ++++++++++++++++++++ tools/placer/src/cost.rs | 696 +++++++++++++++++++++++++++++++++++++++++++ tools/placer/src/geom.rs | 174 +++++++++++ tools/placer/src/main.rs | 279 ++++++++++++++++++ tools/placer/src/model.rs | 700 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 2631 insertions(+) create mode 100644 tools/placer/src/anneal.rs create mode 100644 tools/placer/src/congest.rs create mode 100644 tools/placer/src/cost.rs create mode 100644 tools/placer/src/geom.rs create mode 100644 tools/placer/src/main.rs create mode 100644 tools/placer/src/model.rs (limited to 'tools/placer/src') diff --git a/tools/placer/src/anneal.rs b/tools/placer/src/anneal.rs new file mode 100644 index 0000000..96b18b8 --- /dev/null +++ b/tools/placer/src/anneal.rs @@ -0,0 +1,461 @@ +//! Simulated annealing over part positions and 90 degree turns (VPR-style schedule: moves +//! per temperature grow with N^(4/3), the cooling rate and move range adapt to the +//! acceptance rate). A run stops when it has converged: the best cost improved by less than +//! 0.1 % over the last 15 temperatures and fewer than 5 % of the moves are accepted. +//! The legality terms (overlap, band, bounds) start at 1 % and reach full weight once the +//! temperature has dropped by 100x, so that big parts can pass each other early on. +//! A push move shifts a part together with the parts it would run into (transitively), so +//! a row of parts can slide as one where moving any single one would overlap its neighbour. + +use crate::cost::State; +use crate::geom::{dist, turn, Pt, Rect}; +use crate::model::Model; +use rand::rngs::SmallRng; +use rand::{Rng, SeedableRng}; + +/// largest number of parts (masters) one push may move +const PUSH_MAX: usize = 8; + +#[derive(Clone, Copy, PartialEq)] +pub enum Start { + /// from the board's placement + Keep, + /// random positions inside each part's group bbox (or the board), random turns + Scramble, +} + +#[derive(Clone)] +pub struct Opts { + pub start: Start, + pub inner: f64, + pub seed: u64, + /// initial temperature = t0 x the standard deviation of random move deltas + pub t0: f64, + pub grid: f64, +} + +pub struct Run { + pub seed: u64, + pub cost: f64, + pub at: Vec, + pub rot: Vec, + pub moves: u64, + pub temps: u32, +} + +struct Ctx<'m> { + m: &'m Model, + swaps: Vec>, + groups: Vec, + /// movable ICs (>= 3 pads) with the movable 2-pad parts on their nets; a cluster move + /// takes those that are within 3 mm of the IC at the time + clusters: Vec>, + grid: f64, +} + +fn clusters(m: &Model) -> Vec> { + m.movable + .iter() + .filter(|&&i| m.parts[i].pads.len() >= 3) + .map(|&i| { + let mut c = vec![i]; + c.extend(m.movable.iter().copied().filter(|&j| { + m.parts[j].pads.len() == 2 && m.parts[j].nets.iter().any(|n| m.parts[i].nets.contains(n)) + })); + c + }) + .filter(|c| c.len() > 1) + .collect() +} + +impl<'m> Ctx<'m> { + fn snap(&self, v: f64) -> f64 { + (v / self.grid).round() * self.grid + } + + /// Keep a part's anchor such that its courtyard stays on the board. + fn clamp(&self, i: usize, at: Pt, r: u8) -> Pt { + let b = self.m.bounds; + let h = self.m.parts[i].hull.place((0.0, 0.0), r); + let fit = |v: f64, lo: f64, hi: f64| if lo <= hi { v.clamp(lo, hi) } else { (lo + hi) / 2.0 }; + (self.snap(fit(at.0, b.x0 - h.x0, b.x1 - h.x1)), self.snap(fit(at.1, b.y0 - h.y0, b.y1 - h.y1))) + } + + /// One random move as (part, anchor, rotation) triples. Single parts stay on the board; + /// a group move that would push a part off it is dropped. + fn pick(&self, s: &State, rng: &mut SmallRng, rlim: f64) -> Vec<(usize, Pt, u8)> { + let mut mv = self.pick_any(s, rng, rlim); + if mv.len() == 1 { + let (i, at, r) = mv[0]; + mv[0].1 = self.clamp(i, at, r); + } else if mv.iter().any(|&(i, at, r)| { + let h = self.m.parts[i].hull.place(at, r); + h.outside(&self.m.bounds) > 1e-9 + }) { + mv.clear(); + } + mv + } + + /// Shift part i by d with every movable part whose courtyard the moving ones would hit, + /// transitively. A follower that is hit brings its master (and so all its followers); + /// fixed parts are not pushed. Empty if more than PUSH_MAX parts would move. + fn push(&self, s: &State, i: usize, d: Pt) -> Vec<(usize, Pt, u8)> { + let m = self.m; + if d == (0.0, 0.0) { + return vec![]; + } + let mut c = vec![i]; + let mut moving: Vec = vec![false; m.parts.len()]; + let mut k = 0; + while k < c.len() { + let bodies: Vec = std::iter::once(c[k]).chain(m.parts[c[k]].followers.iter().copied()).collect(); + for &b in &bodies { + moving[b] = true; + } + for &b in &bodies { + let h = s.hull(b); + let moved = Rect::new(h.x0 + d.0, h.y0 + d.1, h.x1 + d.0, h.y1 + d.1); + for j in 0..m.parts.len() { + if moving[j] || m.parts[j].fixed || !s.hull(j).hits(&moved) { + continue; + } + let root = m.parts[j].follow.map_or(j, |(m0, _)| m0); + if !c.contains(&root) { + c.push(root); + if c.len() > PUSH_MAX { + return vec![]; + } + } + } + } + k += 1; + } + c.iter().map(|&j| (j, (s.at[j].0 + d.0, s.at[j].1 + d.1), s.rot[j])).collect() + } + + fn pick_any(&self, s: &State, rng: &mut SmallRng, rlim: f64) -> Vec<(usize, Pt, u8)> { + let m = self.m; + let mv = &m.movable; + let i = mv[rng.gen_range(0..mv.len())]; + let (at, r) = (s.at[i], s.rot[i]); + let jitter = |rng: &mut SmallRng| (rng.gen_range(-rlim..=rlim), rng.gen_range(-rlim..=rlim)); + let u: f64 = rng.gen(); + if u < 0.32 { + let (dx, dy) = jitter(rng); + vec![(i, (self.snap(at.0 + dx), self.snap(at.1 + dy)), r)] + } else if u < 0.40 { + // push: half of them along one axis only, which is how rows slide + let (mut dx, mut dy) = jitter(rng); + if rng.gen_bool(0.5) { + if rng.gen_bool(0.5) { + dx = 0.0 + } else { + dy = 0.0 + } + } + self.push(s, i, (self.snap(dx), self.snap(dy))) + } else if u < 0.55 { + vec![(i, at, (r + rng.gen_range(1..4)) & 3)] + } else if u < 0.62 { + let (dx, dy) = jitter(rng); + vec![(i, (self.snap(at.0 + dx), self.snap(at.1 + dy)), (r + rng.gen_range(1..4)) & 3)] + } else if u < 0.72 { + // swap with a part of the same footprint + let c = &self.swaps[i]; + if c.is_empty() { + return vec![]; + } + let j = c[rng.gen_range(0..c.len())]; + let k: u8 = if rng.gen_bool(0.5) { 0 } else { 2 }; + vec![(i, s.at[j], (s.rot[j] + k) & 3), (j, at, (r + k) & 3)] + } else if u < 0.80 { + // put one of its pads next to another pad of the same net (decaps: next to a pin) + let p = &m.parts[i]; + let own: Vec = p.pads.iter().copied().filter(|&k| m.pads[k].net.is_some()).collect(); + if own.is_empty() { + return vec![]; + } + let k = own[rng.gen_range(0..own.len())]; + let net = &m.nets[m.pads[k].net.unwrap()]; + let others: Vec = net.pads.iter().copied().filter(|&q| m.pads[q].part != i).collect(); + if others.is_empty() { + return vec![]; + } + let q = others[rng.gen_range(0..others.len())]; + let tq = s.pad_pos(q); + // land in front of the target pin when it has a direction + let qn = m.pads[q].normal.map(|n| turn(n, s.rot[m.pads[q].part])); + let d = rng.gen_range(1.2..3.0); + let (tx, ty) = match qn { + Some(n) => (tq.0 + n.0 * d + rng.gen_range(-0.6..0.6), tq.1 + n.1 * d + rng.gen_range(-0.6..0.6)), + None => { + let a = rng.gen_range(0.0..std::f64::consts::TAU); + (tq.0 + d * a.cos(), tq.1 + d * a.sin()) + } + }; + // turn so that our pad faces the target, else at random + let rot = match (m.pads[k].normal, qn) { + (Some(kn), Some(n)) => (0..4u8) + .max_by(|&a, &b| { + let fa = turn(kn, a); + let fb = turn(kn, b); + (-(fa.0 * n.0 + fa.1 * n.1)).partial_cmp(&-(fb.0 * n.0 + fb.1 * n.1)).unwrap() + }) + .unwrap(), + _ => rng.gen_range(0..4), + }; + let l = turn(m.pads[k].local, rot); + vec![(i, (self.snap(tx - l.0), self.snap(ty - l.1)), rot)] + } else if u < 0.88 { + // an IC with its satellites: shift, or turn about the IC + if self.clusters.is_empty() { + return vec![]; + } + let all = &self.clusters[rng.gen_range(0..self.clusters.len())]; + let near = s.hull(all[0]).grow(3.0); + let c: Vec = all.iter().copied().enumerate().filter(|&(k, j)| k == 0 || s.hull(j).hits(&near)).map(|(_, j)| j).collect(); + let o = s.at[c[0]]; + if rng.gen_bool(0.75) { + let (dx, dy) = jitter(rng); + let (dx, dy) = (self.snap(dx), self.snap(dy)); + c.iter().map(|&j| (j, (s.at[j].0 + dx, s.at[j].1 + dy), s.rot[j])).collect() + } else { + let k = rng.gen_range(1..4u8); + c.iter() + .map(|&j| { + let d = turn((s.at[j].0 - o.0, s.at[j].1 - o.1), k); + (j, (self.snap(o.0 + d.0), self.snap(o.1 + d.1)), (s.rot[j] + k) & 3) + }) + .collect() + } + } else { + // a whole group: shift, or turn about its centre + if self.groups.is_empty() { + return vec![]; + } + let g = &m.groups[self.groups[rng.gen_range(0..self.groups.len())]]; + if rng.gen_bool(0.75) { + let (dx, dy) = jitter(rng); + let (dx, dy) = (self.snap(dx), self.snap(dy)); + g.parts.iter().map(|&j| (j, (s.at[j].0 + dx, s.at[j].1 + dy), s.rot[j])).collect() + } else { + let k = rng.gen_range(1..4u8); + let n = g.parts.len() as f64; + let c = g.parts.iter().fold((0.0, 0.0), |a, &j| (a.0 + s.at[j].0 / n, a.1 + s.at[j].1 / n)); + g.parts + .iter() + .map(|&j| { + let d = turn((s.at[j].0 - c.0, s.at[j].1 - c.1), k); + (j, (self.snap(c.0 + d.0), self.snap(c.1 + d.1)), (s.rot[j] + k) & 3) + }) + .collect() + } + } + } +} + +fn scramble(m: &Model, rng: &mut SmallRng, grid: f64) -> (Vec, Vec) { + let mut at: Vec = m.parts.iter().map(|p| p.at0).collect(); + let mut rot: Vec = m.parts.iter().map(|p| p.rot0).collect(); + let fixed: Vec<_> = (0..m.parts.len()).filter(|&j| m.parts[j].fixed).map(|j| m.parts[j].hull.place(at[j], rot[j])).collect(); + for &i in &m.movable { + let p = &m.parts[i]; + let area = p.groups.iter().find_map(|&g| m.groups[g].bbox).unwrap_or(m.bounds); + // the spot of a few random tries that overlaps the fixed parts least + let mut best = (f64::MAX, (0.0, 0.0), 0u8); + for _ in 0..20 { + let r = rng.gen_range(0..4u8); + let h = p.hull.place((0.0, 0.0), r); + let (x0, x1) = (area.x0 - h.x0, area.x1 - h.x1); + let (y0, y1) = (area.y0 - h.y0, area.y1 - h.y1); + let x = if x1 > x0 { rng.gen_range(x0..x1) } else { (x0 + x1) / 2.0 }; + let y = if y1 > y0 { rng.gen_range(y0..y1) } else { (y0 + y1) / 2.0 }; + let at = ((x / grid).round() * grid, (y / grid).round() * grid); + let hw = p.hull.place(at, r); + let ov: f64 = fixed.iter().map(|f| f.inter(&hw)).sum(); + if ov < best.0 { + best = (ov, at, r); + } + if ov == 0.0 { + break; + } + } + at[i] = best.1; + rot[i] = best.2; + } + m.sync(&mut at, &mut rot); + (at, rot) +} + +pub fn anneal(m: &Model, o: &Opts) -> Run { + let mut rng = SmallRng::seed_from_u64(o.seed); + let (at, rot) = match o.start { + Start::Keep => { + let (mut at, mut rot): (Vec, Vec) = (m.parts.iter().map(|p| p.at0).collect(), m.parts.iter().map(|p| p.rot0).collect()); + m.sync(&mut at, &mut rot); + (at, rot) + } + Start::Scramble => scramble(m, &mut rng, o.grid), + }; + let mut s = State::new(m, at, rot); + let swaps = m + .parts + .iter() + .enumerate() + .map(|(i, p)| { + if p.fixed { + return vec![]; + } + m.movable.iter().copied().filter(|&j| j != i && m.parts[j].fpid == p.fpid).collect() + }) + .collect(); + let groups = (0..m.groups.len()).filter(|&g| m.groups[g].parts.len() >= 2).collect(); + let ctx = Ctx { m, swaps, groups, clusters: clusters(m), grid: o.grid }; + let diag = dist((m.bounds.x0, m.bounds.y0), (m.bounds.x1, m.bounds.y1)); + let nmov = m.movable.len().max(1) as f64; + let per_t = (o.inner * nmov.powf(4.0 / 3.0)).ceil() as usize; + let nnets = m.nets.len().max(1) as f64; + + // initial temperature from the spread of random move deltas, measured with the legality + // terms at their starting weight (at full weight a scrambled start's overlaps dominate) + const PEN0: f64 = 0.01; + if o.start == Start::Scramble { + s.set_pen(PEN0); + } + let mut rlim = if o.start == Start::Keep { 2.0 } else { diag }; + let mut deltas = vec![]; + for _ in 0..(per_t.min(500)) { + let mv = ctx.pick(&s, &mut rng, rlim); + if mv.is_empty() { + continue; + } + let d = s.propose(&mv); + deltas.push(d); + s.reject(); + } + let mean = deltas.iter().sum::() / deltas.len().max(1) as f64; + let sd = (deltas.iter().map(|d| (d - mean).powi(2)).sum::() / deltas.len().max(1) as f64).sqrt(); + let mut t = o.t0 * sd; + let t_full = t / 100.0; + let ramp = |t: f64| if o.start == Start::Keep { 1.0 } else { (t_full / t).clamp(PEN0, 1.0) }; + s.set_pen(ramp(t)); + let mut moves = 0u64; + // PLACER_TRACE=1: one line per temperature on stderr + let trace = std::env::var("PLACER_TRACE").is_ok(); + let mut temps = 0u32; + let mut best = (f64::MAX, s.at.clone(), s.rot.clone()); + let (mut mark, mut stall) = (f64::MAX, 0); + loop { + let mut acc = 0usize; + let mut tried = 0usize; + for _ in 0..per_t { + let mv = ctx.pick(&s, &mut rng, rlim); + if mv.is_empty() { + continue; + } + tried += 1; + let d = s.propose(&mv); + if d <= 0.0 || (t > 0.0 && rng.gen::() < (-d / t).exp()) { + s.accept(); + acc += 1; + if s.pen() == 1.0 && s.total < best.0 { + best = (s.total, s.at.clone(), s.rot.clone()); + } + } else { + s.reject(); + } + } + moves += tried as u64; + temps += 1; + let a = acc as f64 / tried.max(1) as f64; + if trace { + let big = *m.movable.iter().max_by_key(|&&i| m.parts[i].pads.len()).unwrap(); + eprintln!( + "t {temps:3} T {t:10.3} pen {:.3} acc {a:.3} rlim {rlim:6.2} cost {:10.1} {} at ({:.1}, {:.1})", + s.pen(), + s.total, + m.parts[big].reference, + s.at[big].0, + s.at[big].1 + ); + } + rlim = (rlim * (1.0 - 0.44 + a)).clamp(0.3, diag); + t *= if a > 0.96 { + 0.5 + } else if a > 0.8 { + 0.9 + } else if a > 0.15 { + 0.95 + } else { + 0.8 + }; + // converged: no real progress for 15 temperatures and hardly anything accepted + s.set_pen(ramp(t)); + if s.pen() < 1.0 { + continue; + } + if s.total < best.0 { + best = (s.total, s.at.clone(), s.rot.clone()); + } + if best.0 < mark * (1.0 - 1e-3) { + mark = best.0; + stall = 0; + } else { + stall += 1; + } + if (stall >= 15 && a < 0.05) || t < 1e-9 * nnets || temps >= 1000 { + break; + } + } + // quench: greedy small moves from the best state, with the legality terms at 10x so that + // leftover overlaps are pushed out + let mut s = State::new(m, best.1, best.2); + s.set_pen(10.0); + for _ in 0..per_t * 4 { + let mv = ctx.pick(&s, &mut rng, 0.5); + if mv.is_empty() { + continue; + } + if s.propose(&mv) < 0.0 { + s.accept(); + } else { + s.reject(); + } + moves += 1; + } + s.set_pen(1.0); + let cost = s.total; + Run { seed: o.seed, cost, at: s.at.clone(), rot: s.rot.clone(), moves, temps } +} + +/// Random moves with random acceptance; checks the incremental total against a full +/// recomputation. Returns the largest drift seen. +pub fn selftest(m: &Model, moves: usize, seed: u64) -> f64 { + let mut rng = SmallRng::seed_from_u64(seed); + let (at, rot) = scramble(m, &mut rng, 0.05); + let mut s = State::new(m, at, rot); + let swaps = (0..m.parts.len()).map(|_| vec![]).collect(); + let groups = (0..m.groups.len()).filter(|&g| m.groups[g].parts.len() >= 2).collect(); + let ctx = Ctx { m, swaps, groups, clusters: clusters(m), grid: 0.05 }; + let mut worst: f64 = 0.0; + for k in 0..moves { + let r = rng.gen_range(0.3..10.0); + let mv = ctx.pick(&s, &mut rng, r); + if mv.is_empty() { + continue; + } + s.propose(&mv); + if rng.gen_bool(0.5) { + s.accept(); + } else { + s.reject(); + } + if k % 500 == 499 { + let inc = s.total; + let full = s.recompute().total(); + worst = worst.max((inc - full).abs() / full.abs().max(1.0)); + } + } + worst +} diff --git a/tools/placer/src/congest.rs b/tools/placer/src/congest.rs new file mode 100644 index 0000000..db61efc --- /dev/null +++ b/tools/placer/src/congest.rs @@ -0,0 +1,321 @@ +//! Routing channels: how much track a placement asks for compared with the room between the +//! pads. Two measures on a grid of cells: +//! +//! rudy each ratsnest line spreads its track (Manhattan length x the class's track + +//! clearance) evenly over its bounding box; overflow = track area above the cells' +//! room, in mm of default track. Cheap; blind to detours. +//! groute coarse global routing with negotiated congestion (PathFinder): every net is +//! routed as a tree (Dijkstra to the nearest tree node) on two layers with vias; cells used beyond their room +//! get dearer each round (present and history cost) until nobody overuses them or +//! the rounds run out. Reports the remaining overflow, length and vias. +//! +//! Room of a cell per layer = its width, minus pads (grown by the clearance; SMD pads block +//! F.Cu, THT pads both layers), track keep-outs and the edge clearance. Cells holding a pin are +//! not counted as overflowing: a pad would otherwise block its own net. + +use crate::cost::State; +use crate::geom::{Pt, Rect}; +use crate::model::Model; +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +const CLR: f64 = 0.2; +/// default track + clearance (mm), the unit of the overflow figures +const UNIT: f64 = 0.4; + +pub struct Grid { + x0: f64, + y0: f64, + cell: f64, + nx: usize, + ny: usize, + /// room per node (layer * nx * ny + cell), mm of cross-section + cap: Vec, + /// node holds a pin of some net + pin: Vec, +} + +impl Grid { + fn idx(&self, p: Pt) -> (usize, usize) { + let i = (((p.0 - self.x0) / self.cell).floor().max(0.0) as usize).min(self.nx - 1); + let j = (((p.1 - self.y0) / self.cell).floor().max(0.0) as usize).min(self.ny - 1); + (i, j) + } + + fn cell_rect(&self, i: usize, j: usize) -> Rect { + let x = self.x0 + i as f64 * self.cell; + let y = self.y0 + j as f64 * self.cell; + Rect::new(x, y, x + self.cell, y + self.cell) + } + + /// Cells overlapped by r: (i, j, overlap area). + fn cover(&self, r: &Rect) -> Vec<(usize, usize, f64)> { + let (i0, j0) = self.idx((r.x0, r.y0)); + let (i1, j1) = self.idx((r.x1, r.y1)); + let mut v = vec![]; + for j in j0..=j1 { + for i in i0..=i1 { + let a = self.cell_rect(i, j).inter(r); + if a > 0.0 { + v.push((i, j, a)); + } + } + } + v + } + + pub fn new(m: &Model, s: &State, cell: f64) -> Grid { + let b = m.bounds; + let nx = ((b.x1 - b.x0) / cell).ceil() as usize; + let ny = ((b.y1 - b.y0) / cell).ceil() as usize; + let n = nx * ny; + let mut g = Grid { x0: b.x0, y0: b.y0, cell, nx, ny, cap: vec![cell; 2 * n], pin: vec![false; 2 * n] }; + let area = cell * cell; + let block = |g: &mut Grid, r: &Rect, layers: &[usize]| { + for (i, j, a) in g.cover(r) { + for &l in layers { + let k = l * n + j * nx + i; + g.cap[k] -= cell * a / area; + } + } + }; + for (k, pad) in m.pads.iter().enumerate() { + let r = s.pad_rect(k).grow(CLR); + let layers: &[usize] = if pad.tht { &[0, 1] } else { &[0] }; + block(&mut g, &r, layers); + let (i, j) = g.idx(s.pad_pos(k)); + for &l in layers { + g.pin[l * n + j * nx + i] = true; + } + } + for r in &m.track_keepouts { + block(&mut g, r, &[0, 1]); + } + // the edge clearance: everything outside the board shrunk by it + let inner = b.grow(-m.w.edge); + for j in 0..ny { + for i in 0..nx { + let c = g.cell_rect(i, j); + let out = c.area() - c.inter(&inner); + for l in 0..2 { + g.cap[l * n + j * nx + i] -= cell * out / area; + } + } + } + for c in g.cap.iter_mut() { + *c = c.max(0.0); + } + g + } +} + +/// RUDY overflow in mm of default track. +pub fn rudy(m: &Model, s: &State, g: &Grid) -> f64 { + let n = g.nx * g.ny; + let mut demand = vec![0.0; n]; + for (a, b, net) in s.lines() { + let l1 = (a.0 - b.0).abs() + (a.1 - b.1).abs(); + let mut r = Rect::new(a.0, a.1, b.0, b.1); + // at least one cell wide, so straight lines spread over their own cells + let gx = ((g.cell - (r.x1 - r.x0)) / 2.0).max(0.0); + let gy = ((g.cell - (r.y1 - r.y0)) / 2.0).max(0.0); + r = Rect::new(r.x0 - gx, r.y0 - gy, r.x1 + gx, r.y1 + gy); + let track = l1 * m.nets[net].pitch; + let ra = r.area(); + for (i, j, a) in g.cover(&r) { + demand[j * g.nx + i] += track * a / ra; + } + } + let mut over = 0.0; + for c in 0..n { + let room = (g.cap[c] + g.cap[n + c]) * g.cell; + over += (demand[c] - room).max(0.0); + } + over / UNIT +} + +#[derive(Debug, Default, Clone, Copy)] +pub struct GResult { + /// default tracks beyond the cells' room after the last round, summed over cells + pub overflow: f64, + /// cells (per layer) still overused + pub over_cells: usize, + pub length: f64, + pub vias: usize, + pub rounds: usize, +} + +#[derive(PartialEq)] +struct Q(f64, usize); +impl Eq for Q {} +impl PartialOrd for Q { + fn partial_cmp(&self, o: &Self) -> Option { + Some(self.cmp(o)) + } +} +impl Ord for Q { + fn cmp(&self, o: &Self) -> Ordering { + o.0.total_cmp(&self.0) // min-heap + } +} + +pub struct GOpts { + pub rounds: usize, + /// via cost in cells + pub via: f64, + /// B.Cu step cost factor (the detailed router prefers F.Cu) + pub bmult: f64, +} + +impl Default for GOpts { + fn default() -> Self { + GOpts { rounds: 30, via: 4.0, bmult: 1.5 } + } +} + +pub fn groute(m: &Model, s: &State, g: &Grid, o: &GOpts) -> GResult { + let n = g.nx * g.ny; + let nn = 2 * n; + // nets as pin lists (node sets per pin: F, or F and B for THT), in Prim order + struct GNet { + pins: Vec>, + d: f64, + } + let mut nets = vec![]; + for net in &m.nets { + let mut pins: Vec<(Pt, Vec)> = vec![]; + for &k in &net.pads { + let p = s.pad_pos(k); + let (i, j) = g.idx(p); + let c = j * g.nx + i; + let nodes = if m.pads[k].tht { vec![c, n + c] } else { vec![c] }; + if !pins.iter().any(|(_, v)| v[0] == c) { + pins.push((p, nodes)); + } + } + if pins.len() < 2 { + continue; + } + let pts: Vec = pins.iter().map(|p| p.0).collect(); + let mut order = vec![0]; + for (_, b) in crate::geom::mst(&pts) { + order.push(b); + } + // a track wider than a cell takes the whole cell (and its neighbours' room is not tracked) + nets.push(GNet { pins: order.into_iter().map(|k| pins[k].1.clone()).collect(), d: net.pitch.min(g.cell) }); + } + + let mut usage = vec![0.0; nn]; + let mut hist = vec![0.0; nn]; + let mut paths: Vec> = vec![vec![]; nets.len()]; + let mut vias = vec![0usize; nets.len()]; + let mut gcost = vec![f64::INFINITY; nn]; + let mut par = vec![usize::MAX; nn]; + let mut stamp = vec![0u32; nn]; + let mut intree = vec![0u32; nn]; + let mut call = 0u32; + let mut tcall = 0u32; + let mut res = GResult::default(); + let mut pf = 0.5; + for round in 0..o.rounds { + res.rounds = round + 1; + for (ni, net) in nets.iter().enumerate() { + for &v in &paths[ni] { + usage[v] -= net.d; + } + paths[ni].clear(); + vias[ni] = 0; + tcall += 1; + let mut tree: Vec = net.pins[0].clone(); + for &v in &tree { + intree[v] = tcall; + } + for pin in &net.pins[1..] { + if pin.iter().any(|&v| intree[v] == tcall) { + continue; + } + // Dijkstra from the pin to the nearest node of the tree (several targets, so no + // simple heuristic); the grid is small enough + call += 1; + let mut heap = BinaryHeap::new(); + for &v in pin { + stamp[v] = call; + gcost[v] = 0.0; + par[v] = usize::MAX; + heap.push(Q(0.0, v)); + } + let mut found = usize::MAX; + while let Some(Q(_, v)) = heap.pop() { + if intree[v] == tcall { + found = v; + break; + } + let gv = gcost[v]; + let (l, c) = (v / n, v % n); + let (x, y) = ((c % g.nx) as i64, (c / g.nx) as i64); + let mut relax = |w: usize, step: f64, heap: &mut BinaryHeap| { + let lw = w / n; + let over = if g.pin[w] { 0.0 } else { (usage[w] + net.d - g.cap[w]).max(0.0) / UNIT }; + let base = step * if lw == 1 { o.bmult } else { 1.0 }; + let ng = gv + base * (1.0 + hist[w]) * (1.0 + pf * over); + if stamp[w] != call || ng < gcost[w] { + stamp[w] = call; + gcost[w] = ng; + par[w] = v; + heap.push(Q(ng, w)); + } + }; + for (dx, dy, st) in [(1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0), (1, 1, 1.414), (1, -1, 1.414), (-1, 1, 1.414), (-1, -1, 1.414)] { + let (qx, qy) = (x + dx, y + dy); + if qx < 0 || qy < 0 || qx >= g.nx as i64 || qy >= g.ny as i64 { + continue; + } + relax(l * n + qy as usize * g.nx + qx as usize, st, &mut heap); + } + relax((1 - l) * n + c, o.via, &mut heap); + } + if found == usize::MAX { + continue; + } + let mut v = found; + while v != usize::MAX { + if intree[v] != tcall { + intree[v] = tcall; + tree.push(v); + } + let p = par[v]; + if p != usize::MAX && p / n != v / n { + vias[ni] += 1; + } + v = p; + } + } + for &v in &tree { + usage[v] += net.d; + } + paths[ni] = tree; + } + let mut over = 0.0; + let mut cells = 0; + for v in 0..nn { + if g.pin[v] { + continue; + } + let ov = usage[v] - g.cap[v]; + if ov > 1e-9 { + over += ov; + cells += 1; + hist[v] += 0.3 * ov / UNIT; + } + } + res.overflow = over / UNIT; + res.over_cells = cells; + if cells == 0 { + break; + } + pf *= 1.6; + } + res.length = paths.iter().map(|p| p.len() as f64 * g.cell).sum(); + res.vias = vias.iter().sum(); + res +} diff --git a/tools/placer/src/cost.rs b/tools/placer/src/cost.rs new file mode 100644 index 0000000..a91e25d --- /dev/null +++ b/tools/placer/src/cost.rs @@ -0,0 +1,696 @@ +//! Placement cost with incremental updates: a move changes only the nets, part pairs and +//! part terms of the parts it moves, so only those are evaluated again. Crossings and blocks +//! are updated from the ratsnest lines that changed (most of a big net's MST stays as it was) +//! and from the moved pads. +//! +//! Terms (weights in model::Weights): +//! per net ratsnest length x net weight, escape (lines leaving a pin backwards), +//! decoupling (cap to its pin, ground pad to the IC's ground pin), coverage +//! (every decoupled IC pin has a cap within 3 mm) +//! global crossings of ratsnest lines of different nets (each one a via on 2 layers); +//! the line from each decap to its pin counts too, so caps keep pin order +//! per net/part block: ratsnest lines over another net's pads (a detour or a via) +//! per pair courtyard overlap, other parts' pads in a fine-pitch IC's fan-out band, +//! [[link]] pads farther apart than allowed +//! per part outside the board / pad edge clearance, in a keep-out, outside a group bbox; +//! [[pull]] pads' distance to their board side +//! +//! A move of a replicated channel's master moves its followers along (propose expands it). + +use crate::geom::{crosses, dist, mst, seg_hits, turn, Pt, Rect}; +use crate::model::Model; + +#[derive(Clone, Copy)] +pub struct Seg { + a: Pt, + b: Pt, + w: f64, + bb: Rect, + net: usize, + /// parts at the two ends + pa: usize, + pb: usize, +} + +/// The same line (pad positions are recomputed identically, so exact comparison works). +fn same(e: &Seg, f: &Seg) -> bool { + (e.a == f.a && e.b == f.b) || (e.a == f.b && e.b == f.a) +} + +fn cross_w(e: &Seg, f: &Seg) -> f64 { + if e.bb.hits(&f.bb) && crosses(e.a, e.b, f.a, f.b) { + (e.w + f.w) / 2.0 + } else { + 0.0 + } +} + +/// A net's lines after a proposed move. +struct Pending { + net: usize, + cost: f64, + segs: Vec, + bb: Rect, + /// old lines that are gone + removed: Vec, + /// new lines that were not there before + added: Vec, +} + +/// Weighted cost terms (and the raw crossing count) of a whole placement. +#[derive(Default, Clone, Copy, Debug, serde::Serialize)] +pub struct Terms { + pub length: f64, + pub escape: f64, + pub decap: f64, + pub cover: f64, + pub crossing: f64, + pub overlap: f64, + pub band: f64, + pub bounds: f64, + pub block: f64, + pub link: f64, + pub pull: f64, + pub crossings: usize, + pub ratsnest_mm: f64, +} + +impl Terms { + pub fn total(&self) -> f64 { + self.length + self.escape + self.decap + self.cover + self.crossing + self.overlap + self.band + self.bounds + self.block + self.link + self.pull + } +} + +#[derive(Default, Clone, Copy)] +struct NetT { + length: f64, + escape: f64, + decap: f64, + cover: f64, + mm: f64, +} + +impl NetT { + fn sum(&self) -> f64 { + self.length + self.escape + self.decap + self.cover + } +} + +pub struct State<'m> { + pub m: &'m Model, + pub at: Vec, + pub rot: Vec, + pp: Vec, + /// courtyard hull of each part on the board + hull_w: Vec, + net_cost: Vec, + segs: Vec>, + /// bounding box of each net's lines + nbb: Vec, + pair: Vec, + unary: Vec, + pub total: f64, + /// scale of the legality terms (overlap, band, bounds); the annealer ramps it up to 1 + pen: f64, + // pending move + cur: u32, + nstamp: Vec, + pstamp: Vec, + moved: Vec, + old: Vec<(Pt, u8)>, + new: Vec<(Pt, u8)>, + p_net: Vec, + p_pair: Vec<(usize, f64)>, + p_un: Vec<(usize, f64)>, + p_delta: f64, +} + +/// A rectangle that hits nothing. +const NONE: Rect = Rect { x0: f64::INFINITY, y0: f64::INFINITY, x1: f64::NEG_INFINITY, y1: f64::NEG_INFINITY }; + +fn segs_bb(segs: &[Seg]) -> Rect { + segs.iter().fold(NONE, |a, e| a.union(&e.bb)) +} + +fn cross_between(a: &[Seg], b: &[Seg]) -> f64 { + let mut s = 0.0; + for e in a { + for f in b { + if e.bb.hits(&f.bb) && crosses(e.a, e.b, f.a, f.b) { + s += (e.w + f.w) / 2.0; + } + } + } + s +} + +impl<'m> State<'m> { + pub fn new(m: &'m Model, at: Vec, rot: Vec) -> State<'m> { + let n = m.parts.len(); + let mut s = State { + m, + at, + rot, + pp: vec![(0.0, 0.0); m.pads.len()], + hull_w: vec![Rect::default(); n], + net_cost: vec![0.0; m.nets.len()], + segs: vec![vec![]; m.nets.len()], + nbb: vec![NONE; m.nets.len()], + pair: vec![0.0; n * n], + unary: vec![0.0; n], + total: 0.0, + pen: 1.0, + cur: 0, + nstamp: vec![0; m.nets.len()], + pstamp: vec![0; n], + moved: vec![], + old: vec![], + new: vec![], + p_net: vec![], + p_pair: vec![], + p_un: vec![], + p_delta: 0.0, + }; + s.recompute(); + s + } + + /// Scale the legality terms and re-evaluate. + pub fn set_pen(&mut self, pen: f64) { + if pen != self.pen { + self.pen = pen; + self.recompute(); + } + } + + pub fn pen(&self) -> f64 { + self.pen + } + + pub fn initial(m: &'m Model) -> State<'m> { + State::new(m, m.parts.iter().map(|p| p.at0).collect(), m.parts.iter().map(|p| p.rot0).collect()) + } + + /// Evaluate everything from scratch; returns the terms. + pub fn recompute(&mut self) -> Terms { + let m = self.m; + for i in 0..m.parts.len() { + self.place_pads(i); + } + let mut t = Terms::default(); + for n in 0..m.nets.len() { + let (nt, segs) = self.net_eval(n); + self.net_cost[n] = nt.sum(); + self.nbb[n] = segs_bb(&segs); + self.segs[n] = segs; + t.length += nt.length; + t.escape += nt.escape; + t.decap += nt.decap; + t.cover += nt.cover; + t.ratsnest_mm += nt.mm; + } + let mut x = 0.0; + for a in 0..m.nets.len() { + for b in a + 1..m.nets.len() { + let c = cross_between(&self.segs[a], &self.segs[b]); + x += c; + if c > 0.0 { + t.crossings += self.segs[a] + .iter() + .map(|e| self.segs[b].iter().filter(|f| e.bb.hits(&f.bb) && crosses(e.a, e.b, f.a, f.b)).count()) + .sum::(); + } + } + } + t.crossing = m.w.crossing * x; + let n = m.parts.len(); + for i in 0..n { + for j in i + 1..n { + let (ov, band, link) = self.pair_eval(i, j); + self.pair[i * n + j] = ov + band + link; + t.overlap += ov; + t.band += band; + t.link += link; + } + let (bounds, pull) = self.unary_eval(i); + self.unary[i] = bounds + pull; + t.bounds += bounds; + t.pull += pull; + } + let all: Vec = (0..n).collect(); + t.block = m.w.block * self.segs.iter().flatten().map(|e| self.block_parts(e, &all)).sum::(); + self.total = t.total(); + t + } + + fn set_pose(&mut self, i: usize, at: Pt, r: u8) { + self.at[i] = at; + self.rot[i] = r; + self.place_pads(i); + } + + fn place_pads(&mut self, i: usize) { + let p = &self.m.parts[i]; + self.hull_w[i] = p.hull.place(self.at[i], self.rot[i]); + for &k in &p.pads { + let l = turn(self.m.pads[k].local, self.rot[i]); + self.pp[k] = (self.at[i].0 + l.0, self.at[i].1 + l.1); + } + } + + pub fn pad_rect(&self, k: usize) -> Rect { + let pad = &self.m.pads[k]; + let h = if self.rot[pad.part] & 1 == 1 { (pad.half.1, pad.half.0) } else { pad.half }; + Rect::around(self.pp[k], h.0, h.1) + } + + fn net_eval(&self, n: usize) -> (NetT, Vec) { + let m = self.m; + let w = &m.w; + let net = &m.nets[n]; + let mut t = NetT::default(); + let pts: Vec = net.pads.iter().map(|&k| self.pp[k]).collect(); + let mut segs = Vec::with_capacity(pts.len()); + let mut esc = 0.0; + for (i, j) in mst(&pts) { + let (a, b) = (pts[i], pts[j]); + let l = dist(a, b); + t.mm += l; + let (ka, kb) = (net.pads[i], net.pads[j]); + let (pa, pb) = (m.pads[ka].part, m.pads[kb].part); + segs.push(Seg { a, b, w: net.weight, bb: Rect::new(a.0, a.1, b.0, b.1), net: n, pa, pb }); + if pa == pb || l < 1e-6 { + continue; // same part: fixed geometry + } + for (k, from, to) in [(ka, a, b), (kb, b, a)] { + if let Some(nl) = m.pads[k].normal { + let nw = turn(nl, self.rot[m.pads[k].part]); + let c = (nw.0 * (to.0 - from.0) + nw.1 * (to.1 - from.1)) / l; + esc += ((1.0 - c) / 2.0).powi(2) * l.min(m.parts[m.pads[k].part].detour); + } + } + } + t.length = net.weight * w.length * t.mm; + // not scaled by the net weight: a pin facing away costs a detour on any net + t.escape = w.escape * esc; + for &d in &net.decaps { + let dc = &m.decaps[d]; + let (s, g) = (self.pp[dc.sig], self.pp[dc.gnd]); + let mut best = (f64::MAX, 0.0, 0); + for (c, gp) in &dc.cands { + let ds = dist(s, self.pp[*c]); + let dg = gp.iter().map(|&q| dist(g, self.pp[q])).fold(f64::MAX, f64::min); + let v = ds + if dg < f64::MAX { 0.5 * dg } else { 0.0 }; + if v < best.0 { + best = (v, ds, *c); + } + } + // the cap is routed to this pin first: its line takes part in the crossings + let c = self.pp[best.2]; + let pb = m.pads[best.2].part; + segs.push(Seg { a: s, b: c, w: net.weight, bb: Rect::new(s.0, s.1, c.0, c.1), net: n, pa: dc.part, pb }); + let (lim, coef) = if dc.bulk { (8.0, 0.3) } else { (3.0, 1.0) }; + // quadratic for the first 2 mm past the limit, then linear (a far cap still pulls, + // but a scrambled start does not swamp everything else) + let x = (best.1 - lim).max(0.0); + let over = if x <= 2.0 { x * x } else { 4.0 * x - 4.0 }; + t.decap += w.decap * coef * best.0 + w.decap_limit * over; + } + for &q in &net.cover { + let near = net + .decaps + .iter() + .map(|&d| dist(self.pp[m.decaps[d].sig], self.pp[q])) + .fold(f64::MAX, f64::min); + t.cover += w.cover * (near - 3.0).max(0.0).min(20.0); + } + (t, segs) + } + + /// Cost of a [[link]] at the current poses (0 within its distance). + fn link_eval(&self, l: usize) -> f64 { + let k = &self.m.links[l]; + let x = (dist(self.pp[k.a], self.pp[k.b]) - k.max).max(0.0); + self.m.w.link * k.weight * if x <= 2.0 { x * x } else { 4.0 * x - 4.0 } + } + + /// (overlap, band, link) cost of a pair of parts. + fn pair_eval(&self, i: usize, j: usize) -> (f64, f64, f64) { + let m = self.m; + let (a, b) = (&m.parts[i], &m.parts[j]); + let mut link = 0.0; + for &l in &a.links { + let k = &m.links[l]; + let (pa, pb) = (m.pads[k.a].part, m.pads[k.b].part); + if (pa == i && pb == j) || (pa == j && pb == i) { + link += self.link_eval(l); + } + } + if a.fixed && b.fixed { + return (0.0, 0.0, link); + } + let g = m.w.fanout; + if !self.hull_w[i].grow(g).hits(&self.hull_w[j].grow(g)) { + return (0.0, 0.0, link); + } + let mut ov = 0.0; + for ra in &a.court { + let ra = ra.place(self.at[i], self.rot[i]); + for rb in &b.court { + ov += ra.inter(&rb.place(self.at[j], self.rot[j])); + } + } + let mut band = 0.0; + for (x, y) in [(i, j), (j, i)] { + if let Some(bl) = m.parts[x].band { + let br = bl.place(self.at[x], self.rot[x]); + for &k in &m.parts[y].pads { + band += br.inter(&self.pad_rect(k)); + } + } + } + (self.pen * m.w.overlap * ov, self.pen * m.w.band * band, link) + } + + /// Unweighted block cost of line `e` over the pads of `parts` (pads of other nets; parts + /// at the line's own ends are left out, the escape term covers those). + fn block_parts(&self, e: &Seg, parts: &[usize]) -> f64 { + let m = self.m; + let mut s = 0.0; + for &j in parts { + if j == e.pa || j == e.pb || !e.bb.hits(&self.hull_w[j]) { + continue; + } + for &k in &m.parts[j].pads { + if m.pads[k].net != Some(e.net) && seg_hits(e.a, e.b, &self.pad_rect(k)) { + s += e.w; + } + } + } + s + } + + /// Lines that changed with the pending move: the new ones (after) or the removed ones (before). + fn changed<'a>(&'a self, pn: &'a [Pending], after: bool) -> Vec<&'a Seg> { + let mut v = vec![]; + for p in pn { + if after { + v.extend(p.added.iter().map(|&j| &p.segs[j])); + } else { + v.extend(self.segs[p.net].iter().zip(&p.removed).filter(|(_, &r)| r).map(|(e, _)| e)); + } + } + v + } + + /// Unchanged lines of the nets the move touched. + fn kept<'a>(&'a self, p: &'a Pending) -> impl Iterator { + self.segs[p.net].iter().zip(&p.removed).filter(|(_, &r)| !r).map(|(e, _)| e) + } + + /// Crossings of the changed lines with the unchanged ones and with each other. + fn cross_changed(&self, pn: &[Pending], after: bool) -> f64 { + let ch = self.changed(pn, after); + let mut x = 0.0; + for (a, e) in ch.iter().enumerate() { + for k in 0..self.m.nets.len() { + if self.nstamp[k] != self.cur && self.nbb[k].hits(&e.bb) { + x += self.segs[k].iter().map(|f| cross_w(e, f)).sum::(); + } + } + for p in pn.iter().filter(|p| p.net != e.net) { + x += self.kept(p).map(|f| cross_w(e, f)).sum::(); + } + x += ch[a + 1..].iter().filter(|f| f.net != e.net).map(|f| cross_w(e, f)).sum::(); + } + x + } + + /// Blocks of the changed lines over all parts, and of the unchanged lines over the moved + /// parts, at the current poses. + fn block_changed(&self, pn: &[Pending], after: bool, region: &Rect, all: &[usize]) -> f64 { + let mut b: f64 = self.changed(pn, after).iter().map(|e| self.block_parts(e, all)).sum(); + for k in 0..self.m.nets.len() { + if self.nstamp[k] != self.cur && self.nbb[k].hits(region) { + for e in self.segs[k].iter().filter(|e| e.bb.hits(region)) { + b += self.block_parts(e, &self.moved); + } + } + } + for p in pn { + for e in self.kept(p).filter(|e| e.bb.hits(region)) { + b += self.block_parts(e, &self.moved); + } + } + b + } + + /// (bounds, pull) cost of a part. + fn unary_eval(&self, i: usize) -> (f64, f64) { + let m = self.m; + let p = &m.parts[i]; + if p.fixed { + return (0.0, 0.0); + } + // the side of the part's group region, else of the board + let b = p.groups.iter().find_map(|&g| m.groups[g].bbox).unwrap_or(m.bounds); + let mut pull = 0.0; + for &(k, dir, wt) in &p.pulls { + let q = self.pp[k]; + // distance to the side the outward vector points at + let d = match dir { + (x, _) if x > 0.5 => b.x1 - q.0, + (x, _) if x < -0.5 => q.0 - b.x0, + (_, y) if y > 0.5 => b.y1 - q.1, + _ => q.1 - b.y0, + }; + pull += m.w.pull * wt * d.max(0.0); + } + let mut s = 0.0; + let inner = m.bounds.grow(-m.w.edge); + // area outside, plus the distance so that a part far outside is pulled back + let out = |r: &Rect, b: &Rect| { + r.outside(b) + (b.x0 - r.x0).max(r.x1 - b.x1).max(0.0) + (b.y0 - r.y0).max(r.y1 - b.y1).max(0.0) + }; + for r in &p.court { + let r = r.place(self.at[i], self.rot[i]); + s += out(&r, &m.bounds); + for k in &m.keepouts { + s += r.inter(k); + } + for &g in &p.groups { + if let Some(b) = m.groups[g].bbox { + s += out(&r, &b); + } + } + } + for &k in &p.pads { + let r = self.pad_rect(k); + s += r.outside(&inner); + for z in &m.pad_keepouts { + s += r.inter(z); + } + } + (self.pen * m.w.overlap * s, pull) + } + + /// Move parts to new anchors/rotations; returns the cost delta. Follow with accept() or reject(). + pub fn propose(&mut self, moves: &[(usize, Pt, u8)]) -> f64 { + let m = self.m; + self.cur += 1; + let cur = self.cur; + self.moved.clear(); + self.old.clear(); + self.new.clear(); + // followers go where their master goes + let mut mv: Vec<(usize, Pt, u8)> = moves.iter().copied().filter(|&(i, _, _)| m.parts[i].follow.is_none()).collect(); + for k in 0..mv.len() { + let (i, at, r) = mv[k]; + for &f in &m.parts[i].followers { + let off = m.parts[f].follow.unwrap().1; + mv.push((f, (at.0 + off.0, at.1 + off.1), r)); + } + } + for &(i, at, r) in &mv { + self.moved.push(i); + self.old.push((self.at[i], self.rot[i])); + self.new.push((at, r & 3)); + self.set_pose(i, at, r & 3); + self.pstamp[i] = cur; + } + let mut delta = 0.0; + // nets: new lines, and which lines changed + let mut pn = std::mem::take(&mut self.p_net); + pn.clear(); + for mi in 0..self.moved.len() { + for &n in &m.parts[self.moved[mi]].nets { + if self.nstamp[n] == cur { + continue; + } + self.nstamp[n] = cur; + let (t, segs) = self.net_eval(n); + delta += t.sum() - self.net_cost[n]; + let old = &self.segs[n]; + let mut removed = vec![false; old.len()]; + let mut matched = vec![false; segs.len()]; + for (i, e) in old.iter().enumerate() { + match (0..segs.len()).find(|&j| !matched[j] && same(e, &segs[j])) { + Some(j) => matched[j] = true, + None => removed[i] = true, + } + } + let added = (0..segs.len()).filter(|&j| !matched[j]).collect(); + pn.push(Pending { net: n, cost: t.sum(), bb: segs_bb(&segs), segs, removed, added }); + } + } + delta += m.w.crossing * (self.cross_changed(&pn, true) - self.cross_changed(&pn, false)); + // blocks: after the move, then at the old poses + let n = m.parts.len(); + let all: Vec = (0..n).collect(); + let mut region = NONE; + for (k, &i) in self.moved.iter().enumerate() { + region = region.union(&self.hull_w[i]).union(&m.parts[i].hull.place(self.old[k].0, self.old[k].1)); + } + let b_after = self.block_changed(&pn, true, ®ion, &all); + for k in 0..self.moved.len() { + let (a, r) = self.old[k]; + self.set_pose(self.moved[k], a, r); + } + let b_before = self.block_changed(&pn, false, ®ion, &all); + for k in 0..self.moved.len() { + let (a, r) = self.new[k]; + self.set_pose(self.moved[k], a, r); + } + delta += m.w.block * (b_after - b_before); + self.p_net = pn; + // pairs and part terms + self.p_pair.clear(); + self.p_un.clear(); + for mi in 0..self.moved.len() { + let s = self.moved[mi]; + for j in 0..n { + if j == s || (self.pstamp[j] == cur && j < s) { + continue; + } + let (lo, hi) = if s < j { (s, j) } else { (j, s) }; + let (ov, band, link) = self.pair_eval(lo, hi); + let v = ov + band + link; + let key = lo * n + hi; + if v != self.pair[key] { + delta += v - self.pair[key]; + self.p_pair.push((key, v)); + } + } + let (bounds, pull) = self.unary_eval(s); + let u = bounds + pull; + delta += u - self.unary[s]; + self.p_un.push((s, u)); + } + self.p_delta = delta; + delta + } + + pub fn accept(&mut self) { + for p in self.p_net.drain(..) { + self.net_cost[p.net] = p.cost; + self.segs[p.net] = p.segs; + self.nbb[p.net] = p.bb; + } + for &(k, v) in &self.p_pair { + self.pair[k] = v; + } + for &(i, v) in &self.p_un { + self.unary[i] = v; + } + self.total += self.p_delta; + } + + pub fn reject(&mut self) { + for k in (0..self.moved.len()).rev() { + let i = self.moved[k]; + (self.at[i], self.rot[i]) = self.old[k]; + self.place_pads(i); + } + } + + /// Ratsnest lines of all nets (MST plus each decap's line to its pin): (a, b, net). + pub fn lines(&self) -> Vec<(Pt, Pt, usize)> { + self.segs.iter().flatten().map(|e| (e.a, e.b, e.net)).collect() + } + + pub fn hull(&self, i: usize) -> Rect { + self.hull_w[i] + } + + pub fn pad_pos(&self, k: usize) -> Pt { + self.pp[k] + } + + /// Readable findings for calibration: (category, text, cost), worst first. + pub fn findings(&self) -> Vec<(String, String, f64)> { + let m = self.m; + let mut out = vec![]; + let name = |k: usize| format!("{}.{}", m.parts[m.pads[k].part].reference, m.pads[k].num); + let short = |n: &str| n.rsplit('/').next().unwrap_or(n).to_string(); + for (ni, net) in m.nets.iter().enumerate() { + let (t, _) = self.net_eval(ni); + if t.escape > 0.5 { + out.push(("escape".into(), short(&net.name), t.escape)); + } + for &d in &net.decaps { + let dc = &m.decaps[d]; + let s = self.pp[dc.sig]; + let (c, ds) = dc + .cands + .iter() + .map(|(c, _)| (*c, dist(s, self.pp[*c]))) + .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap()) + .unwrap(); + let lim = if dc.bulk { 8.0 } else { 3.0 }; + if ds > lim * 0.8 { + out.push(("decap".into(), format!("{} -> {} {:.2} mm", m.parts[dc.part].reference, name(c), ds), ds)); + } + } + for &q in &net.cover { + let near = net + .decaps + .iter() + .map(|&d| dist(self.pp[m.decaps[d].sig], self.pp[q])) + .fold(f64::MAX, f64::min); + if near > 3.0 { + out.push(("cover".into(), format!("{} nearest cap {:.2} mm", name(q), near), m.w.cover * (near - 3.0))); + } + } + } + let n = m.parts.len(); + for i in 0..n { + for j in i + 1..n { + let (ov, band, link) = self.pair_eval(i, j); + if link > 1e-9 { + out.push(("link".into(), format!("{} / {}", m.parts[i].reference, m.parts[j].reference), link)); + } + if ov > 1e-9 { + out.push(("overlap".into(), format!("{} / {}", m.parts[i].reference, m.parts[j].reference), ov)); + } + if band > 1e-9 { + out.push(("band".into(), format!("{} / {}", m.parts[i].reference, m.parts[j].reference), band)); + } + } + for k in 0..m.nets.len() { + let b = m.w.block * self.segs[k].iter().map(|e| self.block_parts(e, &[i])).sum::(); + if b > 1e-9 { + out.push(("block".into(), format!("{} over {}", short(&m.nets[k].name), m.parts[i].reference), b)); + } + } + let (u, pull) = self.unary_eval(i); + if u > 1e-9 { + out.push(("bounds".into(), m.parts[i].reference.clone(), u)); + } + if pull > 1e-9 { + out.push(("pull".into(), m.parts[i].reference.clone(), pull)); + } + } + out.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap()); + out + } +} diff --git a/tools/placer/src/geom.rs b/tools/placer/src/geom.rs new file mode 100644 index 0000000..3514340 --- /dev/null +++ b/tools/placer/src/geom.rs @@ -0,0 +1,174 @@ +//! Axis-aligned rectangles, 90 degree turns, segment crossings and the MST. + +pub type Pt = (f64, f64); + +#[derive(Clone, Copy, Debug, Default)] +pub struct Rect { + pub x0: f64, + pub y0: f64, + pub x1: f64, + pub y1: f64, +} + +impl Rect { + pub fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Rect { + Rect { x0: x0.min(x1), y0: y0.min(y1), x1: x0.max(x1), y1: y0.max(y1) } + } + pub fn around(c: Pt, hw: f64, hh: f64) -> Rect { + Rect::new(c.0 - hw, c.1 - hh, c.0 + hw, c.1 + hh) + } + pub fn area(&self) -> f64 { + (self.x1 - self.x0) * (self.y1 - self.y0) + } + /// Overlap area with `o`. + pub fn inter(&self, o: &Rect) -> f64 { + let w = self.x1.min(o.x1) - self.x0.max(o.x0); + let h = self.y1.min(o.y1) - self.y0.max(o.y0); + if w > 0.0 && h > 0.0 { + w * h + } else { + 0.0 + } + } + pub fn hits(&self, o: &Rect) -> bool { + self.x0 < o.x1 && o.x0 < self.x1 && self.y0 < o.y1 && o.y0 < self.y1 + } + /// Area of `self` that lies outside `b`. + pub fn outside(&self, b: &Rect) -> f64 { + self.area() - self.inter(b) + } + pub fn grow(&self, d: f64) -> Rect { + Rect { x0: self.x0 - d, y0: self.y0 - d, x1: self.x1 + d, y1: self.y1 + d } + } + pub fn union(&self, o: &Rect) -> Rect { + Rect { x0: self.x0.min(o.x0), y0: self.y0.min(o.y0), x1: self.x1.max(o.x1), y1: self.y1.max(o.y1) } + } + /// The rectangle of a footprint-local rectangle on a part at `at`, turned by `k` x 90 degrees. + pub fn place(&self, at: Pt, k: u8) -> Rect { + let a = turn((self.x0, self.y0), k); + let b = turn((self.x1, self.y1), k); + Rect::new(a.0 + at.0, a.1 + at.1, b.0 + at.0, b.1 + at.1) + } +} + +/// Turn a footprint-local vector by k x 90 degrees as KiCad does: positive angles turn +/// counter-clockwise on screen, where y points down. +pub fn turn(p: Pt, k: u8) -> Pt { + match k & 3 { + 0 => p, + 1 => (p.1, -p.0), + 2 => (-p.0, -p.1), + _ => (-p.1, p.0), + } +} + +pub fn dist(a: Pt, b: Pt) -> f64 { + ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() +} + +/// Proper crossing of segments ab and cd; touching or shared ends do not count. +pub fn crosses(a: Pt, b: Pt, c: Pt, d: Pt) -> bool { + fn orient(p: Pt, q: Pt, r: Pt) -> f64 { + (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0) + } + let (o1, o2) = (orient(a, b, c), orient(a, b, d)); + if o1 * o2 >= 0.0 { + return false; + } + let (o3, o4) = (orient(c, d, a), orient(c, d, b)); + o3 * o4 < 0.0 +} + +/// Segment ab passes through rectangle r (Liang-Barsky clipping). +pub fn seg_hits(a: Pt, b: Pt, r: &Rect) -> bool { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let (mut t0, mut t1) = (0.0f64, 1.0f64); + for (p, q) in [(-dx, a.0 - r.x0), (dx, r.x1 - a.0), (-dy, a.1 - r.y0), (dy, r.y1 - a.1)] { + if p.abs() < 1e-12 { + if q < 0.0 { + return false; + } + } else { + let t = q / p; + if p < 0.0 { + t0 = t0.max(t); + } else { + t1 = t1.min(t); + } + if t0 > t1 { + return false; + } + } + } + true +} + +/// Prim's MST over the points: (i, j) pairs. +pub fn mst(pts: &[Pt]) -> Vec<(usize, usize)> { + let n = pts.len(); + let mut out = Vec::with_capacity(n.saturating_sub(1)); + if n < 2 { + return out; + } + let mut inside = vec![false; n]; + let mut best = vec![f64::INFINITY; n]; + let mut link = vec![usize::MAX; n]; + best[0] = 0.0; + for _ in 0..n { + let mut i = usize::MAX; + for k in 0..n { + if !inside[k] && (i == usize::MAX || best[k] < best[i]) { + i = k; + } + } + inside[i] = true; + if link[i] != usize::MAX { + out.push((link[i], i)); + } + for k in 0..n { + if !inside[k] { + let d = dist(pts[i], pts[k]); + if d < best[k] { + best[k] = d; + link[k] = i; + } + } + } + } + out +} + +/// Cover a polygon with rectangles: one horizontal slab per pair of vertex heights, each +/// cut into the x intervals that lie inside. Exact for rectilinear outlines, a slight +/// overestimate for slanted edges and arcs (each slab takes the wider of its two ends). +pub fn poly_rects(poly: &[[f64; 2]]) -> Vec { + let mut ys: Vec = poly.iter().map(|p| p[1]).collect(); + ys.sort_by(|a, b| a.partial_cmp(b).unwrap()); + ys.dedup_by(|a, b| (*a - *b).abs() < 1e-4); + let xs_at = |y: f64| { + let mut xs = Vec::new(); + for i in 0..poly.len() { + let (a, b) = (poly[i], poly[(i + 1) % poly.len()]); + if (a[1] <= y && b[1] > y) || (b[1] <= y && a[1] > y) { + xs.push(a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0])); + } + } + xs.sort_by(|a, b| a.partial_cmp(b).unwrap()); + xs + }; + let mut out = Vec::new(); + for w in ys.windows(2) { + let (y0, y1) = (w[0], w[1]); + let eps = (y1 - y0) * 1e-3; + let (lo, hi) = (xs_at(y0 + eps), xs_at(y1 - eps)); + if lo.len() != hi.len() { + continue; + } + for k in (0..lo.len()).step_by(2) { + if k + 1 < lo.len() { + out.push(Rect::new(lo[k].min(hi[k]), y0, lo[k + 1].max(hi[k + 1]), y1)); + } + } + } + out +} diff --git a/tools/placer/src/main.rs b/tools/placer/src/main.rs new file mode 100644 index 0000000..c94f865 --- /dev/null +++ b/tools/placer/src/main.rs @@ -0,0 +1,279 @@ +//! placer: simulated-annealing component placement for KiCad boards. +//! +//! placer score PROBLEM CONFIG [PLACEMENT.json] cost terms and findings of a placement +//! placer selftest PROBLEM CONFIG incremental cost == full evaluation +//! placer congest PROBLEM CONFIG [--cell MM] PLACEMENT... routing-channel measures (RUDY, +//! global route) per placement, one line each +//! placer run PROBLEM CONFIG OUT_DIR [--runs N] [--start scramble|keep] [--seed S] +//! [--inner X] [--t0 X] [--top K] [--route BOARD.json ROUTE.toml [--route-top K]] +//! placer route PROBLEM CONFIG BOARD.json ROUTE.toml OUT_DIR PLACEMENT... +//! route placements, rank them by the result +//! +//! PROBLEM comes from export.py, CONFIG is the board's placement.toml. `run` anneals N +//! independent runs in parallel and writes the best K as OUT_DIR/rank_NN.json plus +//! OUT_DIR/runs.tsv. A placement file maps ref -> [x, y, rotation in degrees], either at the +//! top level or under "placement". +//! +//! `--route` routes the best K placements in-process with tools/router-rs (BOARD.json is any +//! dump of the board from tools/router/dump_board.py; parts are moved to each placement) and +//! ranks them by the router's result (split nets, failed connections, pour islands, then the +//! route.toml's [rank] score of length, vias, necked and B.Cu length): OUT_DIR/routed.tsv, +//! routes_NN.json for tools/router/write_board.py, routed_best.json (the placement). + +mod anneal; +mod congest; +mod cost; +mod geom; +mod model; + +use anneal::{anneal, selftest, Opts, Start}; +use anyhow::{bail, Context, Result}; +use cost::State; +use model::Model; +use rayon::prelude::*; +use std::collections::BTreeMap; +use std::time::Instant; + +fn placement_json(m: &Model, s: &State) -> BTreeMap { + m.parts + .iter() + .enumerate() + .map(|(i, p)| { + let r = s.rot[i] as f64 * 90.0; + (p.reference.clone(), [(s.at[i].0 * 1e4).round() / 1e4, (s.at[i].1 * 1e4).round() / 1e4, r]) + }) + .collect() +} + +fn load_placement<'m>(m: &'m Model, path: &str) -> Result> { + let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(path).with_context(|| path.to_string())?)?; + let map = v.get("placement").unwrap_or(&v).as_object().context("placement must be an object")?; + let mut at: Vec<_> = m.parts.iter().map(|p| p.at0).collect(); + let mut rot: Vec<_> = m.parts.iter().map(|p| p.rot0).collect(); + for (r, xyr) in map { + let Some(i) = m.part(r) else { bail!("{path}: no part {r}") }; + let a: Vec = serde_json::from_value(xyr.clone())?; + at[i] = (a[0], a[1]); + rot[i] = (((a[2] / 90.0).round() as i64).rem_euclid(4)) as u8; + } + Ok(State::new(m, at, rot)) +} + +/// No courtyard overlap, nothing off the board, in a keep-out or outside its group bbox. +fn legal(s: &mut State) -> bool { + let t = s.recompute(); + t.overlap < 1e-6 && t.bounds < 1e-6 +} + +/// Route placements (name, placement, legal) on a board in parallel; write routes_NAME.json, +/// routed.tsv (legal placements first, then best routed first) and routed_best.json into `out`. +fn route_all(board: &str, toml: &str, out: &str, cands: Vec<(String, BTreeMap, bool)>) -> Result<()> { + let cfg = router::config::Config::load(toml)?; + let base = std::path::Path::new(toml).parent().unwrap_or(std::path::Path::new(".")); + let t0 = Instant::now(); + let mut rows: Vec<(String, router::run::Summary, bool)> = cands + .par_iter() + .map(|(name, p, ok)| -> Result<(String, router::run::Summary, bool)> { + let mut b = router::io::BoardJson::load(board)?; + router::placement::apply(&mut b, p)?; + let (run, sum) = router::run::route(&b, &cfg, base, &Default::default())?; + std::fs::write(format!("{out}/routes_{name}.json"), serde_json::to_string(&run.r.result())?)?; + Ok((name.clone(), sum, *ok)) + }) + .collect::>()?; + rows.sort_by_key(|r| (!r.2, r.1.key())); + let secs = t0.elapsed().as_secs_f64(); + let mut tsv = String::from("placement\tlegal\tsplit\tfailed\tislands\tvias\tlength_mm\tneck_mm\tbcu_mm\tscore\tsecs\n"); + for (n, s, ok) in &rows { + tsv += &format!("{n}\t{}\t{}\t{}\t{}\t{}\t{:.1}\t{:.1}\t{:.1}\t{:.1}\t{:.1}\n", *ok as u8, s.split, s.failed, s.islands, s.vias, s.length, s.neck, s.bcu, s.score, s.secs); + } + std::fs::write(format!("{out}/routed.tsv"), &tsv)?; + let complete = rows.iter().filter(|r| r.2 && r.1.split == 0 && r.1.failed == 0 && r.1.islands == 0).count(); + println!("routed {} placements in {secs:.1} s: {complete} legal and complete; best first:", rows.len()); + for (n, s, _) in rows.iter().take(5) { + println!( + " {n}: split {} failed {} islands {} vias {} length {:.0} mm neck {:.1} mm score {:.0} ({:.1} s)", + s.split, s.failed, s.islands, s.vias, s.length, s.neck, s.score, s.secs + ); + } + if let Some((best, _, _)) = rows.first() { + let p = &cands.iter().find(|c| &c.0 == best).unwrap().1; + std::fs::write(format!("{out}/routed_best.json"), serde_json::to_string_pretty(&serde_json::json!({"from": best, "placement": p}))?)?; + } + Ok(()) +} + +fn print_terms(t: &cost::Terms) { + println!( + "total {:.1} = length {:.1} + escape {:.1} + decap {:.1} + cover {:.1} + crossing {:.1} + overlap {:.1} + band {:.1} + bounds {:.1} + block {:.1} + link {:.1} + pull {:.1}", + t.total(), + t.length, + t.escape, + t.decap, + t.cover, + t.crossing, + t.overlap, + t.band, + t.bounds, + t.block, + t.link, + t.pull + ); + println!("crossings {}, ratsnest {:.1} mm", t.crossings, t.ratsnest_mm); +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: placer score PROBLEM CONFIG [PLACEMENT]\n placer run PROBLEM CONFIG OUT_DIR [--runs N] [--start scramble|keep] [--seed S] [--inner X] [--t0 X] [--top K] [--route BOARD.json ROUTE.toml [--route-top K]]\n placer route PROBLEM CONFIG BOARD.json ROUTE.toml OUT_DIR PLACEMENT..."; + if args.len() < 4 { + bail!("{usage}"); + } + let m = Model::load(&args[2], &args[3])?; + match args[1].as_str() { + "score" => { + let mut s = match args.get(4) { + Some(p) => load_placement(&m, p)?, + None => State::initial(&m), + }; + let t = s.recompute(); + println!( + "{} parts ({} movable), {} nets, {} decaps, {} groups", + m.parts.len(), + m.movable.len(), + m.nets.len(), + m.decaps.len(), + m.groups.len() + ); + let gs: Vec = m.groups.iter().map(|g| format!("{} ({})", g.name, g.parts.len())).collect(); + println!("groups: {}", gs.join(", ")); + print_terms(&t); + for (cat, what, c) in s.findings().iter().take(40) { + println!(" {cat:8} {what:40} {c:8.2}"); + } + } + "run" => { + let out = args.get(4).context(usage)?; + let mut o = Opts { start: Start::Scramble, inner: 10.0, seed: 1, t0: 20.0, grid: 0.05 }; + let (mut runs, mut top) = (8usize, 10usize); + let (mut route, mut route_top) = (None, None); + let mut k = 5; + while k < args.len() { + let v = args.get(k + 1).context(usage)?; + match args[k].as_str() { + "--route" => { + route = Some((v.clone(), args.get(k + 2).context(usage)?.clone())); + k += 1; + } + "--route-top" => route_top = Some(v.parse::()?), + "--runs" => runs = v.parse()?, + "--start" => o.start = if v == "keep" { Start::Keep } else { Start::Scramble }, + "--seed" => o.seed = v.parse()?, + "--inner" => o.inner = v.parse()?, + "--t0" => o.t0 = v.parse()?, + "--top" => top = v.parse()?, + a => bail!("unknown option {a}\n{usage}"), + } + k += 2; + } + std::fs::create_dir_all(out)?; + let t0 = Instant::now(); + let res: Vec<_> = (0..runs) + .into_par_iter() + .map(|r| anneal(&m, &Opts { seed: o.seed + r as u64, ..o.clone() })) + .collect(); + let secs = t0.elapsed().as_secs_f64(); + // legal placements first (no courtyard overlap, nothing off the board or in a keep-out) + let legal: Vec = res.iter().map(|r| legal(&mut State::new(&m, r.at.clone(), r.rot.clone()))).collect(); + let mut idx: Vec = (0..res.len()).collect(); + idx.sort_by(|&a, &b| legal[b].cmp(&legal[a]).then(res[a].cost.partial_cmp(&res[b].cost).unwrap())); + let legal: Vec = idx.iter().map(|&i| legal[i]).collect(); + let res: Vec<_> = idx.into_iter().map(|i| &res[i]).collect(); + let moves: u64 = res.iter().map(|r| r.moves).sum(); + println!( + "{runs} runs in {secs:.1} s ({:.0} k moves/s total, {:.2} s per run per core)", + moves as f64 / secs / 1e3, + secs * rayon::current_num_threads() as f64 / runs as f64 + ); + let mut cands = Vec::new(); + let mut tsv = String::from("rank\tseed\tcost\tcrossings\tratsnest_mm\toverlap\tband\tbounds\ttemps\tmoves\n"); + for (rank, r) in res.iter().enumerate() { + let mut s = State::new(&m, r.at.clone(), r.rot.clone()); + let t = s.recompute(); + tsv += &format!( + "{rank}\t{}\t{:.2}\t{}\t{:.1}\t{:.2}\t{:.2}\t{:.2}\t{}\t{}\n", + r.seed, r.cost, t.crossings, t.ratsnest_mm, t.overlap, t.band, t.bounds, r.temps, r.moves + ); + if rank < route_top.unwrap_or(top) { + cands.push((format!("{rank:02}"), placement_json(&m, &s), legal[rank])); + } + if rank < top { + let j = serde_json::json!({"seed": r.seed, "cost": r.cost, "terms": t, "placement": placement_json(&m, &s)}); + std::fs::write(format!("{out}/rank_{rank:02}.json"), serde_json::to_string_pretty(&j)?)?; + } + if rank < 5 { + print!("#{rank} seed {} ", r.seed); + print_terms(&t); + } + } + std::fs::write(format!("{out}/runs.tsv"), tsv)?; + if let Some((board, toml)) = route { + route_all(&board, &toml, out, cands)?; + } + } + "route" => { + let (board, toml, out) = (args.get(4).context(usage)?, args.get(5).context(usage)?, args.get(6).context(usage)?); + std::fs::create_dir_all(out)?; + let mut cands = Vec::new(); + for f in &args[7..] { + let mut s = load_placement(&m, f)?; + let name = std::path::Path::new(f).file_stem().unwrap().to_string_lossy().into_owned(); + let ok = legal(&mut s); + cands.push((name, placement_json(&m, &s), ok)); + } + route_all(board, toml, out, cands)?; + } + "congest" => { + let mut cell = 0.5; + let mut files = vec![]; + let mut k = 4; + while k < args.len() { + if args[k] == "--cell" { + cell = args.get(k + 1).context(usage)?.parse()?; + k += 2; + } else { + files.push(args[k].clone()); + k += 1; + } + } + println!("file\tcost\tcrossings\trudy\tgr_overflow\tgr_cells\tgr_length\tgr_vias\tgr_rounds\tms"); + let rows: Vec = files + .par_iter() + .map(|f| { + let t0 = Instant::now(); + let mut s = load_placement(&m, f).unwrap(); + let t = s.recompute(); + let g = congest::Grid::new(&m, &s, cell); + let r = congest::rudy(&m, &s, &g); + let gr = congest::groute(&m, &s, &g, &congest::GOpts::default()); + format!( + "{}\t{:.1}\t{}\t{:.1}\t{:.1}\t{}\t{:.0}\t{}\t{}\t{:.0}", + f, t.total(), t.crossings, r, gr.overflow, gr.over_cells, gr.length, gr.vias, gr.rounds, + t0.elapsed().as_secs_f64() * 1e3 + ) + }) + .collect(); + for r in rows { + println!("{r}"); + } + } + "selftest" => { + let drift = selftest(&m, 20000, 7); + println!("largest relative drift of the incremental total: {drift:.2e}"); + if drift > 1e-6 { + bail!("incremental cost drifts from the full evaluation"); + } + } + _ => bail!("{usage}"), + } + Ok(()) +} diff --git a/tools/placer/src/model.rs b/tools/placer/src/model.rs new file mode 100644 index 0000000..c8e978b --- /dev/null +++ b/tools/placer/src/model.rs @@ -0,0 +1,700 @@ +//! The placement problem: parts, pads, nets from export.py's JSON, plus the sidecar config +//! (placement.toml) and what can be inferred from the netlist (decoupling caps, pin normals, +//! fine-pitch fan-out bands, fixed parts). +//! +//! Labels beyond the netlist: `[[link]]` keeps two pads within a distance (a net tie on a +//! Kelvin pad), `[[pull]]` draws the pads of interface nets towards a board side (where the +//! host connects), `[[replicate]]` makes repeated channels copies of the first one at a fixed +//! pitch (followers move with their master and are never moved on their own). + +use crate::geom::{poly_rects, Pt, Rect}; +use anyhow::{bail, Context, Result}; +use serde::Deserialize; +use std::collections::HashMap; + +// ---------- export.py JSON ---------- + +#[derive(Deserialize)] +struct JPad { + num: String, + net: String, + x: f64, + y: f64, + w: f64, + h: f64, + tht: bool, +} + +#[derive(Deserialize)] +struct JPart { + #[serde(rename = "ref")] + reference: String, + value: String, + fpid: String, + x: f64, + y: f64, + rot: f64, + locked: bool, + board_only: bool, + fields: HashMap, + court: Vec>, + pads: Vec, +} + +#[derive(Deserialize)] +struct JKeepout { + poly: Vec<[f64; 2]>, + footprints: bool, + pads: bool, + #[serde(default)] + tracks: bool, +} + +#[derive(Deserialize)] +struct JClass { + track: f64, + clearance: f64, +} + +#[derive(Deserialize)] +struct JProblem { + bounds: [f64; 4], + parts: Vec, + netclass: HashMap, + #[serde(default)] + classes: HashMap, + fill: Vec, + keepouts: Vec, +} + +// ---------- placement.toml ---------- + +/// Cost weights. Lengths are in mm, areas in mm^2. +#[derive(Deserialize, Clone, Debug)] +#[serde(default, deny_unknown_fields)] +pub struct Weights { + /// per mm of ratsnest (MST) length, times the net weight + pub length: f64, + /// per crossing of two ratsnest lines, times the mean weight of both nets + pub crossing: f64, + /// per line that leaves a pin backwards, times the detour (part size); not scaled by net weight + pub escape: f64, + /// per ratsnest line over another net's pad, times the net weight + pub block: f64, + /// per mm from a decoupling cap to its pin (ground pad counts half) + pub decap: f64, + /// beyond the decap limit (3 mm, 8 mm for bulk caps): per mm^2 for the first 2 mm, then 4 per mm + pub decap_limit: f64, + /// per mm that a decoupled IC pin is farther than 3 mm from its nearest cap + pub cover: f64, + /// per mm^2 of courtyard overlap, outside the board, in a keep-out or outside a group bbox + pub overlap: f64, + /// per mm^2 of another part's pad in a fine-pitch IC's fan-out band + pub band: f64, + /// fan-out band width in front of fine-pitch pin rows (mm) + pub fanout: f64, + /// copper-to-edge clearance for pads (mm) + pub edge: f64, + /// [[link]] past its distance: per mm^2 for the first 2 mm, then 4 per mm (times its weight) + pub link: f64, + /// [[pull]]: per mm from a pad to its side of the part's group bbox, else of the board + /// (times its weight) + pub pull: f64, +} + +impl Default for Weights { + fn default() -> Self { + Weights { + length: 1.0, + crossing: 4.0, + escape: 3.0, + block: 3.0, + decap: 3.0, + decap_limit: 20.0, + cover: 4.0, + overlap: 100.0, + band: 40.0, + fanout: 1.0, + edge: 0.5, + link: 20.0, + pull: 1.0, + } + } +} + +#[derive(Deserialize, Default)] +#[serde(deny_unknown_fields)] +struct CNet { + #[serde(rename = "match")] + pattern: String, + weight: f64, +} + +#[derive(Deserialize, Default)] +#[serde(deny_unknown_fields)] +struct CGroup { + name: String, + #[serde(default)] + parts: Vec, + bbox: Option<[f64; 4]>, +} + +#[derive(Deserialize, Default)] +#[serde(deny_unknown_fields)] +struct CAttach { + part: String, + /// "U2.21" + pin: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CLink { + /// "NT1.2" + a: String, + b: String, + /// pad centre distance (mm) allowed without cost + max: f64, + #[serde(default = "one")] + weight: f64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CPull { + /// net name globs + nets: Vec, + /// "N", "S", "E" or "W" + side: String, + #[serde(default = "one")] + weight: f64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CReplicate { + /// channels, each a list of parts; channel k's part i follows channel 0's part i + parts: Vec>, + /// offset (mm) from one channel to the next, in board axes + pitch: [f64; 2], +} + +fn one() -> f64 { + 1.0 +} + +#[derive(Deserialize, Default)] +#[serde(default, deny_unknown_fields)] +struct Config { + fixed: Vec, + /// net-class name -> weight; classes not listed weigh 1 + class: HashMap, + net: Vec, + group: Vec, + attach: Vec, + link: Vec, + pull: Vec, + replicate: Vec, + weights: Weights, +} + +// ---------- model ---------- + +pub struct Pad { + pub part: usize, + pub num: String, + /// None for unconnected pads and fill nets + pub net: Option, + pub fill: bool, + pub local: Pt, + pub half: Pt, + /// outward direction a track leaves the pin in, footprint-local + pub normal: Option, + /// through-hole (blocks both layers) + pub tht: bool, +} + +pub struct Part { + pub reference: String, + pub fpid: String, + pub fixed: bool, + pub at0: Pt, + pub rot0: u8, + pub pads: Vec, + pub court: Vec, + /// bounding box of the courtyard (local) + pub hull: Rect, + /// fine-pitch ICs: pad envelope grown by the fan-out width (local) + pub band: Option, + /// detour length when a line leaves a pin backwards + pub detour: f64, + /// non-fill nets on this part + pub nets: Vec, + /// all groups this part belongs to, innermost first + pub groups: Vec, + /// links this part has a pad in + pub links: Vec, + /// [[pull]] pads: (pad, outward unit vector of the side, weight) + pub pulls: Vec<(usize, Pt, f64)>, + /// replicated channel: (master part, offset from it); moves only with the master + pub follow: Option<(usize, Pt)>, + /// parts that follow this one + pub followers: Vec, +} + +pub struct Link { + pub a: usize, + pub b: usize, + pub max: f64, + pub weight: f64, +} + +pub struct Decap { + pub part: usize, + pub sig: usize, + pub gnd: usize, + pub bulk: bool, + /// candidate pins (pad) with the ground pins of the same part + pub cands: Vec<(usize, Vec)>, +} + +pub struct Net { + pub name: String, + pub pads: Vec, + pub weight: f64, + /// track width + clearance of the net's class (mm): the room one track takes + pub pitch: f64, + pub decaps: Vec, + /// IC pins that need a cap within 3 mm + pub cover: Vec, +} + +pub struct Group { + pub name: String, + pub bbox: Option, + /// movable members, including those of subgroups + pub parts: Vec, +} + +pub struct Model { + pub parts: Vec, + pub pads: Vec, + pub nets: Vec, + pub decaps: Vec, + pub groups: Vec, + pub links: Vec, + pub bounds: Rect, + /// rule areas no courtyard may enter + pub keepouts: Vec, + /// rule areas no pad may enter + pub pad_keepouts: Vec, + /// rule areas no track may enter + pub track_keepouts: Vec, + pub w: Weights, + pub movable: Vec, +} + +const COURT_MARGIN: f64 = 0.03; + +fn glob(pat: &str, s: &str) -> bool { + // '*' only + let parts: Vec<&str> = pat.split('*').collect(); + if parts.len() == 1 { + return pat == s; + } + let mut rest = s; + for (i, p) in parts.iter().enumerate() { + if i == 0 { + if !rest.starts_with(p) { + return false; + } + rest = &rest[p.len()..]; + } else if i == parts.len() - 1 { + return rest.ends_with(p); + } else if let Some(k) = rest.find(p) { + rest = &rest[k + p.len()..]; + } else { + return false; + } + } + true +} + +fn cap_uf(v: &str) -> f64 { + let v = v.trim(); + let k = v.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(v.len()); + let n: f64 = v[..k].parse().unwrap_or(0.0); + let f = match v[k..].chars().next() { + Some('p') => 1e-6, + Some('n') => 1e-3, + Some('u') | Some('ยต') => 1.0, + Some('m') => 1e3, + _ => 1.0, + }; + n * f +} + +fn is_ic(reference: &str, npads: usize) -> bool { + npads >= 4 && !reference.starts_with(['J', 'P']) && !reference.starts_with("TP") +} + +/// Outward direction of each pad: 2-pad parts along their axis, ICs and connectors from the +/// side of the pad envelope the pad sits on (pads elongated along it decide first); centre +/// pads (exposed pads, module ground pads) and THT pads have none. +fn normals(pads: &[JPad]) -> Vec> { + let smd: Vec<&JPad> = pads.iter().filter(|p| !p.tht).collect(); + if smd.len() == 2 && pads.len() == 2 { + let c = ((smd[0].x + smd[1].x) / 2.0, (smd[0].y + smd[1].y) / 2.0); + return pads + .iter() + .map(|p| { + let (dx, dy) = (p.x - c.0, p.y - c.1); + let l = (dx * dx + dy * dy).sqrt(); + (l > 1e-6).then(|| (dx / l, dy / l)) + }) + .collect(); + } + if smd.len() < 3 { + return pads.iter().map(|_| None).collect(); + } + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for p in &smd { + x0 = x0.min(p.x); + y0 = y0.min(p.y); + x1 = x1.max(p.x); + y1 = y1.max(p.y); + } + let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); + pads.iter() + .map(|p| { + if p.tht { + return None; + } + let d = [p.x - x0, x1 - p.x, p.y - y0, y1 - p.y]; + let m = d.iter().cloned().fold(f64::MAX, f64::min); + if m > 0.3 { + return None; // not on the perimeter + } + if p.w > 1.3 * p.h { + return Some((if p.x < cx { -1.0 } else { 1.0 }, 0.0)); + } + if p.h > 1.3 * p.w { + return Some((0.0, if p.y < cy { -1.0 } else { 1.0 })); + } + let dirs = [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0)]; + let (mut nx, mut ny) = (0.0, 0.0); + for (k, dir) in dirs.iter().enumerate() { + if d[k] < m + 0.2 { + nx += dir.0; + ny += dir.1; + } + } + let l = ((nx * nx + ny * ny) as f64).sqrt(); + (l > 1e-6).then(|| (nx / l, ny / l)) + }) + .collect() +} + +fn rot_steps(deg: f64) -> u8 { + (((deg / 90.0).round() as i64).rem_euclid(4)) as u8 +} + +impl Model { + pub fn load(problem: &str, config: &str) -> Result { + let jp: JProblem = serde_json::from_str(&std::fs::read_to_string(problem).with_context(|| problem.to_string())?)?; + let cfg: Config = toml::from_str(&std::fs::read_to_string(config).with_context(|| config.to_string())?) + .with_context(|| format!("parsing {config}"))?; + let w = cfg.weights.clone(); + let fillset: std::collections::HashSet<&str> = jp.fill.iter().map(|s| s.as_str()).collect(); + let is_fill = |n: &str| { + fillset.contains(n) || { + let base = n.rsplit('/').next().unwrap_or(n); + matches!(base, "GND" | "GNDA" | "GNDD" | "AGND" | "DGND" | "VSS" | "PGND") + } + }; + + // nets + let mut netid: HashMap = HashMap::new(); + let mut nets: Vec = Vec::new(); + let mut names: Vec<&String> = jp.netclass.keys().collect(); + names.sort(); + for n in names { + if is_fill(n) { + continue; + } + let cls = &jp.netclass[n]; + let mut weight = *cfg.class.get(cls).unwrap_or(&1.0); + for o in &cfg.net { + if glob(&o.pattern, n) { + weight = o.weight; + } + } + let pitch = jp.classes.get(cls).map(|c| c.track + c.clearance).unwrap_or(0.4); + netid.insert(n.clone(), nets.len()); + nets.push(Net { name: n.clone(), pads: vec![], weight, pitch, decaps: vec![], cover: vec![] }); + } + + // parts and pads + let mut parts = Vec::new(); + let mut pads = Vec::new(); + let fixed_cfg: std::collections::HashSet<&str> = cfg.fixed.iter().map(|s| s.as_str()).collect(); + for (pi, p) in jp.parts.iter().enumerate() { + // grown by a bit more than half the courtyard line: KiCad's DRC flags courtyards + // that touch, so parts must keep at least one grid step apart + let mut court: Vec = p.court.iter().flat_map(|poly| poly_rects(poly)).map(|r| r.grow(COURT_MARGIN)).collect(); + if court.is_empty() { + for q in &p.pads { + court.push(Rect::around((q.x, q.y), q.w / 2.0 + 0.25, q.h / 2.0 + 0.25)); + } + } + let hull = court.iter().skip(1).fold(court[0], |a, r| a.union(r)); + let field_fixed = p.fields.get("Place_Fixed").map(|v| !v.is_empty() && v != "0" && v != "no").unwrap_or(false); + let hole = p.fpid.contains("MountingHole") || p.fpid.contains("DIN_Post") || p.fpid.contains("DIN_Housing"); + let fixed = p.locked || p.board_only || hole || field_fixed || fixed_cfg.contains(p.reference.as_str()); + let ns = normals(&p.pads); + let mut ids = vec![]; + for (q, n) in p.pads.iter().zip(ns) { + let net = netid.get(&q.net).copied(); + if let Some(k) = net { + nets[k].pads.push(pads.len()); + } + ids.push(pads.len()); + pads.push(Pad { + part: pi, + num: q.num.clone(), + net, + fill: is_fill(&q.net), + local: (q.x, q.y), + half: (q.w / 2.0, q.h / 2.0), + normal: n, + tht: q.tht, + }); + } + // fine-pitch: >= 8 SMD pads with neighbours closer than 0.7 mm + let smd: Vec<&JPad> = p.pads.iter().filter(|q| !q.tht).collect(); + let pitch = smd + .iter() + .enumerate() + .flat_map(|(i, a)| smd[i + 1..].iter().map(move |b| ((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt())) + .fold(f64::MAX, f64::min); + let band = (smd.len() >= 8 && pitch < 0.7).then(|| { + smd.iter() + .map(|q| Rect::around((q.x, q.y), q.w / 2.0, q.h / 2.0)) + .reduce(|a, b| a.union(&b)) + .unwrap() + .grow(w.fanout) + }); + let mut pn: Vec = ids.iter().filter_map(|&k| pads[k].net).collect(); + pn.sort(); + pn.dedup(); + parts.push(Part { + reference: p.reference.clone(), + fpid: p.fpid.clone(), + fixed, + at0: (p.x, p.y), + rot0: rot_steps(p.rot), + pads: ids, + court, + hull, + band, + detour: ((hull.x1 - hull.x0) + (hull.y1 - hull.y0)) / 2.0, + nets: pn, + groups: vec![], + links: vec![], + pulls: vec![], + follow: None, + followers: vec![], + }); + } + let pref: HashMap = parts.iter().enumerate().map(|(i, p)| (p.reference.clone(), i)).collect(); + + // decoupling caps: C with one pad on a fill net, the other on a net with IC pins + let mut decaps = Vec::new(); + let xtal_nets: std::collections::HashSet = parts + .iter() + .filter(|p| p.reference.starts_with('Y')) + .flat_map(|p| p.nets.clone()) + .collect(); + let attach: HashMap<&str, &str> = cfg.attach.iter().map(|a| (a.part.as_str(), a.pin.as_str())).collect(); + for (pi, (p, jpart)) in parts.iter().zip(&jp.parts).enumerate() { + if !p.reference.starts_with('C') || p.pads.len() != 2 { + continue; + } + let (a, b) = (p.pads[0], p.pads[1]); + let (sig, gnd) = match (pads[a].fill, pads[b].fill) { + (false, true) => (a, b), + (true, false) => (b, a), + _ => continue, + }; + let Some(net) = pads[sig].net else { continue }; + let bulk = cap_uf(&jpart.value) >= 4.7; + let mut cands = vec![]; + if let Some(pin) = attach.get(p.reference.as_str()) { + let (r, num) = pin.split_once('.').context("attach pin must be REF.PIN")?; + let Some(&ic) = pref.get(r) else { bail!("attach {}: no part {r}", p.reference) }; + let Some(&k) = parts[ic].pads.iter().find(|&&k| pads[k].num == num) else { + bail!("attach {}: no pin {pin}", p.reference) + }; + cands.push(k); + } else { + for &k in &nets[net].pads { + let q = &parts[pads[k].part]; + let ok = is_ic(&q.reference, q.pads.len()) || (bulk && q.reference.starts_with(['L', 'F'])); + if pads[k].part != pi && ok { + cands.push(k); + } + } + } + if cands.is_empty() { + continue; + } + let cands = cands + .into_iter() + .map(|k| { + let g = parts[pads[k].part].pads.iter().copied().filter(|&j| pads[j].fill).collect(); + (k, g) + }) + .collect(); + nets[net].decaps.push(decaps.len()); + decaps.push(Decap { part: pi, sig, gnd, bulk, cands }); + } + // IC pins on nets with a small cap need a cap within 3 mm (crystal nets excluded) + for (ni, net) in nets.iter_mut().enumerate() { + if xtal_nets.contains(&ni) || !net.decaps.iter().any(|&d| !decaps[d].bulk) { + continue; + } + net.cover = net + .pads + .iter() + .copied() + .filter(|&k| { + let q = &parts[pads[k].part]; + is_ic(&q.reference, q.pads.len()) && !q.reference.starts_with(['Y', 'L', 'F']) + }) + .collect(); + } + + // links, pulls and replicated channels + let pad_of = |parts: &[Part], s: &str, what: &str| -> Result { + let (r, num) = s.split_once('.').with_context(|| format!("{what} {s}: write REF.PIN"))?; + let Some(&pi) = pref.get(r) else { bail!("{what} {s}: no part {r}") }; + parts[pi].pads.iter().copied().find(|&k| pads[k].num == num).with_context(|| format!("{what} {s}: no pin {num}")) + }; + let mut links = Vec::new(); + for l in &cfg.link { + let (a, b) = (pad_of(&parts, &l.a, "link")?, pad_of(&parts, &l.b, "link")?); + for k in [a, b] { + let pi = pads[k].part; + if !parts[pi].links.contains(&links.len()) { + parts[pi].links.push(links.len()); + } + } + links.push(Link { a, b, max: l.max, weight: l.weight }); + } + for pl in &cfg.pull { + let dir = match pl.side.as_str() { + "N" => (0.0, -1.0), + "S" => (0.0, 1.0), + "W" => (-1.0, 0.0), + "E" => (1.0, 0.0), + o => bail!("pull: side {o:?} is not N, S, E or W"), + }; + for (pi, jpart) in jp.parts.iter().enumerate() { + for (q, &k) in jpart.pads.iter().zip(&parts[pi].pads.clone()) { + if pl.nets.iter().any(|g| glob(g, &q.net)) { + parts[pi].pulls.push((k, dir, pl.weight)); + } + } + } + } + for rp in &cfg.replicate { + let Some(first) = rp.parts.first() else { continue }; + for (c, chan) in rp.parts.iter().enumerate().skip(1) { + if chan.len() != first.len() { + bail!("replicate: channel {c} has {} parts, channel 0 has {}", chan.len(), first.len()); + } + for (r0, r) in first.iter().zip(chan) { + let (Some(&m0), Some(&f)) = (pref.get(r0.as_str()), pref.get(r.as_str())) else { bail!("replicate: no part {r0} or {r}") }; + if parts[m0].fpid != parts[f].fpid { + bail!("replicate: {r} ({}) is not the footprint of {r0} ({})", parts[f].fpid, parts[m0].fpid); + } + if parts[m0].fixed || parts[f].fixed { + bail!("replicate: {r0} and {r} must both be movable"); + } + parts[f].follow = Some((m0, (rp.pitch[0] * c as f64, rp.pitch[1] * c as f64))); + parts[m0].followers.push(f); + } + } + } + + // groups: from the config and from Place_Group fields ("eth/xtal" is a subgroup of "eth") + let mut groups: Vec = Vec::new(); + let mut gid: HashMap = HashMap::new(); + let mut member: Vec<(usize, String)> = vec![]; + for (pi, p) in jp.parts.iter().enumerate() { + if let Some(g) = p.fields.get("Place_Group").filter(|g| !g.is_empty()) { + member.push((pi, g.clone())); + } + } + for g in &cfg.group { + gid.insert(g.name.clone(), groups.len()); + groups.push(Group { name: g.name.clone(), bbox: g.bbox.map(|b| Rect::new(b[0], b[1], b[2], b[3])), parts: vec![] }); + for r in &g.parts { + let Some(&pi) = pref.get(r.as_str()) else { bail!("group {}: no part {r}", g.name) }; + member.retain(|(q, _)| *q != pi); // the config overrides the field + member.push((pi, g.name.clone())); + } + } + for (pi, g) in member { + // the group and every parent group + let segs: Vec<&str> = g.split('/').collect(); + for k in (1..=segs.len()).rev() { + let name = segs[..k].join("/"); + let id = *gid.entry(name.clone()).or_insert_with(|| { + groups.push(Group { name: name.clone(), bbox: None, parts: vec![] }); + groups.len() - 1 + }); + if !parts[pi].fixed && parts[pi].follow.is_none() && !groups[id].parts.contains(&pi) { + groups[id].parts.push(pi); + } + if !parts[pi].groups.contains(&id) { + parts[pi].groups.push(id); + } + } + } + + let keepouts = jp.keepouts.iter().filter(|k| k.footprints).flat_map(|k| poly_rects(&k.poly)).collect(); + let pad_keepouts = jp.keepouts.iter().filter(|k| k.pads).flat_map(|k| poly_rects(&k.poly)).collect(); + let track_keepouts = jp.keepouts.iter().filter(|k| k.tracks).flat_map(|k| poly_rects(&k.poly)).collect(); + let movable = (0..parts.len()).filter(|&i| !parts[i].fixed && parts[i].follow.is_none()).collect(); + let b = jp.bounds; + Ok(Model { + parts, + pads, + nets, + decaps, + groups, + links, + bounds: Rect::new(b[0], b[1], b[2], b[3]), + keepouts, + pad_keepouts, + track_keepouts, + w, + movable, + }) + } + + /// Put every follower at its master's pose plus its offset. + pub fn sync(&self, at: &mut [Pt], rot: &mut [u8]) { + for (i, p) in self.parts.iter().enumerate() { + if let Some((m0, off)) = p.follow { + at[i] = (at[m0].0 + off.0, at[m0].1 + off.1); + rot[i] = rot[m0]; + } + } + } + + pub fn part(&self, r: &str) -> Option { + self.parts.iter().position(|p| p.reference == r) + } +} -- cgit v1.3