Files
2026-09-24 10:40:57 +08:00

82 lines
3.8 KiB
Python

"""Offline STEP comparison. Reference geometry is never sent to a model."""
import argparse
import itertools
import json
from pathlib import Path
from build123d import Compound, Pos, Rot, Solid, import_step
def flat_geometry(shape):
# STEP assemblies keep a display tree in children. Boolean operations must
# use the located BRep solids, not the original child locations in that tree.
solids = [Solid(solid.wrapped) for solid in shape.solids()]
return solids[0] if len(solids) == 1 else Compound(solids)
def centered(shape):
box = shape.bounding_box()
translation = [-value for value in (box.min + box.max) * .5]
return flat_geometry(Pos(*translation) * shape), translation
def orthogonal_rotations():
seen = set()
for angles in itertools.product((0, 90, 180, 270), repeat=3):
rotation = Rot(*angles)
transform = rotation.wrapped.Transformation()
key = tuple(round(transform.Value(i, j), 6) for i in range(1, 4) for j in range(1, 4))
if key not in seen:
seen.add(key)
yield angles, rotation
def compare_step_files(reference_file, candidate_file):
expected, reference_translation = centered(import_step(str(reference_file)))
actual, candidate_translation = centered(import_step(str(candidate_file)))
expected_sizes = list(expected.bounding_box().size)
options = []
for angles, rotation in orthogonal_rotations():
oriented = flat_geometry(rotation * actual)
sizes = list(oriented.bounding_box().size)
error = sum(((a-b)/b)**2 for a, b in zip(sizes, expected_sizes))
options.append((error, angles, oriented))
minimum = min(item[0] for item in options)
scores = []
for error, angles, oriented in options:
if error > minimum + 1e-10:
continue
overlap = oriented & expected
shared = overlap.volume if overlap is not None else 0
union = actual.volume + expected.volume - shared
scores.append({'rotation_xyz_degrees': list(angles), 'volume_iou': shared / union})
best = max(scores, key=lambda item: item['volume_iou'])
return {'reference_file': str(reference_file), 'candidate_file': str(candidate_file),
'reference_volume_mm3': expected.volume, 'candidate_volume_mm3': actual.volume,
'volume_relative_error': abs(actual.volume - expected.volume) / expected.volume,
'reference_bbox_mm': expected_sizes, 'candidate_bbox_mm': list(actual.bounding_box().size),
'candidate_solid_count': len(actual.solids()), 'candidate_valid': bool(actual.is_valid),
'reference_translation_mm': reference_translation, 'candidate_translation_mm': candidate_translation,
'best_axis_aligned_volume_iou': best['volume_iou'], 'tested_orientations': scores,
'best_rotation_xyz_degrees': best['rotation_xyz_degrees'],
'alignment': '包络中心平移对齐;从24种正交旋转中选择包络轴向最匹配的旋转并取最大体积交并比;无缩放、无镜像。',
'limitation': '该分数不是还原准确率,不能替代孔槽、局部尺寸及图纸验收;不搜索任意角度或任意平移。'}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--reference', type=Path, required=True)
parser.add_argument('--candidate', type=Path, action='append', required=True)
parser.add_argument('--output', type=Path)
args = parser.parse_args()
results = [compare_step_files(args.reference, candidate) for candidate in args.candidate]
text = json.dumps(results, ensure_ascii=False, indent=2)
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(text, encoding='utf-8')
print(text)
if __name__ == '__main__':
main()