aboutsummaryrefslogtreecommitdiff
path: root/tools/placer/src/cost.rs
blob: a91e25d821381d4f8277c8c6e81b18548ef12e53 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
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<Seg>,
    bb: Rect,
    /// old lines that are gone
    removed: Vec<bool>,
    /// new lines that were not there before
    added: Vec<usize>,
}

/// 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<Pt>,
    pub rot: Vec<u8>,
    pp: Vec<Pt>,
    /// courtyard hull of each part on the board
    hull_w: Vec<Rect>,
    net_cost: Vec<f64>,
    segs: Vec<Vec<Seg>>,
    /// bounding box of each net's lines
    nbb: Vec<Rect>,
    pair: Vec<f64>,
    unary: Vec<f64>,
    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<u32>,
    pstamp: Vec<u32>,
    moved: Vec<usize>,
    old: Vec<(Pt, u8)>,
    new: Vec<(Pt, u8)>,
    p_net: Vec<Pending>,
    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<Pt>, rot: Vec<u8>) -> 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::<usize>();
                }
            }
        }
        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<usize> = (0..n).collect();
        t.block = m.w.block * self.segs.iter().flatten().map(|e| self.block_parts(e, &all)).sum::<f64>();
        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<Seg>) {
        let m = self.m;
        let w = &m.w;
        let net = &m.nets[n];
        let mut t = NetT::default();
        let pts: Vec<Pt> = 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<Item = &'a Seg> {
        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::<f64>();
                }
            }
            for p in pn.iter().filter(|p| p.net != e.net) {
                x += self.kept(p).map(|f| cross_w(e, f)).sum::<f64>();
            }
            x += ch[a + 1..].iter().filter(|f| f.net != e.net).map(|f| cross_w(e, f)).sum::<f64>();
        }
        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<usize> = (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, &region, &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, &region, &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::<f64>();
                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
    }
}