#!/usr/bin/env python3 """Validate physical references and prepare non-executing schema-1 material cards. JSON masters retain provenance, directional data, limits and unsupported quantities. No CAD document is opened, no body is assigned and no missing constant is invented. """ from __future__ import annotations import argparse from collections import Counter import hashlib import json import math from pathlib import Path import re import sys ROOT = Path(__file__).resolve().parents[4] PACK = ROOT / 'assets/render/physical' MAX_BYTES = 8 * 1024 * 1024 ID = re.compile(r'[a-z][a-z0-9-]{0,63}\Z') CORE = {'density','elasticity','tensile_strength','yield_strength','compressive_strength','shear_strength','thermal_conductivity','thermal_expansion','specific_heat'} PRESSURE = {'young_modulus','shear_modulus','tensile_strength','yield_strength','compressive_strength','shear_strength','flexural_strength','flexural_modulus','compressive_modulus','stress_at_strain','internal_bond_strength'} TEMPERATURE = {'glass_transition','melting_temperature','heat_deflection','service_temperature','decomposition_temperature'} DIMENSIONLESS = {'poisson_ratio','elongation_break','relative_permittivity','loss_tangent','water_absorption','hardness_shore_a','hardness_shore_d','hardness_brinell','hardness_knoop','specific_gravity','electrical_conductivity_iacs','refractive_index','porosity','void_ratio','thermal_emittance','solar_absorptance','thickness_swelling'} CONVERSIONS = { 'kg/m^3':('density',1.,0.), 'g/cm^3':('density',1000.,0.), 'lb/in^3':('density',27679.904710203,0.), 'Pa':('pressure',1.,0.), 'kPa':('pressure',1e3,0.), 'MPa':('pressure',1e6,0.), 'GPa':('pressure',1e9,0.), 'psi':('pressure',6894.757293168,0.), 'ksi':('pressure',6894757.293168,0.), '1':('ratio',1.,0.), '%':('ratio',.01,0.), 'W/(m K)':('conductivity',1.,0.), 'Btu/(h ft degF)':('conductivity',1.730734666371,0.), '1/K':('expansion',1.,0.), 'ppm/K':('expansion',1e-6,0.), '1/degF':('expansion',1.8,0.), 'J/(kg K)':('heat',1.,0.), 'J/(g K)':('heat',1000.,0.), 'Btu/(lb degF)':('heat',4186.8,0.), 'K':('temperature',1.,0.), 'degC':('temperature',1.,273.15), 'degF':('temperature',5/9,255.3722222222222), 'ohm m':('resistivity',1.,0.), 'ohm cm':('resistivity',.01,0.), 'microohm cm':('resistivity',1e-8,0.), 'ohm mm^2/m':('resistivity',1e-6,0.), 'V/m':('field',1.,0.), 'kV/mm':('field',1e6,0.), 'V/mil':('field',1/.0000254,0.), 'N':('force',1.,0.), 'N/m':('tear',1.,0.), 'pli':('tear',175.1268352465,0.), 'Pa sqrt(m)':('toughness',1.,0.), 'MPa sqrt(m)':('toughness',1e6,0.), 'm':('length',1.,0.), 'micrometre':('length',1e-6,0.), 'mil':('length',.0000254,0.), 'rad':('angle',1.,0.), 'degree':('angle',math.pi/180,0.)} QUANTITY = {q:('pressure','Pa') for q in PRESSURE} QUANTITY.update({q:('temperature','K') for q in TEMPERATURE}) QUANTITY.update({q:('ratio','1') for q in DIMENSIONLESS}) QUANTITY.update({'density':('density','kg/m^3'),'grain_density':('density','kg/m^3'), 'thermal_conductivity':('conductivity','W/(m K)'), 'thermal_expansion':('expansion','1/K'), 'specific_heat':('heat','J/(kg K)'), 'volume_resistivity':('resistivity','ohm m'), 'dielectric_strength':('field','V/m'), 'hardness_janka':('force','N'), 'tear_strength':('tear','N/m'), 'fracture_toughness':('toughness','Pa sqrt(m)'), 'mean_particle_size':('length','m'), 'dry_film_thickness':('length','m'), 'angle_of_repose':('angle','rad')}) class Invalid(ValueError): """A physical reference violates the reviewed contract.""" def require(ok, message): if not ok: raise Invalid(message) def unique(pairs): out = {} for key, value in pairs: require(key not in out, f'duplicate JSON field: {key}') out[key] = value return out def reject_constant(value): raise Invalid(f'non-finite JSON constant: {value}') def read(path): require(path.is_file() and not path.is_symlink(), f'expected regular input: {path.name}') require(path.stat().st_size <= MAX_BYTES, f'oversized input: {path.name}') raw = path.read_bytes();require(len(raw) <= MAX_BYTES, 'input grew beyond byte budget') data = json.loads(raw, object_pairs_hook=unique, parse_constant=reject_constant) require(isinstance(data, dict), 'expected JSON object') return data def text(value, label, limit=2048): require(isinstance(value,str) and 0 < len(value.encode('utf-8')) <= limit and not any(ord(c)<32 for c in value), f'invalid {label}') def number(value, low=-1e30, high=1e30): require(type(value) in (int,float) and low <= value <= high and math.isfinite(value), 'invalid bounded number') return float(value) def close(a,b): return math.isclose(a,b,rel_tol=2e-11,abs_tol=1e-14*max(abs(b),1e-20)) def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest() def encoded(value): return (json.dumps(value,ensure_ascii=True,indent=2,allow_nan=False)+'\n').encode() def check_conditions(c): base={'temperature_k','temperature_interval_k','moisture_dry_basis_kg_kg','strain_rate_per_s','state','direction','test_method'} numeric={'crosshead_speed_mm_min','frequency_hz','specimen_thickness_mm','engineering_strain','heating_rate_k_min', 'test_stress_pa','wavelength_nm','minimum_film_thickness_m','immersion_hours','specimen_mass_kg'} strings={'environment','thermal_regime','density_basis','excitation'} require(isinstance(c,dict) and base<=set(c)<=base|numeric|strings|{'lower_thickness_exclusive','thickness_range_mm'},'unknown or missing condition field') for key in numeric & set(c): number(c[key],0,1e18) for key in strings & set(c): text(c[key],key,256) if 'lower_thickness_exclusive' in c: require(type(c['lower_thickness_exclusive']) is bool,'thickness endpoint flag must be Boolean') if 'thickness_range_mm' in c: bounds=c['thickness_range_mm'] require(isinstance(bounds,list) and len(bounds)==2 and 0=0,'negative physical value') if q in TEMPERATURE|{'density','grain_density','young_modulus','shear_modulus','specific_heat','thermal_conductivity','relative_permittivity','refractive_index'}:require(v>0,'positive physical quantity required') if q in {'porosity','thermal_emittance','solar_absorptance'}:require(v<=1,'fraction above one') if q.startswith('hardness_shore_'):require(v<=100,'Shore hardness above 100') c=p['conditions'];check_conditions(c) for key in ['temperature_k','moisture_dry_basis_kg_kg','strain_rate_per_s']: require(key in c,'condition field must be explicit even when unknown') if c[key] is not None:number(c[key],0,1e12) if c.get('temperature_interval_k') is not None: interval=c['temperature_interval_k'];require(isinstance(interval,list) and len(interval)==2,'temperature interval shape') require(00,'physical requirements cannot be empty') refs=b.get('references');require(isinstance(refs,list) and len(refs)<=16,'reference list bounds');pairs=set() for ref in refs: require(ref.get('profile_id') in profiles,'unresolved physical reference');text(ref.get('relation'),'reference relationship',256) pair=(ref['profile_id'],ref['relation']);require(pair not in pairs,'duplicate reference');pairs.add(pair) require(b.get('status')==('reference_selection_required' if refs else 'specific_recipe_required'),'status conflicts with references') checked[id]=b surface_ids=set();originals={s['id']:s for s in authorities['surfaces']} for s in binding['surfaces']: id=s.get('surface_id');require(id in originals and id not in surface_ids,'invalid surface ID');original=originals[id] require(s.get('catalog_ids')==original['catalog_ids']==s.get('physical_binding_ids'),'surface physical association drift') require(s.get('name')==original['name'] and s.get('auto_assign_body') is False and s.get('preserve_existing_material') is True,'surface scope/name mismatch') first=checked[original['catalog_ids'][0]] require(s.get('status')==first['status'] and s.get('physical_role')==first['physical_role'],'surface status/role drift');surface_ids.add(id) return profiles,sources def load(): data,sources,binding,registry=[read(PACK/name) for name in ('profiles.json','sources.json','bindings.json','quantities.json')] profiles,source_map=validate_data(data,sources,binding,registry) return profiles,source_map,binding def native_condition(p,r): c=r['conditions'];extra={k:v for k,v in c.items() if k not in {'state','temperature_k','moisture_dry_basis_kg_kg','strain_rate_per_s'} and v is not None} state=c['state']+' | '+r['qualifier']+' reference; source review required; not design allowables.' if extra:state+=' | '+json.dumps(extra,sort_keys=True,separators=(',',':')) if r['uncertainty'] is not None:state+=' | Reported uncertainty retained in extended profile.' if r['qualifier']=='derived':state+=' | Derived value; formula retained in extended profile.' require(len(state.encode())<=1024,'native condition overflow') return {k:c[k] for k in ('temperature_k','moisture_dry_basis_kg_kg','strain_rate_per_s')}|{'state':state} def native_card(p,sources): selected=[];used=set();properties=p['properties'];by_q={} for r in properties:by_q.setdefault(r['quantity'],[]).append(r) def point(q): rows=by_q.get(q,[]) if len(rows)!=1:return None r=rows[0] return r if type(r['value']) in (int,float) and r['qualifier'] in {'typical','derived'} and r['conditions']['direction'] in {'not_reported','isotropic'} else None def add(r,data,extra=()): selected.append({'data':data,'source_id':r['source_id'],'conditions':native_condition(p,r)}) used.add(r['id']);used.update(extra) rho=point('density') if rho:add(rho,{'kind':'density','kg_m3':rho['value']}) cp=point('specific_heat') if cp:add(cp,{'kind':'specific_heat','j_kg_k':cp['value']}) for q in ('tensile_strength','yield_strength','compressive_strength','shear_strength'): r=point(q) if r:add(r,{'kind':q,'pa':r['value']}) if p['isotropic_reference_model']: e,nu=point('young_modulus'),point('poisson_ratio') if e and nu: keys=('temperature_k','temperature_interval_k','moisture_dry_basis_kg_kg','strain_rate_per_s','state','direction','environment','thermal_regime','specimen_thickness_mm','heating_rate_k_min') require(e['source_id']==nu['source_id'] and all(e['conditions'].get(k)==nu['conditions'].get(k) for k in keys),'mixed elastic source/conditions') require(-1