Files
MeltMind/tools/physical_support_diagnostics.py
T

69 lines
4.2 KiB
Python

"""Support-resolution and common-subset diagnostics; no estimator or cut rerun."""
import argparse
import json
from pathlib import Path
import numpy as np
from scipy.spatial import cKDTree
from projector_remesh_probe import geometry, grouped
from physical_support_probe import statistics
def main():
p = argparse.ArgumentParser()
p.add_argument('output', type=Path)
out = p.parse_args().output
destination = out / 'support_resolution_and_paired_effects.json'
if destination.exists():
raise FileExistsError(destination)
contract = json.loads((out / 'execution_contract.json').read_text())['O2']
result = json.loads((out / 'physical_support_results.json').read_text())
rows = []
for r in result['rows']:
shape, level, radius = r['shape'], r['resolution'], r['radius']
fields = np.load(out / f'{shape}_{level}_paired_fields.npz')
support = []
for variant in r['variants']:
x, _, _ = geometry(shape, level, variant)
distances = cKDTree(x).sparse_distance_matrix(cKDTree(x), radius, output_type='coo_matrix')
ids, js, ds = distances.row, distances.col, distances.data
kernel = np.maximum(1-(ds/radius)**2, 0)**2
keep = kernel > 0
ids, js, kernel = ids[keep], js[keep], kernel[keep]
delta = x[js]-x[ids]
norm = np.bincount(ids, weights=kernel, minlength=len(x))
moment = np.zeros((len(x), 3, 3))
for i in range(3):
for j in range(3):
moment[:, i, j] = np.bincount(ids, weights=kernel*delta[:, i]*delta[:, j], minlength=len(x))/norm
ev = np.linalg.eigvalsh(moment)
support.append(dict(variant=variant, kernel_support_rank_below_three_fraction=float(np.mean(ev[:, 0] < 1e-10*radius**2)),
relative_smallest_second_moment=statistics(ev[:, 0]/radius**2),
no_axial_z_support_fraction=float(np.mean(moment[:, 2, 2] < 1e-10*radius**2)),
scope='Support geometry diagnostic with equal kernel weights, not an estimator accuracy test; no quadrature or tensor rerun.'))
features = {arm: [grouped(fields[arm+suffix], .1) for suffix in ['_tensor_A', '_tensor_B_common']] for arm in contract['arms']}
effects = {}
for first, second, title in [
('archived_three_hop_mass', 'physical_radius_lumped_volume', 'support_operator_at_volume_weighting'),
('physical_radius_equal_nodes', 'physical_radius_lumped_volume', 'quadrature_at_fixed_physical_support')]:
a, b = features[first]
c, d = features[second]
stable = (a['code'] == b['code']) & (a['code'] == c['code']) & (a['code'] == d['code']) & np.isin(a['code'], [1, 2])
e1 = np.linalg.norm(a['projector']-b['projector'], axis=(2, 3)).max(1)
e2 = np.linalg.norm(c['projector']-d['projector'], axis=(2, 3)).max(1)
effect = {}
for region in ['all', 'interior', 'wall_end', 'junction']:
mask = np.ones(len(stable), bool) if region == 'all' else fields['region'] == region
selected = stable & mask
effect[region] = dict(total_queries=int(mask.sum()), common_same_two_group_queries=int(selected.sum()),
before=statistics(e1[selected]), after=statistics(e2[selected]),
after_minus_before=statistics((e2-e1)[selected]),
strictly_worse_fraction=float(np.mean(e2[selected] > e1[selected]+1e-12)) if selected.any() else None)
effects[title] = dict(arms=[first, second], regions=effect,
caveat='Conditional common subset; excluded queries and pattern changes remain in the main result. Neighborhood operator includes kernel/normalization, not radius alone.')
rows.append(dict(shape=shape, resolution=level, support_resolution=support, paired_effects=effects))
destination.write_text(json.dumps(dict(rows=rows, no_soft_gap=True, selection='All existing 12 pairs; no new meshes beyond prior constructions or tuned radius'), indent=2, allow_nan=False)+'\n')
if __name__ == '__main__':
main()