generate_mrdimm_assets_native.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. #!/usr/bin/env python3
  2. """Regenerate MR viewer assets from the BRD parser; no KiCad/IPC claim.
  3. Install beside generate_v2_0_assets.py and pass the independently extracted
  4. MRDIMM main_pins.csv. Geometry is a simplified viewer representation.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import csv
  9. from collections import Counter
  10. from datetime import datetime, timezone
  11. import json
  12. from pathlib import Path
  13. import platform
  14. import tempfile
  15. from jsonschema import Draft202012Validator
  16. import generate_v2_0_assets as native
  17. from board_viewer.assets import validate_generated_bundle
  18. from board_viewer.data import build_board_data
  19. from board_viewer.generator import _publish_directory
  20. ROOT = Path(__file__).resolve().parents[2]
  21. VIEWER = ROOT / 'tools/board-viewer'
  22. ASSETS = ['board-data.json', 'import-report.json', 'board-mask-edge.svg',
  23. 'board-mask-edge-back.svg', 'board-copper.svg', 'board-copper-back.svg',
  24. 'board-silkscreen.svg', 'board-silkscreen-back.svg']
  25. def read(path):
  26. return json.loads(path.read_text(encoding='utf-8'))
  27. def write(path, value):
  28. path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
  29. def source(path):
  30. return {'path': str(path.relative_to(ROOT)), 'sha256': native.sha256_file(path)}
  31. def main():
  32. parser = argparse.ArgumentParser(description=__doc__)
  33. parser.add_argument('--pins', type=Path, required=True, help='Independent native MR placed-pad CSV')
  34. args = parser.parse_args()
  35. brd = ROOT / 'reference/original/board/FCB_FPGA_MCU_V1.2_20260717/FCB_FPGA+MCU_V1.2_20260717.brd'
  36. annotations_path = ROOT / 'config/board_viewer_annotations.fcb_fpga_mcu_v1_2.json'
  37. inventory_path = ROOT / 'config/pin_inventory.fcb_fpga_mcu0611.json'
  38. data_schema = ROOT / 'schemas/board_viewer_data.schema.json'
  39. annotation_schema = ROOT / 'schemas/board_viewer_annotations.schema.json'
  40. build_schema = ROOT / 'schemas/board_viewer_build_info.schema.json'
  41. assert native.sha256_file(brd) == '269b5bab2f2e1215b9392079a003badc34238ae3cbe8e5094c9a11bba8b84ebb'
  42. annotations = read(annotations_path)
  43. Draft202012Validator(read(annotation_schema)).validate(annotations)
  44. board, geometry = native.parse_allegro_brd(brd)
  45. # This exact MR BRD has no outline recognized by the pattern parser. Its
  46. # generic 430x60 fallback clips real components (e.g. R568 y=-67.275).
  47. # Retain the same-BRD historical SVG envelope. These two archived files
  48. # match each other; the subsequently edited historical board-data does not.
  49. # This run does not decode a native outline or prove exact pad geometry.
  50. historical_dir = ROOT / 'evidence/hardware/20261023/mrdimm/historical-viewer-outline'
  51. historical_info = historical_dir / 'build-info.json'
  52. historical_outline = historical_dir / 'board-mask-edge.svg'
  53. assert native.sha256_file(historical_info) == '128bc9cbd79a0f83432f7cee8cb8a9298f5b5e625d8d9cbe2574bed0e50e2c7e'
  54. assert native.sha256_file(historical_outline) == '72af48fddb6914cee8b592ac17cd8d610fb62988ddc4f4959138e44482b9ac90'
  55. parsed_bounds = dict(board.bounds)
  56. assert parsed_bounds == {'x': 0.0, 'y': -60.0, 'width': 430.0, 'height': 60.0}
  57. board.bounds = {'x': 0.0, 'y': -75.0, 'width': 430.0, 'height': 75.0}
  58. bounds_provenance = {
  59. 'source': 'Historical KiCad SVG and its matching build-info, same BRD SHA; not a current native outline extraction',
  60. 'historical_outline': source(historical_outline),
  61. 'historical_build_info': source(historical_info),
  62. 'historical_svg_size_mm': {'width': 429.9966, 'height': 74.9808},
  63. 'historical_build_info_generated_at': '2026-10-14T06:57:25',
  64. 'historical_recorded_toolchain': {'python': '3.11.6', 'kicad': '10.0.4'},
  65. 'native_outline_detected': False,
  66. 'parser_fallback_bounds': parsed_bounds,
  67. 'applied_view_envelope': dict(board.bounds),
  68. 'limits': 'Historical display-envelope dimensions only; this run does not verify the physical board edge or exact pad shape/position.',
  69. }
  70. # Bind component values to the independently decoded complete native BOM.
  71. # A profile with an empty expected value must be corrected from that BOM;
  72. # annotation value validation remains strict.
  73. bom_path = args.pins.resolve().with_name('main_bom.csv')
  74. with bom_path.open(encoding='utf-8', newline='') as stream:
  75. bom_rows = list(csv.DictReader(stream))
  76. bom_by_ref = {row['reference']: row for row in bom_rows}
  77. board_refs = [fp.reference for fp in board.footprints]
  78. assert len(bom_rows) == len(bom_by_ref) == len(board_refs) == len(set(board_refs)) == 1317
  79. assert set(bom_by_ref) == set(board_refs), 'Native BOM/reference coverage mismatch'
  80. assert all('value' in row and row.get('footprint') for row in bom_rows)
  81. for fp in board.footprints:
  82. fp.component_value = bom_by_ref[fp.reference]['value']
  83. actual_rows = [(fp.reference, str(pad.number), pad.net or '') for fp in board.footprints for pad in fp.pads]
  84. with args.pins.open(encoding='utf-8', newline='') as stream:
  85. expected_rows = [(r['reference'], r['pin'], r['net']) for r in csv.DictReader(stream)]
  86. # Keep every numbered pad (even NC) and every named net. Only entries with
  87. # neither a number nor a net are outside this electrical comparison. The
  88. # pattern parser includes two extra such Q52 geometry entries; they are not
  89. # independently verified pads and must not be counted as electrical matches.
  90. actual = Counter(row for row in actual_rows if row[1] or row[2])
  91. expected = Counter(row for row in expected_rows if row[1] or row[2])
  92. assert actual == expected, f'Native pad mismatch: missing={list((expected-actual).items())[:10]}, extra={list((actual-expected).items())[:10]}'
  93. assert len(board.footprints) == 1317 and len(expected_rows) == 3694
  94. assert sum(expected.values()) == 3686
  95. geometry_counts = {
  96. 'viewer_all_pad_entries': len(actual_rows),
  97. 'independent_csv_rows': len(expected_rows),
  98. 'viewer_unnumbered_unconnected_by_ref': dict(Counter(row[0] for row in actual_rows if not row[1] and not row[2])),
  99. 'independent_unnumbered_unconnected_by_ref': dict(Counter(row[0] for row in expected_rows if not row[1] and not row[2])),
  100. 'excluded_geometry_is_not_electrically_verified': True,
  101. }
  102. payload = build_board_data(board, read(inventory_path), annotations, board_name='FCB FPGA+MCU V1.2 20260717')
  103. Draft202012Validator(read(data_schema)).validate(payload)
  104. counts = payload['counts']
  105. assert {k: counts[k] for k in ('touchpoints', 'pads', 'resistors', 'resistor_pads')} == {'touchpoints': 118, 'pads': 629, 'resistors': 644, 'resistor_pads': 1288}
  106. # Existing production MR annotation has no photographic overlay. If that
  107. # changes, use the normal photo-aware generator rather than dropping it.
  108. assert payload.get('photo_overlay') is None
  109. stamp = datetime.now(timezone.utc).isoformat()
  110. with tempfile.TemporaryDirectory(prefix='prod2u-mrdimm-native-') as directory:
  111. out = Path(directory)
  112. write(out / 'board-data.json', payload)
  113. native.generate_svg_layers_from_brd(board, geometry, 'FCB FPGA+MCU V1.2 20260717', payload['touchpoints'], out)
  114. write(out / 'import-report.json', {
  115. 'source_file': brd.name, 'source_format': 'allegro_brd', 'output_file': 'board-data.json',
  116. 'status': 'success', 'errors': [], 'timestamp': stamp,
  117. 'native_pin_comparison': {'status': 'pass', 'independent_csv_sha256': native.sha256_file(args.pins), 'scope': 'All numbered pads including NC, plus any unnumbered entry with a named net; tuple multiplicity must match', 'electrical_pad_entries': sum(expected.values()), 'unique_ref_pin_net': len(expected), 'missing': 0, 'extra': 0},
  118. 'geometry_entry_counts': geometry_counts,
  119. 'view_bounds_provenance': bounds_provenance,
  120. 'native_component_inventory': {'status': 'pass', 'independent_csv_sha256': native.sha256_file(bom_path), 'references': len(bom_rows), 'reference_coverage': 'exact', 'value_source': 'independent native BOM value column', 'footprint_package_names': 'Preserved in the source BOM; this simplified viewer model has no footprint-package field.'},
  121. 'limits': 'Independent native CSV comparison covers ref/pin/net only. Geometry is simplified; no KiCad import or IPC-D-356 comparison was run.'})
  122. info = {
  123. 'schema': 'board-viewer-build-info-v1', 'generated_at': stamp, 'generator_version': '2.1.0',
  124. 'toolchain': {'python': platform.python_version(), 'kicad': 'not_used'},
  125. 'sources': {**native._generator_sources(), 'generator_mrdimm_native': source(Path(__file__).resolve()),
  126. 'brd': source(brd), 'annotations': source(annotations_path), 'inventory': source(inventory_path),
  127. 'native_pins': source(args.pins.resolve()), 'native_bom': source(bom_path),
  128. 'historical_mrdimm_outline': source(historical_outline), 'historical_mrdimm_build_info': source(historical_info),
  129. 'schema_data': source(data_schema), 'schema_annotations': source(annotation_schema), 'schema_build_info': source(build_schema)},
  130. 'assets': {name: {'sha256': native.sha256_file(out/name), 'bytes': (out/name).stat().st_size} for name in ASSETS},
  131. 'verification': {
  132. 'ipcd356': {'status': 'not_run', 'reason': 'Native BRD parser and independent native CSV comparison used; no IPC-D-356 export or comparison executed.'},
  133. 'side_views': {'front_layers': ['board-mask-edge.svg', 'board-silkscreen.svg', 'board-copper.svg'],
  134. 'back_layers': ['board-mask-edge-back.svg', 'board-silkscreen-back.svg', 'board-copper-back.svg'],
  135. 'back_mirror_axis': 'y', 'back_svg_export_mirrored': True,
  136. 'convention': 'Native-parser simplified SVGs; back view mirrored about Y. This is not a KiCad export or exact CAD rendering.'}},
  137. 'counts': {key: counts[key] for key in ('footprints', 'touchpoints', 'pads', 'resistors', 'resistor_pads')}}
  138. Draft202012Validator(read(build_schema)).validate(info)
  139. write(out / 'build-info.json', info)
  140. result = validate_generated_bundle(out, repository_root=ROOT)
  141. assert result.status == 'pass', {'status': result.status, 'asset_errors': result.asset_errors, 'stale_sources': result.stale_sources}
  142. _publish_directory(out, VIEWER/'generated')
  143. print(json.dumps({'status': 'pass', 'output_dir': str(VIEWER/'generated'), 'counts': info['counts'], 'toolchain': info['toolchain'], 'ipcd356': 'not_run'}, ensure_ascii=False))
  144. if __name__ == '__main__':
  145. main()