"""Grid maze router for 2-layer boards (Python side; the search runs in astar.c). The board is a 0.05 mm grid on two layers (0 = F.Cu, 1 = B.Cu). Clearance uses exact distance fields: for every cell the distance to the nearest copper (d1, its net n1) and to the nearest copper of any other net (d2). A track of width w fits where the distance to foreign copper is >= w/2 + CLR. Necks (narrower width) are allowed only near pads, so fine-pitch pins can be entered. Call setup(x0, y0, x1, y1) with the board extents before creating a Board. """ import ctypes, json, math, os, subprocess import numpy as np import shapely from shapely.geometry import Polygon, Point, box, LineString from scipy import ndimage HERE = os.path.dirname(os.path.abspath(__file__)) _LIB = os.path.join(HERE, "libastar.dylib") if not os.path.exists(_LIB) or os.path.getmtime(_LIB) < os.path.getmtime(os.path.join(HERE, "astar.c")): subprocess.run(["cc", "-O3", "-shared", "-fPIC", "-o", _LIB, os.path.join(HERE, "astar.c")], check=True) lib = ctypes.CDLL(_LIB) fp = np.ctypeslib.ndpointer lib.init.argtypes = [ctypes.c_int, ctypes.c_int] lib.route.restype = ctypes.c_int lib.route.argtypes = [fp(np.float32), fp(np.int32), fp(np.float32), fp(np.float32), fp(np.float32), ctypes.c_int, fp(np.int32), ctypes.c_int, fp(np.uint8), ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, fp(np.int32), ctypes.c_int, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_int, ctypes.c_int, fp(np.int32), fp(np.uint8), ctypes.c_int, ctypes.c_int] RES = 0.05 X0 = Y0 = X1 = Y1 = 0.0 NX = NY = N = 0 def setup(x0, y0, x1, y1): """Set the grid to the board extents (mm). Call before Board().""" global X0, Y0, X1, Y1, NX, NY, N X0, Y0, X1, Y1 = x0, y0, x1, y1 NX = int(round((X1 - X0) / RES)) + 1 NY = int(round((Y1 - Y0) / RES)) + 1 N = NX * NY CAP = 1.5 CLR = 0.2 M = 0.015 # numeric margin on clearance checks RDIAG = 0.02 # extra margin on diagonal steps EDGE_CLR = 0.5 # copper to board edge HOLE_CLR = 0.3 # copper to NPTH hole edge def cell_xy(i, j): return X0 + i * RES, Y0 + j * RES def xy_cell(x, y): return int(round((x - X0) / RES)), int(round((y - Y0) / RES)) class Item: __slots__ = ("kind", "net", "layers", "geom", "bbox", "w", "owner") def __init__(self, kind, net, layers, geom, w=0.0, owner=None): self.kind, self.net, self.layers, self.geom, self.w, self.owner = kind, net, layers, geom, w, owner if kind == "pad": self.bbox = geom.bounds elif kind == "seg": (x1, y1), (x2, y2) = geom self.bbox = (min(x1, x2) - w / 2, min(y1, y2) - w / 2, max(x1, x2) + w / 2, max(y1, y2) + w / 2) elif kind == "via": x, y = geom; r = w / 2 self.bbox = (x - r, y - r, x + r, y + r) def dist(self, X, Y): if self.kind == "pad": return shapely.distance(shapely.points(X, Y), self.geom).astype(np.float32) if self.kind == "seg": (x1, y1), (x2, y2) = self.geom dx, dy = x2 - x1, y2 - y1 L2 = dx * dx + dy * dy if L2 == 0: t = np.zeros_like(X) else: t = np.clip(((X - x1) * dx + (Y - y1) * dy) / L2, 0, 1) return (np.hypot(X - (x1 + t * dx), Y - (y1 + t * dy)) - self.w / 2).astype(np.float32) if self.kind == "via": x, y = self.geom return (np.hypot(X - x, Y - y) - self.w / 2).astype(np.float32) class Board: def __init__(self, board_json, netclass_of, domains, plane_nets=("GND",)): d = json.load(open(board_json)) if isinstance(board_json, str) else board_json self.plane_nets = set(plane_nets) self.fpcopper = d.get("fpcopper", []) self.keepouts = [Polygon(k) for k in d.get("keepouts", [])] self.fps = d["fps"] self.netid = {"": -1} self.netname = {-1: ""} self.pads = [] # dicts with poly, net id, layers, ref, num, center for p in d["pads"]: layers = tuple(L for L, k in ((0, "F"), (1, "B")) if p[k]) if not layers: continue name = p["net"] if not name or name.startswith("unconnected"): nid = -1 else: if name not in self.netid: k = len(self.netid); self.netid[name] = k; self.netname[k] = name nid = self.netid[name] poly = Polygon(p["F"] or p["B"]) self.pads.append(dict(ref=p["ref"], num=p["num"], net=nid, layers=layers, poly=poly, x=p["x"], y=p["y"], drill=p["drill"], tht=len(layers) == 2)) self.npth = [(p["x"], p["y"], p["drill"]) for p in d["pads"] if p.get("npth")] self.netclass_of = netclass_of self.domains = domains self.items = [] self.d1 = np.full((2, NY, NX), CAP, np.float32) self.n1 = np.zeros((2, NY, NX), np.int32) self.d2 = np.full((2, NY, NX), CAP, np.float32) self.padd = np.full((2, NY, NX), CAP, np.float32) self.cost = np.zeros((2, NY, NX), np.float32) self.base = np.full((2, NY, NX), CAP, np.float32) gx = X0 + np.arange(NX) * RES; gy = Y0 + np.arange(NY) * RES self.GX, self.GY = np.meshgrid(gx, gy) lib.init(NX, NY) self.tgt = np.zeros(2 * N, np.uint8) self.out = np.zeros(400000, np.int32); self.outneck = np.zeros(400000, np.uint8) self.routes = {} # net id -> list of route records (segments/vias) # ---------- static obstacles ---------- def build_static(self, keepouts=(), domain_seeds=()): keepouts = list(keepouts) + self.keepouts GX, GY = self.GX, self.GY edge = np.minimum.reduce([GX - X0, X1 - GX, GY - Y0, Y1 - GY]) base = edge - (EDGE_CLR - CLR) for (x, y, dr) in self.npth: r = dr / 2 + HOLE_CLR base = np.minimum(base, np.hypot(GX - x, GY - y) - r + CLR) for poly in keepouts: dd = shapely.distance(shapely.points(GX.ravel(), GY.ravel()), poly).reshape(GX.shape) base = np.minimum(base, dd + CLR) # isolation domains (e.g. isolated RS485): voronoi to domain pad copper, eroded by # 1.55 mm each side. Skipped when the board has none. dom_ids = sorted(set(self.domains.values()) | {"LOGIC"}) if len(dom_ids) == 1: dom_ids = [] dist_stack = [] for dmn in dom_ids: mask = np.zeros((NY, NX), bool) for p in self.pads: if p["net"] < 0: continue if self.domains.get(self.netname[p["net"]], "LOGIC") != dmn: continue b = p["poly"].bounds i0, j0 = xy_cell(b[0], b[1]); i1, j1 = xy_cell(b[2], b[3]) sub = shapely.contains_xy(p["poly"], GX[j0:j1+1, i0:i1+1], GY[j0:j1+1, i0:i1+1]) mask[j0:j1+1, i0:i1+1] |= sub ci, cj = xy_cell(p["x"], p["y"]); mask[cj, ci] = True for (sd, sx, sy) in domain_seeds: if sd == dmn: ci, cj = xy_cell(sx, sy); mask[cj, ci] = True dist_stack.append(ndimage.distance_transform_edt(~mask) * RES) if dom_ids: dist_stack = np.array(dist_stack) owner = np.argmin(dist_stack, axis=0) self.dom_owner = owner; self.dom_ids = dom_ids allowed = np.zeros((NY, NX), bool) for k in range(len(dom_ids)): m = owner == k dout = ndimage.distance_transform_edt(m) * RES # distance to nearest non-m cell allowed |= m & (dout >= 1.55) dforb = ndimage.distance_transform_edt(allowed) * RES # distance from allowed cell to forbidden base = np.minimum(base, np.where(allowed, dforb + CLR - RES, -1.0)) self.allowed = allowed base = base.astype(np.float32) self.base[0] = base; self.base[1] = base self.reset_region(None) # pad distance field for via-in-pad avoidance (SMD pads, not exposed pads) for p in self.pads: if p["tht"]: continue b = p["poly"].bounds if (b[2] - b[0]) > 2.5 and (b[3] - b[1]) > 2.5 and p["net"] >= 0 and self.netname[p["net"]] in self.plane_nets: continue # exposed GND pad: vias allowed sl, X, Y = self.window(b, 1.0) dd = shapely.distance(shapely.points(X, Y), p["poly"]).astype(np.float32) for L in p["layers"]: v = self.padd[L][sl]; np.minimum(v, dd, out=v) for p in self.pads: it = Item("pad", p["net"], p["layers"], p["poly"], owner=("pad", p["ref"], p["num"])) p["item"] = it self.items.append(it) self.insert(it) if True: # footprint copper that is not a pad (net-tie bridges, antenna graphics) for g in self.fpcopper: poly = Polygon(g["poly"]).buffer(0) for p in self.pads: if p["ref"] == g["ref"]: poly = poly.difference(p["poly"]) if poly.is_empty: continue # a net tie's bridge is GND copper (it joins the AGND pad to GND) nid = self.netid.get("GND", -1) if g["ref"].startswith("NT") else -1 it = Item("pad", nid, (0,) if g["layer"] == "F" else (1,), poly, owner=("fpcopper", g["ref"])) self.items.append(it); self.insert(it) # KiCad sees this graphic as net-less for hole clearance (0.3 mm to the via hole) sl, X, Y = self.window(poly.bounds, 1.0) dd = shapely.distance(shapely.points(X, Y), poly).astype(np.float32) - 0.1 for L in (0, 1): v = self.padd[L][sl]; np.minimum(v, dd, out=v) def window(self, b, pad): i0 = max(0, int(math.floor((b[0] - pad - X0) / RES))); j0 = max(0, int(math.floor((b[1] - pad - Y0) / RES))) i1 = min(NX - 1, int(math.ceil((b[2] + pad - X0) / RES))); j1 = min(NY - 1, int(math.ceil((b[3] + pad - Y0) / RES))) sl = (slice(j0, j1 + 1), slice(i0, i1 + 1)) return sl, self.GX[sl], self.GY[sl] def reset_region(self, b): if b is None: sl = (slice(None), slice(None)) else: sl, _, _ = self.window(b, 0) for L in (0, 1): bd = self.base[L][sl] self.d1[L][sl] = np.minimum(bd, CAP) self.n1[L][sl] = np.where(bd < CAP, -1, 0) self.d2[L][sl] = CAP def insert(self, it, clip=None): b = it.bbox if clip is not None: b2 = (max(b[0] - CAP, clip[0]), max(b[1] - CAP, clip[1]), min(b[2] + CAP, clip[2]), min(b[3] + CAP, clip[3])) if b2[0] > b2[2] or b2[1] > b2[3]: return sl, X, Y = self.window(b2, 0) else: sl, X, Y = self.window(b, CAP) dd = it.dist(X, Y) net = it.net for L in it.layers: d1 = self.d1[L][sl]; n1 = self.n1[L][sl]; d2 = self.d2[L][sl] same = n1 == net np.minimum(d1, dd, out=d1, where=same) m = (~same) & (dd < d1) d2[m] = d1[m]; d1[m] = dd[m]; n1[m] = net o = (~same) & (~m) np.minimum(d2, dd, out=d2, where=o) def remove_items(self, items): if not items: return ids = set(id(i) for i in items) self.items = [i for i in self.items if id(i) not in ids] for it in items: b = (it.bbox[0] - CAP, it.bbox[1] - CAP, it.bbox[2] + CAP, it.bbox[3] + CAP) self.reset_region(b) for o in self.items: ob = o.bbox if ob[0] - CAP > b[2] or ob[2] + CAP < b[0] or ob[1] - CAP > b[3] or ob[3] + CAP < b[1]: continue self.insert(o, clip=b) # ---------- routing ---------- def cells_of(self, items, layers=(0, 1)): out = [] for it in items: sl, X, Y = self.window(it.bbox, 0.05) dd = it.dist(X, Y) jj, ii = np.nonzero(dd <= 0.0) j0, i0 = sl[0].start, sl[1].start c = (jj + j0) * NX + (ii + i0) for L in it.layers: if L in layers: out.append(L * N + c) if not out: return np.zeros(0, np.int32) return np.unique(np.concatenate(out)).astype(np.int32) def route(self, net, src_items, tgt_items=None, goal_layer1=False, w=0.2, wneck=0.0, via_d=0.6, via_cost=40.0, via_cmult=0.0, bmult=3.0, turn=4.0, allow_via=True, layer_mask=3, neck_items=(), max_expand=4000000, hxy=None, extra_tgt_cells=None): src = self.cells_of(src_items) if len(src) == 0: return None if tgt_items: tc = self.cells_of(tgt_items) else: tc = np.zeros(0, np.int32) if extra_tgt_cells is not None and len(extra_tgt_cells): tc = np.concatenate([tc, extra_tgt_cells]).astype(np.int32) self.tgt[tc] = 1 if hxy is None: if tgt_items: g0 = tgt_items[0] c = g0.geom.centroid if g0.kind == "pad" else (Point(g0.geom) if g0.kind == "via" else Point(g0.geom[0])) hxy = (c.x, c.y) else: hxy = (X0, Y0) hx, hy = xy_cell(*hxy) boxes = [] for it in neck_items: b = it.bbox i0, j0 = xy_cell(b[0] - 1.0, b[1] - 1.0); i1, j1 = xy_cell(b[2] + 1.0, b[3] + 1.0) boxes += [i0, j0, i1, j1] boxes = np.array(boxes or [0, 0, -1, -1], np.int32) r_nom = w / 2 + CLR + M r_neck = (wneck / 2 + CLR + M) if wneck else 0.0 r_via = via_d / 2 + CLR + M r_vpad = via_d / 2 + 0.05 n = lib.route(self.d1.ravel(), self.n1.ravel(), self.d2.ravel(), self.padd.ravel(), self.cost.ravel(), net, src, len(src), self.tgt, int(goal_layer1), hx, hy, r_nom, r_neck, r_via, r_vpad, RDIAG, boxes, len(boxes) // 4, via_cost, via_cmult, bmult, turn, int(allow_via), max_expand, self.out, self.outneck, len(self.out), layer_mask) self.tgt[tc] = 0 if n < 0: return None path = self.out[:n][::-1].copy(); neck = self.outneck[:n][::-1].copy() return path, neck def path_to_geom(self, net, path, neck, w, wneck, via_d): """Convert a cell path into segments and vias (lists).""" pts = [] for s, nk in zip(path, neck): L = int(s // N); c = int(s % N) pts.append((L, c % NX, c // NX, int(nk))) segs, vias = [], [] run = [pts[0]] def flush(run): if len(run) < 2: return # widths per step k = 0 while k < len(run) - 1: L, i, j, nk = run[k] wd = wneck if (wneck and (run[k][3] or run[k + 1][3])) else w # extend while direction and width constant di, dj = run[k + 1][1] - i, run[k + 1][2] - j m = k + 1 while m < len(run) - 1: w2 = wneck if (wneck and (run[m][3] or run[m + 1][3])) else w if (run[m + 1][1] - run[m][1], run[m + 1][2] - run[m][2]) != (di, dj) or w2 != wd: break m += 1 segs.append((L, cell_xy(i, j), cell_xy(run[m][1], run[m][2]), wd)) k = m for p in pts[1:]: if p[0] != run[-1][0]: flush(run) vias.append(cell_xy(p[1], p[2])) run = [p] else: run.append(p) flush(run) return segs, vias def commit(self, net, segs, vias, via_d, tag): items = [] for (L, a, b, wd) in segs: it = Item("seg", net, (L,), (a, b), w=wd, owner=tag) items.append(it) for v in vias: items.append(Item("via", net, (0, 1), v, w=via_d, owner=tag)) for it in items: self.items.append(it); self.insert(it) return items def stub(self, net, cell_xy_pt, L, target_item, w): """Straight stub from a path end to the centre of the pad it ends in (if inside).""" if target_item.kind != "pad": return None c = target_item.geom.centroid if target_item.geom.contains(Point(cell_xy_pt)) and (abs(c.x - cell_xy_pt[0]) > 1e-6 or abs(c.y - cell_xy_pt[1]) > 1e-6): return (L, cell_xy_pt, (c.x, c.y), w) return None