127 lines
8.7 KiB
Python
127 lines
8.7 KiB
Python
"""Postprocess frozen tensors and region volumes; no mesh, estimator or solver run."""
|
|
import argparse
|
|
import csv
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import numpy as np
|
|
if __package__:
|
|
from .projector_remesh_probe import grouped
|
|
from .physical_support_probe import statistics
|
|
else:
|
|
from projector_remesh_probe import grouped
|
|
from physical_support_probe import statistics
|
|
|
|
|
|
def funnel(ta, tb, mask):
|
|
a, b = grouped(ta, .1), grouped(tb, .1)
|
|
ga, gb = np.isin(a['code'], [1, 2]), np.isin(b['code'], [1, 2])
|
|
same = a['code'] == b['code']
|
|
n = int(mask.sum())
|
|
counts = dict(A_emit=int(np.sum(mask & ga)), B_emit=int(np.sum(mask & gb)),
|
|
both_emit_same_mode=int(np.sum(mask & ga & gb & same)),
|
|
both_emit_different_mode=int(np.sum(mask & ga & gb & ~same)),
|
|
A_only=int(np.sum(mask & ga & ~gb)), B_only=int(np.sum(mask & ~ga & gb)),
|
|
neither=int(np.sum(mask & ~ga & ~gb)), all_mode_flips=int(np.sum(mask & ~same)))
|
|
assert sum(counts[k] for k in ['both_emit_same_mode', 'both_emit_different_mode', 'A_only', 'B_only', 'neither']) == n
|
|
selected = mask & ga & gb & same
|
|
error = np.linalg.norm(a['projector']-b['projector'], axis=(2, 3)).max(1)
|
|
modes = [-1, 0, 1, 2, 3]
|
|
matrix = [[int(np.sum(mask & (a['code'] == i) & (b['code'] == j))) for j in modes] for i in modes]
|
|
assert np.sum(matrix) == n
|
|
return dict(queries=n, counts=counts, rates={key: value/n if n else None for key, value in counts.items()},
|
|
both_emit_rate=(counts['both_emit_same_mode']+counts['both_emit_different_mode'])/n if n else None,
|
|
projector_difference_both_emit_same_mode=statistics(error[selected]), mode_order=modes, mode_transition_counts=matrix)
|
|
|
|
|
|
def center_oracle(tensor):
|
|
value, vectors = np.linalg.eigh(tensor)
|
|
scale = max(value[-1], 1e-12)
|
|
gate = bool(value.sum() > 1e-10 and (value[1]-value[0])/scale > .1)
|
|
projector = np.outer(vectors[:, 0], vectors[:, 0])
|
|
ideal = np.diag([.5, .5, 0.])
|
|
return dict(eigenvalues_ascending=value.tolist(), mode=int(grouped(tensor[None], .1)['code'][0]),
|
|
axis_gap_pass=gate, tensor_frobenius_error_to_analytic=float(np.linalg.norm(tensor-ideal)),
|
|
eigenvalue_max_error_to_analytic=float(np.max(abs(value-np.array([0., .5, .5])))),
|
|
axis_projector_error_to_analytic=float(np.linalg.norm(projector-np.diag([0., 0., 1.]))) if gate else None), projector
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('output', type=Path)
|
|
out = parser.parse_args().output
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
if (out/'capacity_count_conditions.json').exists() or (out/'eligibility_funnels.json').exists():
|
|
raise FileExistsError('Preserve existing postprocessing')
|
|
source = Path('artifacts/physical-support-2026-11-14')
|
|
summary = json.loads((source/'physical_support_results.json').read_text())
|
|
rows, centers, sources = [], [], []
|
|
for r in summary['rows']:
|
|
p = source/f"{r['shape']}_{r['resolution']}_paired_fields.npz"
|
|
saved = np.load(p)
|
|
sources.append(dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest()))
|
|
for arm in r['arms']:
|
|
a, b = saved[arm+'_tensor_A'], saved[arm+'_tensor_B_common']
|
|
for region in ['all', 'interior', 'wall_end', 'junction']:
|
|
mask = np.ones(len(a), bool) if region == 'all' else saved['region'] == region
|
|
rows.append(dict(shape=r['shape'], resolution=r['resolution'], arm=arm, region=region, **funnel(a, b, mask)))
|
|
if r['shape'] == 'square_rod':
|
|
ids = np.flatnonzero(np.linalg.norm(saved['query']-[.1, .1, 4.], axis=1) < 1e-12)
|
|
assert len(ids) == 1
|
|
qa, pa = center_oracle(a[ids[0]])
|
|
qb, pb = center_oracle(b[ids[0]])
|
|
centers.append(dict(resolution=r['resolution'], arm=arm, query=[.1, .1, 4.], A=qa, B=qb,
|
|
axis_projector_difference_both_pass=float(np.linalg.norm(pa-pb)) if qa['axis_gap_pass'] and qb['axis_gap_pass'] else None))
|
|
(out/'eligibility_funnels.json').write_text(json.dumps(dict(
|
|
emit_gate='Trace>1e-10 and hard-gap=0.1 code in {1,2}; numerical two-cluster emission, NOT physical accuracy or quadrature convergence.',
|
|
denominator='All shared anchors in each region, including failures and mode flips; conditional errors never replace full denominator.',
|
|
center_axis_gate='At the square-rod center, use smallest-eigenvalue axis and its gap from the next eigenvalue; never choose an axis inside the transverse degenerate plane.',
|
|
rows=rows, square_rod_center_oracle=centers, sources=sources), indent=2, allow_nan=False)+'\n')
|
|
with (out/'eligibility_funnels.csv').open('w') as stream:
|
|
writer = csv.writer(stream)
|
|
writer.writerow(['shape','resolution','arm','region','N','A_emit_rate','B_emit_rate','both_emit_rate','all_mode_flip_rate','both_emit_same_mode_N','conditional_Pmax','conditional_P95'])
|
|
for r in rows:
|
|
e = r['projector_difference_both_emit_same_mode']
|
|
writer.writerow([r['shape'],r['resolution'],r['arm'],r['region'],r['queries'],r['rates']['A_emit'],r['rates']['B_emit'],r['both_emit_rate'],r['rates']['all_mode_flips'],e['count'],e['maximum'],e['p95']])
|
|
diagnosis = json.loads((source/'shape_850_diagnosis.json').read_text())
|
|
table = diagnosis['type_region_table']
|
|
volume = np.array([r['volume'] for r in table])
|
|
anchors = np.array([r['seeds'] for r in table])
|
|
S = diagnosis['scale_contract']['S_realized_raw']
|
|
k = diagnosis['scale_contract']['K']
|
|
lo, hi = .95*S, 1.05*S
|
|
lower, upper = np.ceil(volume/hi).astype(int), np.floor(volume/lo).astype(int)
|
|
quota = np.floor(volume/S).astype(int)
|
|
order = np.lexsort((np.arange(len(volume)), -(volume/S-quota)))
|
|
quota[order[:k-int(quota.sum())]] += 1
|
|
assert quota.sum() == k and anchors.sum() == k
|
|
def pressure(n):
|
|
incoming = np.maximum(n*lo-volume, 0).sum()/volume.sum()
|
|
outgoing = np.maximum(volume-n*hi, 0).sum()/volume.sum()
|
|
return dict(import_lower_bound_fraction=float(incoming), export_lower_bound_fraction=float(outgoing),
|
|
total_cross_region_mass_lower_bound_fraction=float(max(incoming, outgoing)))
|
|
condition = dict(case=diagnosis['case'], K=k, S=S, lower_capacity=lo, upper_capacity=hi,
|
|
interval_formula='ceil(Vj/V+) <= nj <= floor(Vj/V-)',
|
|
interpretation='Necessary for zero crossing. Nonempty intervals plus sum lower<=K<=sum upper suffice ONLY for scalar continuously divisible mass with free anchor placement, not graph-connected seeded partitions.',
|
|
regions=[dict(region=int(r['region']), volume_over_S=float(volume[i]/S), minimum_pieces=int(lower[i]), maximum_pieces=int(upper[i]),
|
|
interval_nonempty=bool(lower[i] <= upper[i]), fixed_anchors=int(anchors[i]),
|
|
fixed_anchors_in_interval=bool(lower[i] <= anchors[i] <= upper[i]), proposed_quota_not_executed=int(quota[i])) for i,r in enumerate(table)],
|
|
sum_minimum_pieces=int(lower.sum()), sum_maximum_pieces=int(upper.sum()),
|
|
zero_crossing_scalar_feasible=bool(np.all(lower<=upper) and lower.sum()<=k<=upper.sum()),
|
|
existing_anchor_pressure=pressure(anchors), proposed_quota_pressure=pressure(quota),
|
|
proposed_quota_rule='Largest remainder of Vj/S, stable region-ID tie-break; arithmetic proposal only, no new anchors or partition solves.',
|
|
minimum_anchor_relocations_for_proposed_quota=int(np.maximum(anchors-quota,0).sum()),
|
|
no_sufficiency_claim='Reduced unavoidable mass-exchange lower bound is neither a feasible partition nor a shape guarantee.')
|
|
# A scalar-feasible but indivisible-node-infeasible example guards the interpretation.
|
|
masses=np.array([.6,.6,.6,.2])
|
|
totals=np.array([sum(masses[i] for i in range(4) if bits & (1<<i)) for bits in range(16)])
|
|
assert np.ceil(masses.sum()/1.05) <= 2 <= np.floor(masses.sum()/.95)
|
|
assert not np.any((totals>=.95)&(totals<=1.05))
|
|
condition['indivisibility_counterexample']=dict(node_masses=masses.tolist(), K=2, capacity=[.95,1.05], scalar_count_pass=True, feasible_subsets=0)
|
|
(out/'capacity_count_conditions.json').write_text(json.dumps(condition, indent=2, allow_nan=False)+'\n')
|
|
print(json.dumps({'regional_funnels':len(rows),'center_diagnostics':len(centers),'count_interval_sums':[int(lower.sum()),int(upper.sum())],'K':k,'zero_crossing_feasible':condition['zero_crossing_scalar_feasible'],'anchor_moves_proposed':condition['minimum_anchor_relocations_for_proposed_quota']},indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|