MateuszBocko's picture
Initial | Project Setup
6237959 verified
Raw History Blame Contribute Delete
9.58 kB
"""Checks exchanged CAD solids, the video corrections and all GLB buffers."""
from pathlib import Path
from collections import Counter
import hashlib,json,struct,gc
import numpy as np
import cadquery as cq
import build_orcasat as b
def correction_checks():
parts=b.PARTS
stowed=[p for p in parts if b.visible(p,'stowed','full')]
css=Counter(p.name.split('_')[0] for p in stowed if '_Coarse_Sun_Sensor_' in p.name)
assert css=={'Nadir':1,'Zenith':1,'Starboard':2,'Port':2,'Ram':2,'Wake':2},css
zenith_css=next(p for p in parts if p.name=='Zenith_Coarse_Sun_Sensor_1')
solar=[p for p in parts if p.name.startswith('Zenith_Solar_Cell_') and not p.name.endswith('Bond_Land') and p.name[-1].isdigit()]
assert all(zenith_css.shape.intersect(p.shape).Volume()<1e-6 for p in solar)
src=[p for p in stowed if p.name.startswith('Original_Antenna_')]
assert sum(len(p.shape.Solids()) for p in src)==162
assert len([p for p in src if '10056_1' in p.name])==2
assert len([p for p in src if 'Line_Antenna_Deployer' in p.name])==2
antenna_board=next(p for p in src if p.name.startswith('Original_Antenna_001_'))
side_frames=[p for p in parts if p.name.startswith('Machined_Side_Ladder')]
native_frame_overlap=sum(antenna_board.shape.intersect(p.shape).Volume() for p in side_frames)
assert native_frame_overlap<1e-5, native_frame_overlap
assert not any(p.name.startswith('Copper_Ballast_Visual') for p in parts)
fss=next(p for p in parts if p.name=='Zenith_FSS_Internal_PCBA')
assert fss.shape.BoundingBox().ymin>-47.8
lens=next(p for p in parts if p.name=='Zenith_FSS_Lens')
assert lens.shape.BoundingBox().ymax<-49.4
ballast=next(p for p in parts if p.name=='Nadir_Copper_Ballast')
usb_witness=b.facet_shape(b.box(8,5,2,(8,33.5,-1.0)),'Nadir')
assert ballast.shape.intersect(usb_witness).Volume(1e-8)<1e-5
assert sum('Kapton' in p.name for p in parts)>=7
assert sum('Ribbon' in p.name and p.group=='09_Harness' for p in parts)>=3
rail=cq.Compound.makeCompound([p.shape for p in parts if p.name.startswith('Rail_')]).BoundingBox()
assert np.allclose([rail.xlen,rail.ylen,rail.zlen],[100,100,227],atol=1e-5)
return {'CSS_per_face':dict(css),'native_antenna_solids_stowed':162,'native_antenna_burn_wire_boards':2,'native_antenna_PCB_vs_side_frame_overlap_mm3':native_frame_overlap,'native_retention_lines_stowed':2,'FSS_internal_electronics_and_external_optics':True,'ballast_faces_and_USB_clearance':True,'rail_envelope_mm':[100,100,227]}
def _step_worker(path_string):
path=Path(path_string)
text=path.read_text(errors='replace');header=text[:3000]
shape=cq.importers.importStep(str(path)).val()
assert shape.isValid(),path
solids=shape.Solids();assert solids,path
schema='AP203' if 'CONFIG_CONTROL_DESIGN' in header else 'AP214' if 'AUTOMOTIVE_DESIGN' in header else None
assert schema,path
assert 'SI_UNIT(.MILLI.,.METRE.)' in text.replace(' ',''),path
bb=shape.BoundingBox()
# Adaptive integration is invariant enough for source-vs-STEP comparison;
# the default fixed quadrature varied by 2.3 ppm on this complex assembly.
r={'schema':schema,'solids':len(solids),'valid':True,'units':'mm','colour_records':text.count('COLOUR_RGB('),'bbox_mm':[bb.xmin,bb.xmax,bb.ymin,bb.ymax,bb.zmin,bb.zmax],'volume_mm3':shape.Volume(1e-8),'volume_integration_eps':1e-8,'default_fixed_quadrature_volume_mm3':shape.Volume()}
return r
def validate_steps(out):
from concurrent.futures import ProcessPoolExecutor,as_completed
from multiprocessing import get_context
import tempfile
out=Path(out);cache=Path(tempfile.gettempdir())/'orcasat_step_validation_v2_eps1e-8';cache.mkdir(exist_ok=True)
paths=sorted(list(out.glob('*.step'))+list((out/'modules').glob('*.step'))+list((out/'compatibility').glob('*.step')))
byhash={};records={};digest_for={}
for path in paths:
digest=hashlib.sha256(path.read_bytes()).hexdigest();digest_for[path]=digest
byhash.setdefault(digest,path)
jobs={}
with ProcessPoolExecutor(max_workers=2,mp_context=get_context('spawn')) as pool:
for digest,path in byhash.items():
cached=cache/(digest+'.json')
if cached.exists():records[digest]=json.loads(cached.read_text());continue
jobs[pool.submit(_step_worker,str(path))]=(digest,path)
for future in as_completed(jobs):
digest,path=jobs[future];record=future.result();records[digest]=record
(cache/(digest+'.json')).write_text(json.dumps(record,indent=2))
print('STEP checked',path.name,record['solids'],'solids',flush=True)
result=[]
for path in paths:
digest=digest_for[path];result.append(dict(records[digest],path=str(path.relative_to(out)),sha256=digest))
# Persist measured results before any comparison can fail, so diagnostics
# never require repeating successful imports of unchanged files.
(out/'step_roundtrip_measurements.json').write_text(json.dumps(result,indent=2))
vol_cache={id(p):b.body_axes(p.shape).Volume(1e-8) for p in b.PARTS}
for filename,state,view in [('ORCASat_Stowed.step','stowed','full'),('ORCASat_Deployed.step','deployed','full'),('ORCASat_Internal.step','stowed','internal'),('ORCASat_Exploded.step','deployed','exploded')]:
got=next(x for x in result if x['path']==filename)
selected=[p for p in b.PARTS if b.visible(p,state,view)]
expected=sum(len(p.shape.Solids()) for p in selected)
volume=sum(vol_cache[id(p)] for p in selected)
got['source_volume_mm3']=volume
got['volume_difference_mm3']=got['volume_mm3']-volume
got['volume_relative_error']=abs(got['volume_difference_mm3'])/volume
assert got['solids']==expected,(filename,got['solids'],expected)
print('Volume comparison',filename,'relative error',got['volume_relative_error'],flush=True)
(out/'step_roundtrip_measurements.json').write_text(json.dumps(result,indent=2))
assert np.isclose(got['volume_mm3'],volume,rtol=1e-6), (filename,got['volume_mm3'],volume,got['volume_relative_error'])
assert got['colour_records']>0,filename
return result
def read_glb(path):
raw=Path(path).read_bytes();magic,version,length=struct.unpack_from('<4sII',raw)
assert magic==b'glTF' and version==2 and length==len(raw),path
jl,jt=struct.unpack_from('<I4s',raw,12);assert jt==b'JSON'
doc=json.loads(raw[20:20+jl]);off=20+jl
bl,bt=struct.unpack_from('<I4s',raw,off);assert bt==b'BIN\0' and off+8+bl==len(raw)
binary=raw[off+8:];assert doc['buffers'][0]['byteLength']<=len(binary)
arrays=[]
for ac in doc['accessors']:
bv=doc['bufferViews'][ac['bufferView']];start=bv.get('byteOffset',0)+ac.get('byteOffset',0)
n=ac['count']*{'VEC3':3,'SCALAR':1}[ac['type']]
dtype={5126:'<f4',5125:'<u4'}[ac['componentType']]
assert start+n*4<=bv.get('byteOffset',0)+bv['byteLength']<=len(binary)
a=np.frombuffer(binary,dtype=dtype,count=n,offset=start)
if ac['type']=='VEC3':a=a.reshape(-1,3)
assert np.isfinite(a).all()
arrays.append(a)
mesh_triangles=0
for mesh in doc['meshes']:
for p in mesh['primitives']:
v=arrays[p['attributes']['POSITION']];n=arrays[p['attributes']['NORMAL']];idx=arrays[p['indices']]
assert len(v)==len(n)>0 and len(idx)%3==0 and idx.max()<len(v)
assert np.allclose(np.linalg.norm(n,axis=1),1,atol=1e-4)
assert np.max(np.abs(v))<1, 'Geometry appears not to use metres'
mesh_triangles+=len(idx)//3
for node in doc['nodes']:
if 'mesh' in node:assert node['mesh']<len(doc['meshes'])
for k in node.get('children',[]):assert k<len(doc['nodes'])
return doc,mesh_triangles
def validate_glbs(target,manifest,inventory=None):
defined={r['component'] for r in inventory} if inventory is not None else {p.name for p in b.PARTS}
partnames={r['component'] for r in manifest['items'] if r['kind']=='part'}
assert defined==partnames
expected_solids=sum(int(r['solids']) for r in inventory) if inventory is not None else sum(len(p.shape.Solids()) for p in b.PARTS)
assert len([r for r in manifest['items'] if r['kind']=='solid'])==expected_solids
assert len(list(target.rglob('*.glb')))==len(manifest['files'])
maximum=0
for i,row in enumerate(manifest['files']):
path=target/row['path'];assert hashlib.sha256(path.read_bytes()).hexdigest()==row['sha256']
doc,n=read_glb(path);maximum=max(maximum,n)
if i%500==0:print('Validate GLB',i+1,'/',len(manifest['files']),flush=True)
# Independent consumer verifies hierarchy/transforms, not just our file parser.
import trimesh
scenes=[]
for path in sorted((target/'assemblies').glob('*.glb'))+sorted((target/'modules').glob('*.glb'))+sorted((target/'panels').glob('*.glb')):
scene=trimesh.load(path,force='scene',process=False)
assert scene.geometry and len(scene.graph.nodes_geometry)>0
bounds=np.asarray(scene.bounds);assert np.isfinite(bounds).all()
assert np.max(bounds[1]-bounds[0])<1
scenes.append({'path':str(path.relative_to(target)),'mesh_nodes':len(scene.graph.nodes_geometry),'bbox_m':bounds.tolist()})
return {'all_files_validated':len(manifest['files']),'parts_covered':len(partnames),'solids_covered':expected_solids,'independent_loader':'trimesh '+trimesh.__version__,'independently_loaded_scenes':scenes,'maximum_triangles_in_one_file':maximum}