Newer
Older
SmTIAS-LightSim / scripts / check_led_board_clearance.py
"""LED 基板の違うネット(線)どうしの銅の間隔を全部測り,狭い所を図にする.

基板の切削では,違うネットの銅の間を V 字のカッター(溝の幅 0.3 mm)やハッチングで削る.間が狭い所は
はんだがはみ出すとつながりやすいので(2026-11-10 ユーザー),間隔の分布と狭い場所を洗い出す.

EAGLE の .brd(Fusion から書き出したもの)を読み,ネットごとに銅(パッド・配線)を細かい格子に
塗り,距離変換で「違うネットの銅までの距離」を求める.

実行方法:
    uv run python scripts/check_led_board_clearance.py
    uv run python scripts/check_led_board_clearance.py --brd cad/eagle/SmTIASv4_LED_side_v2.brd
"""

from __future__ import annotations

import argparse
import sys
import xml.etree.ElementTree as ET
from pathlib import Path

import matplotlib
import numpy as np
from scipy.ndimage import distance_transform_edt

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

from sm_tias_lightsim.pcb.eagle import (  # noqa: E402
    COPPER_TOP,
    _f,
    _packages,
    _quarter_turns,
    _rotate,
    parse_rotation,
)

plt.rcParams["font.family"] = ["Yu Gothic", "MS Gothic", "DejaVu Sans"]
ROOT = Path(__file__).resolve().parents[1]
BRD_DIR = ROOT / "output" / "pcb" / "fusion_brd"
DEFAULT = ("SmTIASv4_LED_side_v3", "SmTIASv4_LED_bottom_v3")
RES = 0.02  # 格子の間隔 [mm]
MARGIN = 1.0


def net_shapes(path: Path) -> tuple[dict[str, list], list]:
    """ネット名 → 銅の形の並び(("rect"|"obround", x, y, w, h)・("seg", x1, y1, x2, y2, w))."""
    root = ET.fromstring(path.read_text(encoding="utf-8"))
    packages = _packages(root)
    elements = {el.get("name"): el for el in root.iter("element")}
    outline = []
    for el in root.find(".//board/plain"):
        if el.tag == "wire" and el.get("layer") == "20":
            outline.append(tuple(_f(el, k) for k in ("x1", "y1", "x2", "y2")))
    shapes: dict[str, list] = {}
    for sig in root.iter("signal"):
        net = sig.get("name")
        items = shapes.setdefault(net, [])
        for c in sig.iter("contactref"):
            el = elements[c.get("element")]
            pkg = packages[(el.get("library", ""), el.get("package", ""))]
            ex, ey, erot = _f(el, "x"), _f(el, "y"), parse_rotation(el.get("rot"))
            for p in pkg:
                if p.tag != "smd" or p.get("name") != c.get("pad"):
                    continue
                if p.get("layer") != COPPER_TOP:
                    raise ValueError(f"{path.name}: 裏面のパッド")
                q = _quarter_turns((erot + parse_rotation(p.get("rot"))) % 360.0, path.name)
                dx, dy = _f(p, "dx"), _f(p, "dy")
                w, h = (dx, dy) if q % 2 == 0 else (dy, dx)
                px, py = _rotate(_f(p, "x"), _f(p, "y"), erot)
                kind = "obround" if _f(p, "roundness", 0.0) >= 100.0 else "rect"
                items.append((kind, ex + px, ey + py, w, h))
        for w in sig.iter("wire"):
            if w.get("layer") == COPPER_TOP:
                items.append(("seg", *(_f(w, k) for k in ("x1", "y1", "x2", "y2", "width"))))
    return shapes, outline


def rasterize(shape, xs: np.ndarray, ys: np.ndarray) -> np.ndarray:
    gx, gy = np.meshgrid(xs, ys)
    if shape[0] == "seg":
        _, x1, y1, x2, y2, w = shape
        vx, vy = x2 - x1, y2 - y1
        n2 = vx * vx + vy * vy
        t = np.clip(((gx - x1) * vx + (gy - y1) * vy) / n2, 0, 1) if n2 > 0 else 0.0
        return (gx - x1 - t * vx) ** 2 + (gy - y1 - t * vy) ** 2 <= (w / 2) ** 2
    kind, x, y, w, h = shape
    inside = (np.abs(gx - x) <= w / 2) & (np.abs(gy - y) <= h / 2)
    if kind == "obround":
        r = min(w, h) / 2
        # 両端の半円: 中心線から r 以内
        if w >= h:
            cx = np.clip(gx, x - w / 2 + r, x + w / 2 - r)
            inside = (gx - cx) ** 2 + (gy - y) ** 2 <= r * r
        else:
            cy = np.clip(gy, y - h / 2 + r, y + h / 2 - r)
            inside = (gx - x) ** 2 + (gy - cy) ** 2 <= r * r
    return inside


def analyze(path: Path, out_png: Path, limit: float) -> list[tuple[float, str, str, float, float]]:
    shapes, outline = net_shapes(path)
    pts = np.array([(s[1], s[2]) for v in shapes.values() for s in v])
    x0, y0 = pts.min(axis=0) - 5
    x1, y1 = pts.max(axis=0) + 5
    xs = np.arange(x0, x1, RES)
    ys = np.arange(y0, y1, RES)
    masks = {}
    for net, items in shapes.items():
        m = np.zeros((len(ys), len(xs)), bool)
        for s in items:
            m |= rasterize(s, xs, ys)
        masks[net] = m
    dist = {net: distance_transform_edt(~m) * RES for net, m in masks.items()}
    nets = sorted(masks)
    pairs = []
    for i, a in enumerate(nets):
        for b in nets[i + 1:]:
            d = np.where(masks[b], dist[a], np.inf)
            k = np.unravel_index(np.argmin(d), d.shape)
            if np.isfinite(d[k]):
                pairs.append((float(d[k]) - RES, a, b, float(xs[k[1]]), float(ys[k[0]])))
    pairs.sort()

    # 図: 銅(ネットごとの色)と,違うネットまでの距離が limit 未満の銅の縁
    any_copper = np.zeros_like(next(iter(masks.values())))
    near = np.zeros_like(any_copper)
    for net, m in masks.items():
        any_copper |= m
        others = np.min([dist[o] for o in nets if o != net], axis=0)
        near |= m & (others < limit)
    fig, ax = plt.subplots(figsize=(max(8, (x1 - x0) / 5), 4))
    img = np.zeros((*any_copper.shape, 3))
    img[any_copper] = (0.95, 0.65, 0.25)
    img[near] = (0.85, 0.05, 0.05)
    img[~any_copper] = (1, 1, 1)
    ax.imshow(img, origin="lower", extent=(x0, x1, y0, y1), interpolation="nearest")
    for xa, ya, xb, yb in outline:
        ax.plot([xa, xb], [ya, yb], "c-", lw=0.8)
    for gap, _a, _b, x, y in pairs:
        if gap < limit:
            ax.annotate(f"{gap:.2f}", (x, y), fontsize=6, color="b")
    ax.set_aspect("equal")
    ax.set_title(f"{path.stem}: 違うネットまで {limit} mm 未満の銅(赤)と一番近い所の間隔 [mm]")
    fig.tight_layout()
    fig.savefig(out_png, dpi=150)
    plt.close(fig)
    return pairs


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--brd", type=Path, nargs="+",
                        default=[BRD_DIR / f"{n}.brd" for n in DEFAULT])
    parser.add_argument("--limit", type=float, default=1.0, help="狭いとみなす間隔 [mm]")
    parser.add_argument("--out", type=Path, default=ROOT / "output" / "pcb" / "clearance")
    args = parser.parse_args(argv)
    args.out.mkdir(parents=True, exist_ok=True)
    for path in args.brd:
        png = args.out / f"{path.stem}.png"
        pairs = analyze(path, png, args.limit)
        print(f"== {path.stem}(ネットの組 {len(pairs)})")
        for gap, a, b, x, y in pairs:
            if gap < args.limit:
                print(f"  {gap:.2f} mm  {a} / {b}  ({x:.1f}, {y:.1f})")
        print(f"[saved] {png}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())