"""Fixed physical support, unchanged hard spectral gap, and explicit regional errors.""" import argparse import itertools import json from pathlib import Path import time import numpy as np from scipy.spatial import cKDTree from scipy.sparse import diags if __package__: from .projector_remesh_probe import geometry, exact_distance, grouped, coverage from .route_feasibility import graph_from_edges, node_tensor else: from projector_remesh_probe import geometry, exact_distance, grouped, coverage from route_feasibility import graph_from_edges, node_tensor def physical_average(points, tensor, mass, radius, volume_weighted): if radius <= 0 or np.any(mass <= 0): raise ValueError('Positive radius and quadrature masses required') tree = cKDTree(points) weights = tree.sparse_distance_matrix(tree, radius, output_type='coo_matrix').tocsr() weights.data = np.maximum(1 - (weights.data / radius) ** 2, 0) ** 2 weights.eliminate_zeros() if volume_weighted: weights = weights @ diags(mass) denominator = np.asarray(weights.sum(axis=1)).ravel() weights = diags(1 / denominator) @ weights result = (weights @ tensor.reshape(len(points), 9)).reshape(-1, 3, 3) effective = 1 / np.asarray(weights.multiply(weights).sum(axis=1)).ravel() return result, dict(neighbor_quantiles=np.quantile(np.diff(weights.indptr), [0, .5, .95, 1]).tolist(), effective_quadrature_nodes_quantiles=np.quantile(effective, [0, .5, .95, 1]).tolist(), singleton_neighborhood_nodes=int(np.sum(np.diff(weights.indptr) == 1))) def region_labels(x, name, radius, band): labels = np.full(len(x), 'interior', dtype='= .25 - 1e-12) & (x[:, 1] <= .75 + 1e-12) labels[junction] = 'junction' return labels def statistics(values): if not len(values): return dict(count=0, maximum=None, p50=None, p90=None, p95=None, p99=None) return dict(count=len(values), maximum=float(np.max(values)), **{f'p{q}': float(np.percentile(values, q)) for q in [50, 90, 95, 99]}) def compare(t1, t2, positions, mask, tau): a, b = grouped(t1, tau), grouped(t2, tau) different = a['code'] != b['code'] same = mask & ~different & (a['code'] >= 0) errors = np.linalg.norm(a['projector'] - b['projector'], axis=(2, 3)).max(1) rows = {} for code, name in [(0, 'isotropic'), (1, 'normal_plus_plane'), (2, 'plane_plus_axis'), (3, 'three_singletons')]: select = same & (a['code'] == code) rows[name] = statistics(errors[select]) ids = np.flatnonzero(same) worst = ids[np.argsort(errors[ids])[-3:]] return dict(queries=int(mask.sum()), pattern_mismatch_fraction=float(different[mask].mean()) if mask.any() else None, pattern_counts_A={str(c): int(np.sum(mask & (a['code'] == c))) for c in [-1, 0, 1, 2, 3]}, pattern_counts_B={str(c): int(np.sum(mask & (b['code'] == c))) for c in [-1, 0, 1, 2, 3]}, same_pattern_projector=statistics(errors[same]), by_pattern=rows, directional_two_group_projector=statistics(errors[same & np.isin(a['code'], [1, 2])]), sorted_normalized_eigenvalue_error=statistics(abs(a['ratios'] - b['ratios']).max(1)[mask]), worst_same_pattern_positions=positions[worst].tolist(), first_mismatch_positions=positions[np.flatnonzero(mask & different)[:5]].tolist()) def build(x, tet, name): q = x[tet] volume = abs(np.linalg.det(q[:, 1:] - q[:, :1])) / 6 assert np.all(volume > 0) mass = np.bincount(tet.ravel(), weights=np.repeat(volume / 4, 4), minlength=len(x)) edgeids = np.array(list(itertools.combinations(range(4), 2))) edges = np.unique(np.sort(tet[:, edgeids].reshape(-1, 2), axis=1), axis=0) graph = graph_from_edges(len(x), edges) raw, average, meta = node_tensor(x, tet, mass, exact_distance(x, name), graph, steps=0) baseline = raw.reshape(-1, 9) for _ in range(3): baseline = average @ baseline return raw, baseline.reshape(-1, 3, 3), mass, float(volume.sum()), meta def main(): parser = argparse.ArgumentParser() parser.add_argument('output', type=Path) out = parser.parse_args().output target = out / 'physical_support_results.json' if target.exists(): raise FileExistsError(target) contract = json.loads((out / 'execution_contract.json').read_text())['O2'] old = json.loads(Path('artifacts/capacity-projectors-2026-11-13/group_breakdown/remesh_projectors.json').read_text()) old_rows = {(r['shape'], r['resolution']): r for r in old['rows']} rows = [] started = time.monotonic() for name, levels in contract['levels'].items(): radius, band = contract['radii'][name], contract['wall_band'][name] for level in levels: variants = ['radial_delaunay', 'staggered_interior'] if name == 'circular_rod' else ['six_tets', 'cell_center_twelve'] meshes = [] for variant in variants: x, tet, removed = geometry(name, level, variant) raw, baseline, mass, volume, meta = build(x, tet, name) arms = {'archived_three_hop_mass': baseline} support = {} for key, weighted in [('physical_radius_equal_nodes', False), ('physical_radius_lumped_volume', True)]: arms[key], support[key] = physical_average(x, raw, mass, radius, weighted) meshes.append(dict(x=x, mass=mass, volume=volume, arms=arms, support=support, region=region_labels(x, name, radius, band), removed=removed, meta=meta)) a, b = meshes distances, index = cKDTree(b['x']).query(a['x']) assert np.max(distances) < 1e-10 assert np.isclose(a['volume'], b['volume'], rtol=1e-10) assert np.array_equal(a['region'], b['region'][index]) row = dict(shape=name, resolution=level, radius=radius, region_wall_band=band, variants=variants, volumes=[a['volume'], b['volume']], nodes=[len(a['x']), len(b['x'])], removed_degenerate_tets=[a['removed'], b['removed']], initial_estimator=[a['meta'], b['meta']], quadrature_support=[a['support'], b['support']], arms={}) arrays = dict(query=a['x'], mass_A=a['mass'], mass_B_at_shared=b['mass'][index], region=a['region']) for arm in contract['arms']: ta, tb = a['arms'][arm], b['arms'][arm] regions = {} for region in ['all', 'interior', 'wall_end', 'junction']: mask = np.ones(len(a['x']), bool) if region == 'all' else a['region'] == region regions[region] = compare(ta, tb[index], a['x'], mask, contract['gap_threshold']) for tag, mesh in [('A', a), ('B', b)]: rm = np.ones(len(mesh['x']), bool) if region == 'all' else mesh['region'] == region regions[region]['coverage_' + tag] = coverage(grouped(mesh['arms'][arm][rm], .1), mesh['mass'][rm]) if rm.any() else None regions[region]['volume_fraction_' + tag] = float(mesh['mass'][rm].sum() / mesh['mass'].sum()) row['arms'][arm] = regions arrays[arm + '_tensor_A'] = ta arrays[arm + '_tensor_B_common'] = tb[index] baseline = row['arms']['archived_three_hop_mass']['all'] reference = old_rows[(name, level)]['thresholds']['0.1'] assert np.isclose(baseline['pattern_mismatch_fraction'], reference['pattern_mismatch_query_fraction']) assert np.isclose(baseline['same_pattern_projector']['maximum'], reference['projector_frobenius_max']) row['archived_baseline_reproduced'] = True np.savez_compressed(out / f'{name}_{level}_paired_fields.npz', **arrays) rows.append(row) print(name, level, {arm: round(row['arms'][arm]['all']['pattern_mismatch_fraction'], 4) for arm in contract['arms']}, flush=True) target.write_text(json.dumps(dict(contract=contract, rows=rows, wall_seconds=time.monotonic()-started, acceptance='NOT_ESTABLISHED; no frozen projector thresholds or radius selection'), indent=2, allow_nan=False)+'\n') if __name__ == '__main__': main()