"""Cross-check generated touchpoint pads against KiCad's IPC-D-356 export.""" from __future__ import annotations import math import re from collections import Counter, defaultdict from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path COORDINATE = re.compile(r"X([+-]\d{6})Y([+-]\d{6})") UNIT_MM = 0.00254 DEFAULT_TOLERANCE_MM = 0.02 class IpCd356AlignmentError(ValueError): """Raised when generated numbered pads do not align with IPC-D-356.""" @dataclass(frozen=True) class _Record: record_type: str net: str | None x: float y: float def _normalized_net(value: object) -> str | None: text = str(value or "").strip().upper() return None if text in {"", "N/C"} else text def _records(path: Path) -> list[_Record]: try: lines = path.read_text(encoding="ascii").splitlines() except OSError as exc: raise IpCd356AlignmentError(f"cannot read IPC-D-356 {path}: {exc}") from exc records: list[_Record] = [] for line in lines: record_type = line[:3] if record_type not in {"317", "327"} or line[17:31].strip() == "VIA": continue match = COORDINATE.search(line) if match is None: continue records.append( _Record( record_type=record_type, net=_normalized_net(line[3:17]), x=int(match.group(1)) * UNIT_MM, y=-int(match.group(2)) * UNIT_MM, ) ) if not records: raise IpCd356AlignmentError("IPC-D-356 contains no component pad records") return records def _numbered_pads(board_data: Mapping[str, object]) -> list[tuple[str, str, str | None, float, float]]: result: list[tuple[str, str, str | None, float, float]] = [] touchpoints = board_data.get("touchpoints", []) if not isinstance(touchpoints, list): return result for touchpoint in touchpoints: if not isinstance(touchpoint, Mapping): continue reference = str(touchpoint.get("reference") or "") pins = touchpoint.get("pins", []) if not isinstance(pins, list): continue for pin in pins: if not isinstance(pin, Mapping) or not str(pin.get("number") or ""): continue position = pin.get("position") if not isinstance(position, Mapping): continue result.append( ( reference, str(pin.get("number")), _normalized_net(pin.get("net")), float(position.get("x", 0.0)), float(position.get("y", 0.0)), ) ) return result def validate_ipcd356_alignment( board_data: Mapping[str, object], path: Path | str, *, tolerance_mm: float = DEFAULT_TOLERANCE_MM, ) -> dict[str, object]: if tolerance_mm <= 0: raise ValueError("tolerance_mm must be positive") records = _records(Path(path)) pads = _numbered_pads(board_data) bucket_size = tolerance_mm buckets: dict[tuple[int, int], list[int]] = defaultdict(list) for index, record in enumerate(records): buckets[(round(record.x / bucket_size), round(record.y / bucket_size))].append(index) used: set[int] = set() failures: list[str] = [] matched_types: Counter[str] = Counter() for reference, number, net, x, y in pads: center = (round(x / bucket_size), round(y / bucket_size)) candidates: list[tuple[float, int, _Record]] = [] for offset_x in (-1, 0, 1): for offset_y in (-1, 0, 1): for index in buckets.get((center[0] + offset_x, center[1] + offset_y), []): if index in used: continue record = records[index] distance = math.hypot(x - record.x, y - record.y) if distance <= tolerance_mm: candidates.append((distance, index, record)) net_matches = [item for item in candidates if item[2].net == net] if not net_matches: nearby_nets = sorted({item[2].net or "N/C" for item in candidates}) failures.append( f"{reference}.{number} at {x:.4f},{y:.4f} net={net or 'N/C'} nearby={nearby_nets}" ) continue _, index, record = min(net_matches, key=lambda item: item[0]) used.add(index) matched_types[record.record_type] += 1 if failures: detail = "; ".join(failures[:10]) raise IpCd356AlignmentError( f"D356 alignment failed for {len(failures)}/{len(pads)} numbered pads: {detail}" ) return { "numbered_pads": len(pads), "matched_pads": len(pads), "record_types": {record_type: matched_types.get(record_type, 0) for record_type in ("317", "327")}, "tolerance_mm": tolerance_mm, }