"""Exploratory paired-wall probe on two conforming meshes of analytic solids. Axis-aligned rectangular support is an explicit restriction, not a general mid-surface extractor. Geometry labels are used for evaluation only. """ import argparse from collections import defaultdict from contextlib import contextmanager import hashlib import itertools import json from pathlib import Path import resource import time import numpy as np TOL = 1e-8 OFFSET = 1e-6 ANGLE_COS = float(np.cos(np.deg2rad(5.))) GRID = .5 def save(path, obj): Path(path).write_text(json.dumps(obj, indent=2, allow_nan=False) + '\n') @contextmanager def timed(records, key): cpu, wall = time.process_time(), time.monotonic() yield records[key] = {'cpu_seconds': time.process_time()-cpu, 'wall_seconds': time.monotonic()-wall, 'process_peak_rss_bytes': resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024} def shape(name): # Boxes define physical ground truth, never a flow field. boxes = { 'plate': [([0, 0, 0], [8, 6, 1])], 'u_gap': [([0, 0, 0], [2.5, 4, 1]), ([0, 0, 1], [1, 4, 6]), ([1.5, 0, 1], [2.5, 4, 6])], 't_rib': [([0, 0, 0], [8, 4, 1]), ([3, 0, 1], [5, 4, 2]), ([3.5, 0, 2], [4.5, 4, 5])], }[name] cells = set() for low, high in boxes: for c in itertools.product(*(range(round(a/GRID), round(b/GRID)) for a, b in zip(low, high))): cells.add(c) return sorted(cells) def make_mesh(cells, variant): points, indices, tets, owners = [], {}, [], [] def index(c): c = tuple(c) if c not in indices: indices[c] = len(points) points.append(np.array(c)*GRID) return indices[c] # Freudenthal triangulation, globally reflect local x for the second mesh. # Consistent on every shared face; the surface geometry is identical. for cell_id, cell in enumerate(cells): for perm in itertools.permutations(range(3)): vertices = [np.zeros(3, dtype=int)] for axis in perm: v = vertices[-1].copy(); v[axis] = 1; vertices.append(v) if variant: for v in vertices: v[0] = 1-v[0] tets.append([index(np.array(cell)+v) for v in vertices]); owners.append(cell_id) return np.array(points), np.array(tets), np.array(owners) def wall_anchors(cells): present = set(cells); anchors, normals, tiles = [], [], [] for cell in cells: low = np.array(cell)*GRID for axis in range(3): for sign in [-1, 1]: nb = list(cell); nb[axis] += sign if tuple(nb) in present: continue p = low+GRID/2; p[axis] = low[axis]+(GRID if sign == 1 else 0) n = np.zeros(3); n[axis] = sign anchors.append(p); normals.append(n); tiles.append(low) return np.array(anchors), np.array(normals), np.array(tiles) class Mesh: def __init__(self, x, tet): self.x, self.tet = x, tet self.p = x[tet] matrices = np.transpose(self.p[:, 1:]-self.p[:, :1], (0, 2, 1)) self.volumes = abs(np.linalg.det(matrices))/6 assert np.all(self.volumes > 0) self.inverse = np.linalg.inv(matrices) faces, opposite = [], [] for k in range(4): faces.append(tet[:, [i for i in range(4) if i != k]]) opposite.append(tet[:, k]) faces, opposite = np.concatenate(faces), np.concatenate(opposite) _, idx, counts = np.unique(np.sort(faces, axis=1), axis=0, return_index=True, return_counts=True) assert np.all(counts <= 2), 'nonmanifold volume face' idx = idx[counts == 1]; self.faces = faces[idx]; tri = x[self.faces] n = np.cross(tri[:, 1]-tri[:, 0], tri[:, 2]-tri[:, 0]) wrong = np.einsum('ij,ij->i', n, x[opposite[idx]]-tri[:, 0]) > 0 n[wrong] *= -1; self.normals = n/np.linalg.norm(n, axis=1)[:, None] self.tri = tri self.e1, self.e2 = tri[:, 1]-tri[:, 0], tri[:, 2]-tri[:, 0] # Connected coplanar triangles, not semantic plate/rib labels. parent = list(range(len(tri))) def find(i): while parent[i] != i: parent[i] = parent[parent[i]]; i = parent[i] return i edges = defaultdict(list) for i, f in enumerate(self.faces): for a, b in itertools.combinations(f, 2): edges[tuple(sorted((int(a), int(b))))].append(i) assert all(len(v) == 2 for v in edges.values()), 'boundary not closed manifold' for group in edges.values(): a, b = group if np.dot(self.normals[a], self.normals[b]) > 1-TOL: parent[find(a)] = find(b) roots = [find(i) for i in range(len(tri))] self.patch = np.unique(roots, return_inverse=True)[1] self.patches = [] for k in range(self.patch.max()+1): ids = np.flatnonzero(self.patch == k); pts = tri[ids].reshape(-1, 3) low, high = pts.min(0), pts.max(0); axis = int(np.argmax(abs(self.normals[ids[0]]))) area = np.linalg.norm(np.cross(self.e1[ids], self.e2[ids]), axis=1).sum()/2 lateral = [j for j in range(3) if j != axis] rectangular = abs(area-np.prod((high-low)[lateral])) <= TOL*max(1, area) self.patches.append({'axis': axis, 'low': low, 'high': high, 'rectangular': rectangular, 'span': (high-low)[lateral]}) def hit(self, origin, direction): h = np.cross(np.broadcast_to(direction, self.e2.shape), self.e2) det = np.einsum('ij,ij->i', self.e1, h) ok = abs(det) > 1e-12 inv = np.divide(1., det, out=np.zeros_like(det), where=ok) s = origin-self.tri[:, 0] u = inv*np.einsum('ij,ij->i', s, h) q = np.cross(s, self.e1) v = inv*(q@direction) distance = inv*np.einsum('ij,ij->i', self.e2, q) ok &= (u >= -TOL) & (v >= -TOL) & (u+v <= 1+TOL) & (distance > TOL) ids = np.flatnonzero(ok) if not len(ids): return None d = distance[ids].min(); ties = ids[abs(distance[ids]-d) < TOL] if len(np.unique(self.patch[ties])) != 1: return None # A true edge/corner hit has ambiguous normal. i = int(ties[0]); return origin+d*direction, i def chord_inside(self, a, b): # Intersect the line parameter interval with EACH original tetrahedron. l0 = np.einsum('tij,tj->ti', self.inverse, a-self.p[:, 0]) dl = np.einsum('tij,j->ti', self.inverse, b-a) l0 = np.column_stack([1-l0.sum(1), l0]); dl = np.column_stack([-dl.sum(1), dl]) lo, hi = np.zeros(len(self.tet)), np.ones(len(self.tet)) valid = np.ones(len(self.tet), dtype=bool) for j in range(4): moving = abs(dl[:, j]) > 1e-13 bound = np.divide(-TOL-l0[:, j], dl[:, j], out=np.zeros(len(dl)), where=moving) lo = np.where(moving & (dl[:, j] > 0), np.maximum(lo, bound), lo) hi = np.where(moving & (dl[:, j] < 0), np.minimum(hi, bound), hi) valid &= moving | (l0[:, j] >= -TOL) valid &= lo <= hi intervals = sorted(zip(lo[valid], hi[valid])); end = 0. for left, right in intervals: if left > end+TOL: return False end = max(end, right) if end >= 1-TOL: return True return False def pair(mesh, anchors, normals, tiles): records, prisms = [], [] for i, (a, n, tile) in enumerate(zip(anchors, normals, tiles)): r = {'anchor': i, 'a': a.tolist(), 'normal': n.tolist(), 'paired': False, 'sheet_support': False, 'reason': 'NO_HIT'} source = mesh.hit(a-OFFSET*n, n); target = mesh.hit(a-OFFSET*n, -n) if source is None or target is None: records.append(r); continue b, face = target; _, src = source p, q = int(mesh.patch[src]), int(mesh.patch[face]); h = float(np.linalg.norm(b-a)) r.update(b=b.tolist(), thickness=h, patches=[p, q]) reverse = mesh.hit(b-OFFSET*mesh.normals[face], -mesh.normals[face]) if p == q or np.dot(n, mesh.normals[face]) > -ANGLE_COS: r['reason'] = 'NORMAL_OR_PATCH' elif reverse is None or np.linalg.norm(reverse[0]-a) > 1e-5: r['reason'] = 'REVERSE_MISMATCH' elif not mesh.chord_inside(a, b): r['reason'] = 'CHORD_OUTSIDE' else: r.update(paired=True, reason='PAIRED_ONLY') pa, pb = mesh.patches[p], mesh.patches[q] # Deliberately narrow eligibility: rectangular, planar opposed walls, # thickness <= half the smallest lateral patch extent. if pa['rectangular'] and pb['rectangular'] and h <= .5*min(*pa['span'], *pb['span'])+TOL: axis = pa['axis']; low, high = tile.copy(), tile+GRID low[axis], high[axis] = min(a[axis], b[axis]), max(a[axis], b[axis]) # Entire prism is inside the voxel union, checked separately by # the caller against complete original-tet cell volumes. prisms.append({'low': low, 'high': high, 'h': h, 'pair': tuple(sorted((p, q))), 'axis': axis, 'record': i}) r.update(sheet_support=True, reason='SHEET_PRISM_CANDIDATE') records.append(r) return records, prisms def mapping(mesh, prisms, cells, records): # Certify prism by complete voxel-cell occupancy. Mesh construction has # independently checked 6 nondegenerate tets/cell and exact cell volumes. present = set(cells); certified = [] for p in prisms: lo, hi = np.rint(p['low']/GRID).astype(int), np.rint(p['high']/GRID).astype(int) aligned = np.max(abs(lo*GRID-p['low'])) < TOL and np.max(abs(hi*GRID-p['high'])) < TOL valid = aligned and all(tuple(c) in present for c in itertools.product(*(range(a, b) for a, b in zip(lo, hi)))) records[p['record']]['prism_inside'] = bool(valid) if valid: certified.append(p) else: records[p['record']].update(sheet_support=False, reason='PRISM_OUTSIDE_OR_UNSUPPORTED') keys = sorted(set(p['pair'] for p in certified)); key_id = {key: i for i, key in enumerate(keys)} # Candidate at every original node; ties between distinct wall pairs are # UNKNOWN. A shortest pair needs >=2x separation from each alternative. candidates = [dict() for _ in mesh.x] for p in certified: inside = np.all(mesh.x >= p['low']-TOL, axis=1) & np.all(mesh.x <= p['high']+TOL, axis=1) for i in np.flatnonzero(inside): candidates[i][key_id[p['pair']]] = p['h'] node_pair = np.full(len(mesh.x), -1, int) for i, choices in enumerate(candidates): ordered = sorted((h, k) for k, h in choices.items()) if ordered and (len(ordered) == 1 or ordered[1][0] >= 2*ordered[0][0]-TOL): node_pair[i] = ordered[0][1] tet_pair = np.full(len(mesh.tet), -1, int) for p in certified: k = key_id[p['pair']] inside = np.all(mesh.p >= p['low']-TOL, axis=(1, 2)) & np.all(mesh.p <= p['high']+TOL, axis=(1, 2)) inside &= np.all(node_pair[mesh.tet] == k, axis=1) tet_pair[inside] = k # Scalar projection xi is affine on each certified prism; vertex bounds # imply the entire tet stays in the prism. The count below is exact tet # volume (to floating point), not node counts or centroid quadrature. return node_pair, tet_pair, certified, keys def truth(name, a, n): axis = int(np.argmax(abs(n))) if name == 'plate': return 1. if axis == 2 else None if name == 'u_gap': if axis == 0 and a[2] > 1: return 1. if axis == 2 and 1 < a[0] < 1.5 and a[2] <= 1: return 1. if name == 't_rib': if axis == 2 and (a[0] < 3 or a[0] > 5) and a[2] <= 1: return 1. if axis == 0 and a[2] > 2: return 1. return None def hard_cells(name, cells): c = (np.array(cells)+.5)*GRID if name == 't_rib': return (c[:, 0] >= 3) & (c[:, 0] <= 5) & (c[:, 2] <= 2) if name == 'u_gap': return c[:, 2] <= 1 return np.zeros(len(cells), dtype=bool) def tests(): checks = [] cells = shape('plate'); x, t, owner = make_mesh(cells, 0); m = Mesh(x, t) assert np.isclose(m.volumes.sum(), 48); checks.append('plate_volume_48') assert np.allclose(np.bincount(owner, weights=m.volumes), GRID**3); checks.append('each_cell_volume') assert m.chord_inside(np.array([1., 1., 0.]), np.array([1., 1., 1.])); checks.append('solid_chord') hit = m.hit(np.array([1.25, 1.25, OFFSET]), np.array([0., 0., 1.])) assert hit is not None and np.allclose(hit[0], [1.25, 1.25, 1.]); checks.append('first_hit') xu, tu, _ = make_mesh(shape('u_gap'), 0); mu = Mesh(xu, tu) assert not mu.chord_inside(np.array([1., 2., 3.]), np.array([1.5, 2., 3.])); checks.append('air_gap_rejected') x2, t2, _ = make_mesh(cells, 1); m2 = Mesh(x2, t2) assert len(t2) == len(t) and np.isclose(m2.volumes.sum(), 48); checks.append('second_conforming_mesh') # Metric evaluator only: construction-defined hard zone is exact per cell. tc = shape('t_rib'); assert hard_cells('t_rib', tc).sum()*GRID**3 == 16; checks.append('root_volume_16') return checks def run(root): resource.setrlimit(resource.RLIMIT_CPU, (6600, 6600)) root = Path(root); root.mkdir(parents=True, exist_ok=True) if (root/'science-started.json').exists(): raise FileExistsError('No duplicate probe or retry') save(root/'science-started.json', {'unix': time.time(), 'pid': __import__('os').getpid(), 'scope': 'synthetic_only_first'}) stages = {}; all_results = [] with timed(stages, 'analytic_harness'): save(root/'harness.json', {'checks': tests(), 'status': 'PASS'}) for name in ['plate', 'u_gap', 't_rib']: for variant in [0, 1]: key = f'{name}-mesh{variant}'; out = root/key; out.mkdir() timing = {} with timed(timing, 'geometry_preparation'): cells = shape(name); x, t, owners = make_mesh(cells, variant) anchors, normals, tiles = wall_anchors(cells) with timed(timing, 'adjacency_and_tet_query_setup'): mesh = Mesh(x, t) assert np.allclose(np.bincount(owners, weights=mesh.volumes), GRID**3) np.savez_compressed(out/'mesh.npz', points=x, tets=t, owner_cells=owners, cells=np.array(cells), anchors=anchors, normals=normals, boundary_faces=mesh.faces) with timed(timing, 'rays_reverse_and_whole_chord'): records, prisms = pair(mesh, anchors, normals, tiles) with timed(timing, 'node_mapping_and_certified_tet_volume'): node_pair, tet_pair, certified, keys = mapping(mesh, prisms, cells, records) covered = tet_pair >= 0; hard = hard_cells(name, cells)[owners] expected = [truth(name, a, n) for a, n in zip(anchors, normals)] errors = [abs(r['thickness']/h-1) for r, h in zip(records, expected) if h is not None and r['paired']] false_gap = [] # Independent geometric truth: an accepted segment crossing the U's # open rectangle x in (1,1.5), z>1 is false, irrespective of tet test. for r in records: if name == 'u_gap' and r['paired']: a, b = np.array(r['a']), np.array(r['b']) if min(a[0], b[0]) < 1.5-TOL and max(a[0], b[0]) > 1+TOL and min(a[2], b[2]) > 1+TOL: false_gap.append(r['anchor']) total = float(mesh.volumes.sum()); hard_volume = float(mesh.volumes[hard].sum()) result = {'shape': name, 'variant': variant, 'nodes': len(x), 'tets': len(t), 'anchors': len(anchors), 'total_boundary_area': len(anchors)*GRID**2, 'paired': sum(r['paired'] for r in records), 'paired_area_fraction': sum(r['paired'] for r in records)/len(records), 'thickness_truth_anchors': sum(h is not None for h in expected), 'thickness_paired_denominator': len(errors), 'thickness_relative_error_median_p95': np.quantile(errors, [.5, .95]).tolist() if errors else None, 'accepted_air_crossing_count': len(false_gap), 'accepted_air_crossing_anchors': false_gap, 'true_volume': total, 'covered_tet_volume': float(mesh.volumes[covered].sum()), 'covered_volume_fraction': float(mesh.volumes[covered].sum()/total), 'hard_zone_volume': hard_volume, 'hard_zone_sheet_volume': float(mesh.volumes[hard & covered].sum()), 'root_misclassified_fraction': float(mesh.volumes[hard & covered].sum()/hard_volume) if name == 't_rib' else None, 'mapped_nodes': int((node_pair >= 0).sum()), 'unknown_nodes': int((node_pair < 0).sum()), 'certified_prisms': len(certified), 'timing': timing, 'volume_measure': 'Sum of whole original-tet volumes; all vertices uniquely mapped to one pair and contained in a certified convex prism. No centroid/node-count quadrature.', 'restriction': 'Axis-aligned, rectangular planar wall patches only; exterior geometry identical, triangulations changed; no perturbed-boundary test.'} np.savez_compressed(out/'mapping.npz', node_pair=node_pair, tet_pair=tet_pair, tet_volume=mesh.volumes, hard_tet=hard) save(out/'pairs.json', records) save(out/'prisms.json', [{'low': p['low'].tolist(), 'high': p['high'].tolist(), 'h': p['h'], 'pair': p['pair'], 'axis': p['axis']} for p in certified]) save(out/'result.json', result); all_results.append(result) save(root/'progress.json', {'completed_cases': len(all_results), 'results': all_results}) comparisons = [] for name in ['plate', 'u_gap', 't_rib']: a, b = [r for r in all_results if r['shape'] == name] ra = json.loads((root/f'{name}-mesh0/pairs.json').read_text()); rb = json.loads((root/f'{name}-mesh1/pairs.json').read_text()) assert [r['a'] for r in ra] == [r['a'] for r in rb] comparisons.append({'shape': name, 'identical_physical_anchors': True, 'pair_acceptance_disagreements': sum(r['paired'] != s['paired'] for r, s in zip(ra, rb)), 'max_paired_thickness_absolute_difference': max([abs(r['thickness']-s['thickness']) for r, s in zip(ra, rb) if r['paired'] and s['paired']] or [0.]), 'covered_volume_absolute_difference': abs(a['covered_tet_volume']-b['covered_tet_volume'])}) save(root/'complete.json', {'status': 'SYNTHETIC_EXPLORATORY_COMPLETE', 'cases': all_results, 'remesh_comparison': comparisons, 'harness_timing': stages, 'real_parts_attempted': 0, 'real_skip_reason': 'Method eligibility absent: whole-volume certificate currently relies on exact axis-aligned voxel tiling and rectangular planar wall patches; do not silently extrapolate to Greif.', 'training': False, 'labels_read': False, 'new_packages': False}) if __name__ == '__main__': parser = argparse.ArgumentParser(); parser.add_argument('root'); args = parser.parse_args() run(args.root)