#!/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 = ['' % (x0, y0, w, h, w * 4, h * 4), '' % (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('' % (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('' % (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('' % (mm(q.x), mm(q.y), max(0.15, mm(min(sz.x, sz.y)) / 2), col)) c = f.GetPosition() o.append('%s' % (mm(c.x), mm(c.y) + 0.25, f.GetReference())) for e in rats: o.append('' % (e[1][0], e[1][1], e[2][0], e[2][1])) for x in xs: o.append('' % x[2]) o.append("") 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()