aboutsummaryrefslogtreecommitdiff
path: root/tools/placement_check.py
blob: 198a24c1b4ebeb5298b5d7aeca4c49caee03b5bd (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
#!/usr/bin/env python3
"""Rate the component placement of a KiCad board before routing.

Run with KiCad's bundled Python (pcbnew module):

    $KICAD_PYTHON tools/placement_check.py board.kicad_pcb [--svg out.svg] [--json out.json] \
        [--fill GND] [--pair U2:J2] [--apply-rotations out.kicad_pcb]

Checks (fill nets such as GND are left out of the ratsnest: they reach their pads
through a pour and a via, so their lines say nothing about routability):

  crossings      ratsnest lines of different nets that cross. On two layers each
                 one costs a via or a detour.
  length         total ratsnest length (MST per net), and per net class.
  decoupling     capacitors with one pad on a fill net: distance from the other pad
                 to the nearest pin of that net on an IC (>= 4 pads; bulk caps >= 4.7 uF
                 may also sit at an inductor or ferrite), and IC power pins with no
                 capacitor within 3 mm (crystal nets excluded). The ground pad must be
                 within the limit + 2 mm of a ground pin of the same part (loop area).
  rotation       2-pad parts whose ratsnest gets shorter or crosses less when the
                 part is turned by 90/180/270 degrees in place, without its courtyard
                 hitting another part.
  courtyards     front/back courtyard overlaps, and THT pads inside another
                 footprint's back courtyard (e.g. the DIN housing spacers).
  pairs          courtyard gap between named footprints (--pair A:B), for parts
                 that must sit close together.

The score starts at 100 and loses points per finding; the breakdown is printed.
"""
import argparse, json, math, re, sys
import pcbnew

MM = 1e6
DEFAULT_FILL = r"^(/.*/)?(GND|GNDA|GNDD|AGND|DGND|VSS|PGND)$"


def mm(v):
    return v / MM


class Pad:
    __slots__ = ("ref", "num", "net", "x", "y", "fp", "pad", "tht")

    def __init__(self, fp, pad):
        p = pad.GetPosition()
        self.ref, self.num, self.net = fp.GetReference(), pad.GetNumber(), pad.GetNetname()
        self.x, self.y, self.fp, self.pad = mm(p.x), mm(p.y), fp, pad
        self.tht = pad.GetAttribute() in (pcbnew.PAD_ATTRIB_PTH, pcbnew.PAD_ATTRIB_NPTH)


def mst(points):
    """Prim's MST over [(x, y, tag)], returns [(i, j, length)]."""
    n = len(points)
    if n < 2:
        return []
    inside = [False] * n
    best = [math.inf] * n
    link = [-1] * n
    best[0] = 0
    edges = []
    for _ in range(n):
        i = min((k for k in range(n) if not inside[k]), key=lambda k: best[k])
        inside[i] = True
        if link[i] >= 0:
            edges.append((link[i], i, best[i]))
        for k in range(n):
            if not inside[k]:
                d = math.hypot(points[i][0] - points[k][0], points[i][1] - points[k][1])
                if d < best[k]:
                    best[k], link[k] = d, i
    return edges


def cross(a, b, c, d, eps=1e-6):
    """Proper intersection of segments ab and cd (shared endpoints do not count)."""
    def orient(p, q, r):
        return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])
    for p in (a, b):
        for q in (c, d):
            if abs(p[0] - q[0]) < eps and abs(p[1] - q[1]) < eps:
                return None
    o1, o2, o3, o4 = orient(a, b, c), orient(a, b, d), orient(c, d, a), orient(c, d, b)
    if o1 * o2 < 0 and o3 * o4 < 0:
        t = o1 / (o1 - o2)
        return (c[0] + t * (d[0] - c[0]), c[1] + t * (d[1] - c[1]))
    return None


def rotate_about(px, py, cx, cy, deg):
    a = math.radians(deg)
    dx, dy = px - cx, py - cy
    # KiCad: positive angles turn counter-clockwise on screen (y points down)
    return (cx + dx * math.cos(a) + dy * math.sin(a), cy - dx * math.sin(a) + dy * math.cos(a))


def cap_value_uf(v):
    m = re.match(r"\s*([\d.]+)\s*([pnuµm]?)F?", v)
    if not m:
        return None
    f = {"p": 1e-6, "n": 1e-3, "u": 1, "µ": 1, "m": 1e3, "": 1}[m.group(2)]
    return float(m.group(1)) * f


class Check:
    def __init__(self, board, fill_re, ignore_refs=()):
        self.board = board
        self.fill = re.compile(fill_re)
        fps = [f for f in board.GetFootprints() if f.GetReference() not in ignore_refs]
        self.fps = fps
        self.pads = [Pad(f, p) for f in fps for p in f.Pads() if p.GetNetname()]
        self.nets = {}
        for p in self.pads:
            self.nets.setdefault(p.net, []).append(p)
        # nets with a copper zone count as fill nets too
        zone_nets = {z.GetNetname() for z in board.Zones() if not z.GetIsRuleArea() and z.GetNetname()}
        self.fill_nets = {n for n in self.nets if self.fill.search(n) or n in zone_nets}
        self.netclass = {}
        for n in board.GetNetInfo().NetsByName().values():
            self.netclass[n.GetNetname()] = n.GetNetClassName()

    def is_fill(self, net):
        return net in self.fill_nets

    # --- ratsnest ------------------------------------------------------------
    def ratsnest(self, override=None):
        """[(net, (x1, y1), (x2, y2), length, pad_a, pad_b)]; override maps pad -> (x, y)."""
        out = []
        for net, pads in self.nets.items():
            if self.is_fill(net) or len(pads) < 2:
                continue
            pts = [(override.get(p, (p.x, p.y)) if override else (p.x, p.y)) for p in pads]
            for i, j, d in mst([(x, y, None) for x, y in pts]):
                out.append((net, pts[i], pts[j], d, pads[i], pads[j]))
        return out

    @staticmethod
    def crossings(rats):
        res = []
        for i in range(len(rats)):
            a = rats[i]
            for b in rats[i + 1:]:
                if a[0] == b[0]:
                    continue
                pt = cross(a[1], a[2], b[1], b[2])
                if pt:
                    res.append((a[0], b[0], pt, a, b))
        return res

    # --- decoupling ----------------------------------------------------------
    def decoupling(self):
        ic_pads, src_pads = {}, {}
        for p in self.pads:
            if len(p.fp.Pads()) >= 4 and not p.ref.startswith(("J", "P", "TP")):
                ic_pads.setdefault(p.net, []).append(p)
            elif p.ref.startswith(("L", "FB")):
                src_pads.setdefault(p.net, []).append(p)
        xtal_nets = {p.net for p in self.pads if p.ref.startswith("Y")}
        caps, covered = [], set()
        for f in self.fps:
            ps = [p for p in self.pads if p.fp is f]
            if not f.GetReference().startswith("C") or len(f.Pads()) != 2 or len(ps) != 2:
                continue
            g = [p for p in ps if self.is_fill(p.net)]
            s = [p for p in ps if not self.is_fill(p.net)]
            if len(g) != 1 or len(s) != 1:
                continue
            s = s[0]
            uf = cap_value_uf(f.GetValue()) or 0
            # bulk caps may sit at the IC or at the inductor/ferrite that feeds the rail
            cand = ic_pads.get(s.net, []) + (src_pads.get(s.net, []) if uf >= 4.7 else [])
            if not cand:
                continue
            near = min(cand, key=lambda q: math.hypot(q.x - s.x, q.y - s.y))
            d = math.hypot(near.x - s.x, near.y - s.y)
            # return side: cap ground pad to the nearest ground pin of the same part
            gp = [q for q in self.pads if q.ref == near.ref and q.net == g[0].net]
            dg = min((math.hypot(q.x - g[0].x, q.y - g[0].y) for q in gp), default=None)
            limit = 8.0 if uf >= 4.7 else 3.0
            ok = d <= limit and (dg is None or dg <= limit + 2.0)
            caps.append(dict(ref=f.GetReference(), value=f.GetValue(), net=s.net, ic=near.ref, pin=near.num,
                             dist=round(d, 2), gnd=None if dg is None else round(dg, 2), limit=limit, ok=ok))
            for q in ic_pads.get(s.net, []):
                if math.hypot(q.x - s.x, q.y - s.y) <= 3.0:
                    covered.add((q.ref, q.num))
        # power pins of ICs: pins on nets that carry a decoupling cap (crystal load caps excluded)
        dnets = {c["net"] for c in caps} - xtal_nets
        uncovered = sorted({(p.ref, p.num, p.net) for net in dnets for p in ic_pads.get(net, [])
                            if (p.ref, p.num) not in covered and not p.ref.startswith(("Y", "L", "FB"))})
        return caps, uncovered

    # --- rotation -------------------------------------------------------------
    def rotation(self, rats):
        base_x = self.crossings(rats)
        sugg = []
        for f in self.fps:
            if len(f.Pads()) != 2 or f.IsLocked():
                continue
            mine = [p for p in self.pads if p.fp is f and not self.is_fill(p.net)]
            if not mine:
                continue
            c = f.GetPosition()
            cx, cy = mm(c.x), mm(c.y)
            results = []
            for rot in (0, 90, 180, 270):
                ov = {p: rotate_about(p.x, p.y, cx, cy, rot) for p in mine}
                r = self.ratsnest(ov) if rot else rats
                nets = {p.net for p in mine}
                length = sum(e[3] for e in r if e[0] in nets)
                local = [e for e in r if e[0] in nets]
                others = [e for e in r if e[0] not in nets]
                nx = sum(1 for a in local for b in others if cross(a[1], a[2], b[1], b[2]))
                results.append((rot, nx, length))
            cur = results[0]
            results = [r for r in results if not r[0] or self.fits(f, r[0])]
            best = min(results, key=lambda t: (t[1], t[2]))
            if best[0] and (best[1] < cur[1] or cur[2] - best[2] > 0.5):
                sugg.append(dict(ref=f.GetReference(), turn=best[0],
                                 to=(f.GetOrientationDegrees() + best[0]) % 360,
                                 crossings=(cur[1], best[1]), length=(round(cur[2], 2), round(best[2], 2))))
        return sugg

    def fits(self, f, turn):
        """True if footprint f, turned by `turn` degrees in place, hits no other courtyard."""
        old = f.GetOrientation()
        f.SetOrientation(old + pcbnew.EDA_ANGLE(turn, pcbnew.DEGREES_T))
        ok = True
        for layer in (pcbnew.F_CrtYd, pcbnew.B_CrtYd):
            mine = f.GetCourtyard(layer)
            if not mine.OutlineCount():
                continue
            if any(g is not f and g.GetCourtyard(layer).OutlineCount() and mine.Collide(g.GetCourtyard(layer))
                   for g in self.board.GetFootprints()):
                ok = False
        f.SetOrientation(old)
        return ok

    # --- mechanics -----------------------------------------------------------
    def courtyards(self):
        res = []
        for side, layer in (("front", pcbnew.F_CrtYd), ("back", pcbnew.B_CrtYd)):
            polys = [(f, f.GetCourtyard(layer)) for f in self.fps]
            polys = [(f, p) for f, p in polys if p.OutlineCount()]
            for i, (a, pa) in enumerate(polys):
                for b, pb in polys[i + 1:]:
                    if pa.Collide(pb):
                        res.append(dict(side=side, a=a.GetReference(), b=b.GetReference()))
        for f in self.fps:
            bc = f.GetCourtyard(pcbnew.B_CrtYd)
            if not bc.OutlineCount():
                continue
            for g in self.fps:
                if g is f:
                    continue
                for p in g.Pads():
                    if p.GetAttribute() == pcbnew.PAD_ATTRIB_PTH and bc.Collide(p.GetPosition(), int(p.GetSize().x / 2)):
                        res.append(dict(side="back", a=f.GetReference(), b="%s.%s (THT)" % (g.GetReference(), p.GetNumber())))
        return res

    def gap(self, ra, rb):
        fa = next(f for f in self.fps if f.GetReference() == ra)
        fb = next(f for f in self.fps if f.GetReference() == rb)
        a, b = fa.GetCourtyard(pcbnew.F_CrtYd).BBox(), fb.GetCourtyard(pcbnew.F_CrtYd).BBox()
        dx = max(a.GetLeft() - b.GetRight(), b.GetLeft() - a.GetRight(), 0)
        dy = max(a.GetTop() - b.GetBottom(), b.GetTop() - a.GetBottom(), 0)
        return round(mm(math.hypot(dx, dy)), 2)


def svg(path, chk, rats, xs, flagged):
    bb = chk.board.GetBoardEdgesBoundingBox()
    x0, y0, w, h = mm(bb.GetLeft()) - 2, mm(bb.GetTop()) - 2, mm(bb.GetWidth()) + 4, mm(bb.GetHeight()) + 4
    o = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="%.2f %.2f %.2f %.2f" width="%dmm" height="%dmm">' % (x0, y0, w, h, w * 4, h * 4),
         '<rect x="%.2f" y="%.2f" width="%.2f" height="%.2f" fill="white"/>' % (x0, y0, w, h)]
    for d in chk.board.GetDrawings():
        if d.GetLayer() == pcbnew.Edge_Cuts and d.GetShape() == pcbnew.SHAPE_T_SEGMENT:
            s, e = d.GetStart(), d.GetEnd()
            o.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="black" stroke-width="0.15"/>' % (mm(s.x), mm(s.y), mm(e.x), mm(e.y)))
    for f in chk.fps:
        for layer, col in ((pcbnew.F_CrtYd, "#b0b0b0"), (pcbnew.B_CrtYd, "#c9a0dc")):
            cy = f.GetCourtyard(layer)
            for k in range(cy.OutlineCount()):
                ol = cy.Outline(k)
                pts = " ".join("%.3f,%.3f" % (mm(ol.CPoint(i).x), mm(ol.CPoint(i).y)) for i in range(ol.PointCount()))
                fill = "#ffe0b0" if f.GetReference() in flagged else "none"
                o.append('<polygon points="%s" fill="%s" stroke="%s" stroke-width="0.05"/>' % (pts, fill, col))
        for p in f.Pads():
            q = p.GetPosition(); sz = p.GetSize()
            col = "#2e7d32" if chk.is_fill(p.GetNetname()) else "#c62828"
            o.append('<circle cx="%.3f" cy="%.3f" r="%.3f" fill="%s" opacity="0.6"/>' % (mm(q.x), mm(q.y), max(0.15, mm(min(sz.x, sz.y)) / 2), col))
        c = f.GetPosition()
        o.append('<text x="%.3f" y="%.3f" font-size="0.7" text-anchor="middle" font-family="sans-serif">%s</text>' % (mm(c.x), mm(c.y) + 0.25, f.GetReference()))
    for e in rats:
        o.append('<line x1="%.3f" y1="%.3f" x2="%.3f" y2="%.3f" stroke="#1565c0" stroke-width="0.06"/>' % (e[1][0], e[1][1], e[2][0], e[2][1]))
    for x in xs:
        o.append('<circle cx="%.3f" cy="%.3f" r="0.35" fill="none" stroke="#d50000" stroke-width="0.1"/>' % x[2])
    o.append("</svg>")
    open(path, "w").write("\n".join(o))


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("board")
    ap.add_argument("--fill", default=DEFAULT_FILL, help="regex for fill nets left out of the ratsnest (default: GND-like names; nets with zones are added)")
    ap.add_argument("--ignore", default="", help="comma-separated references to leave out (e.g. an off-board connector)")
    ap.add_argument("--pair", action="append", default=[], help="A:B[:max_mm] report the courtyard gap between two footprints")
    ap.add_argument("--svg", help="write an SVG overlay: courtyards, ratsnest, crossings (red), flagged parts (orange)")
    ap.add_argument("--json", help="write the findings as JSON")
    ap.add_argument("--apply-rotations", metavar="OUT", help="write a copy of the board with the suggested rotations applied")
    a = ap.parse_args()

    board = pcbnew.LoadBoard(a.board)
    chk = Check(board, a.fill, [r for r in a.ignore.split(",") if r])
    rats = chk.ratsnest()
    xs = chk.crossings(rats)
    caps, uncovered = chk.decoupling()
    rot = chk.rotation(rats)
    cy = chk.courtyards()
    pairs = []
    for spec in a.pair:
        parts = spec.split(":")
        g = chk.gap(parts[0], parts[1])
        lim = float(parts[2]) if len(parts) > 2 else None
        pairs.append(dict(a=parts[0], b=parts[1], gap=g, limit=lim, ok=lim is None or g <= lim))

    total = sum(e[3] for e in rats)
    by_class = {}
    for e in rats:
        k = chk.netclass.get(e[0], "?")
        by_class[k] = by_class.get(k, 0) + e[3]
    bad_caps = [c for c in caps if not c["ok"]]
    penalties = {
        "crossings": 1.0 * len(xs),
        "decoupling": sum(min(5.0, max(c["dist"] - c["limit"], (c["gnd"] or 0) - c["limit"] - 2.0, 0.5)) for c in bad_caps)
                      + 1.0 * len(uncovered),
        "rotation": 2.0 * len(rot),
        "courtyards": 10.0 * len(cy),
        "pairs": sum(5.0 for p in pairs if not p["ok"]),
    }
    score = max(0.0, 100.0 - sum(penalties.values()))

    print("board: %s" % a.board)
    print("fill nets (not in ratsnest): %s" % ", ".join(sorted(chk.fill_nets)))
    print("ratsnest: %.1f mm total; %s" % (total, ", ".join("%s %.1f" % kv for kv in sorted(by_class.items()))))
    print("\ncrossings: %d" % len(xs))
    pairs_x = {}
    for n1, n2, pt, ea, eb in xs:
        pairs_x.setdefault(tuple(sorted((n1, n2))), []).append((pt, ea, eb))
    for (n1, n2), lst in sorted(pairs_x.items(), key=lambda kv: -len(kv[1])):
        ea, eb = lst[0][1], lst[0][2]
        print("  %-26s x %-26s %d  (%s.%s-%s.%s / %s.%s-%s.%s)" % (n1, n2, len(lst), ea[4].ref, ea[4].num, ea[5].ref, ea[5].num,
                                                              eb[4].ref, eb[4].num, eb[5].ref, eb[5].num))
    print("\ndecoupling (cap pad to nearest IC pin of its net, limit 3 mm, 8 mm for >= 4.7 uF;")
    print("            cap ground pad to that part's nearest ground pin, limit + 2 mm):")
    for c in sorted(caps, key=lambda c: -c["dist"] + c["limit"]):
        print("  %s %-6s %-6s %-22s %s.%s %5.2f mm  gnd %s%s" % ("  " if c["ok"] else "!!", c["ref"], c["value"], c["net"], c["ic"], c["pin"], c["dist"],
              "  -  " if c["gnd"] is None else "%5.2f" % c["gnd"], "" if c["ok"] else "  > %.0f" % c["limit"]))
    if uncovered:
        print("  IC power pins without a small cap within 3 mm: %s" % ", ".join("%s.%s (%s)" % u for u in uncovered))
    print("\nrotation suggestions: %d" % len(rot))
    for r in rot:
        print("  %-5s turn %3d -> %3d deg  crossings %d -> %d, length %.1f -> %.1f mm" % (r["ref"], r["turn"], r["to"], r["crossings"][0], r["crossings"][1], r["length"][0], r["length"][1]))
    print("\ncourtyard conflicts: %d" % len(cy))
    for c in cy:
        print("  %s: %s / %s" % (c["side"], c["a"], c["b"]))
    if pairs:
        print("\npairs (courtyard gap):")
        for p in pairs:
            print("  %s %s-%s %.2f mm%s" % ("  " if p["ok"] else "!!", p["a"], p["b"], p["gap"], "" if p["limit"] is None else " (max %.1f)" % p["limit"]))
    print("\nscore %.1f / 100   (penalties: %s)" % (score, ", ".join("%s %.1f" % kv for kv in penalties.items() if kv[1])))

    flagged = {c["ref"] for c in bad_caps} | {r["ref"] for r in rot}
    if a.svg:
        svg(a.svg, chk, rats, xs, flagged)
    if a.json:
        json.dump(dict(score=score, penalties=penalties, ratsnest_mm=total, by_class=by_class,
                       crossings=[dict(a=n1, b=n2, at=pt) for n1, n2, pt, _, _ in xs], decoupling=caps,
                       uncovered=uncovered, rotation=rot, courtyards=cy, pairs=pairs), open(a.json, "w"), indent=1)
    if a.apply_rotations:
        for r in rot:
            f = board.FindFootprintByReference(r["ref"])
            f.SetOrientationDegrees(r["to"])
        pcbnew.SaveBoard(a.apply_rotations, board)


if __name__ == "__main__":
    main()