ipcd356.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. """Cross-check generated touchpoint pads against KiCad's IPC-D-356 export."""
  2. from __future__ import annotations
  3. import math
  4. import re
  5. from collections import Counter, defaultdict
  6. from collections.abc import Mapping
  7. from dataclasses import dataclass
  8. from pathlib import Path
  9. COORDINATE = re.compile(r"X([+-]\d{6})Y([+-]\d{6})")
  10. UNIT_MM = 0.00254
  11. DEFAULT_TOLERANCE_MM = 0.02
  12. class IpCd356AlignmentError(ValueError):
  13. """Raised when generated numbered pads do not align with IPC-D-356."""
  14. @dataclass(frozen=True)
  15. class _Record:
  16. record_type: str
  17. net: str | None
  18. x: float
  19. y: float
  20. def _normalized_net(value: object) -> str | None:
  21. text = str(value or "").strip().upper()
  22. return None if text in {"", "N/C"} else text
  23. def _records(path: Path) -> list[_Record]:
  24. try:
  25. lines = path.read_text(encoding="ascii").splitlines()
  26. except OSError as exc:
  27. raise IpCd356AlignmentError(f"cannot read IPC-D-356 {path}: {exc}") from exc
  28. records: list[_Record] = []
  29. for line in lines:
  30. record_type = line[:3]
  31. if record_type not in {"317", "327"} or line[17:31].strip() == "VIA":
  32. continue
  33. match = COORDINATE.search(line)
  34. if match is None:
  35. continue
  36. records.append(
  37. _Record(
  38. record_type=record_type,
  39. net=_normalized_net(line[3:17]),
  40. x=int(match.group(1)) * UNIT_MM,
  41. y=-int(match.group(2)) * UNIT_MM,
  42. )
  43. )
  44. if not records:
  45. raise IpCd356AlignmentError("IPC-D-356 contains no component pad records")
  46. return records
  47. def _numbered_pads(board_data: Mapping[str, object]) -> list[tuple[str, str, str | None, float, float]]:
  48. result: list[tuple[str, str, str | None, float, float]] = []
  49. touchpoints = board_data.get("touchpoints", [])
  50. if not isinstance(touchpoints, list):
  51. return result
  52. for touchpoint in touchpoints:
  53. if not isinstance(touchpoint, Mapping):
  54. continue
  55. reference = str(touchpoint.get("reference") or "")
  56. pins = touchpoint.get("pins", [])
  57. if not isinstance(pins, list):
  58. continue
  59. for pin in pins:
  60. if not isinstance(pin, Mapping) or not str(pin.get("number") or ""):
  61. continue
  62. position = pin.get("position")
  63. if not isinstance(position, Mapping):
  64. continue
  65. result.append(
  66. (
  67. reference,
  68. str(pin.get("number")),
  69. _normalized_net(pin.get("net")),
  70. float(position.get("x", 0.0)),
  71. float(position.get("y", 0.0)),
  72. )
  73. )
  74. return result
  75. def validate_ipcd356_alignment(
  76. board_data: Mapping[str, object],
  77. path: Path | str,
  78. *,
  79. tolerance_mm: float = DEFAULT_TOLERANCE_MM,
  80. ) -> dict[str, object]:
  81. if tolerance_mm <= 0:
  82. raise ValueError("tolerance_mm must be positive")
  83. records = _records(Path(path))
  84. pads = _numbered_pads(board_data)
  85. bucket_size = tolerance_mm
  86. buckets: dict[tuple[int, int], list[int]] = defaultdict(list)
  87. for index, record in enumerate(records):
  88. buckets[(round(record.x / bucket_size), round(record.y / bucket_size))].append(index)
  89. used: set[int] = set()
  90. failures: list[str] = []
  91. matched_types: Counter[str] = Counter()
  92. for reference, number, net, x, y in pads:
  93. center = (round(x / bucket_size), round(y / bucket_size))
  94. candidates: list[tuple[float, int, _Record]] = []
  95. for offset_x in (-1, 0, 1):
  96. for offset_y in (-1, 0, 1):
  97. for index in buckets.get((center[0] + offset_x, center[1] + offset_y), []):
  98. if index in used:
  99. continue
  100. record = records[index]
  101. distance = math.hypot(x - record.x, y - record.y)
  102. if distance <= tolerance_mm:
  103. candidates.append((distance, index, record))
  104. net_matches = [item for item in candidates if item[2].net == net]
  105. if not net_matches:
  106. nearby_nets = sorted({item[2].net or "N/C" for item in candidates})
  107. failures.append(
  108. f"{reference}.{number} at {x:.4f},{y:.4f} net={net or 'N/C'} nearby={nearby_nets}"
  109. )
  110. continue
  111. _, index, record = min(net_matches, key=lambda item: item[0])
  112. used.add(index)
  113. matched_types[record.record_type] += 1
  114. if failures:
  115. detail = "; ".join(failures[:10])
  116. raise IpCd356AlignmentError(
  117. f"D356 alignment failed for {len(failures)}/{len(pads)} numbered pads: {detail}"
  118. )
  119. return {
  120. "numbered_pads": len(pads),
  121. "matched_pads": len(pads),
  122. "record_types": {record_type: matched_types.get(record_type, 0) for record_type in ("317", "327")},
  123. "tolerance_mm": tolerance_mm,
  124. }