Files
MeltMind/tools/run_volume_quadrature_trial.py

211 lines
11 KiB
Python

"""Four authorized estimates: two axial resolutions x two volume quadratures."""
import argparse
import hashlib
import itertools
import json
from pathlib import Path
import resource
import time
import numpy as np
from scipy.spatial import cKDTree
if __package__:
from .projector_remesh_probe import voxel_mesh, exact_distance, grouped
from .route_feasibility import graph_from_edges, node_tensor
from .physical_support_probe import statistics
from .analyze_support_capacity_conditions import funnel, center_oracle
else:
from projector_remesh_probe import voxel_mesh, exact_distance, grouped
from route_feasibility import graph_from_edges, node_tensor
from physical_support_probe import statistics
from analyze_support_capacity_conditions import funnel, center_oracle
def tetra_rule():
small = (5-np.sqrt(5))/20
bary = np.full((4, 4), small)
np.fill_diagonal(bary, (5+3*np.sqrt(5))/20)
return bary
def volume_samples(x, tet, raw, rule):
p = x[tet]
volume = abs(np.linalg.det(p[:, 1:]-p[:, :1]))/6
if rule == 'lumped_vertex':
mass = np.bincount(tet.ravel(), weights=np.repeat(volume/4, 4), minlength=len(x))
return x, mass, raw
if rule != 'tetra_four_point':
raise ValueError(rule)
bary = tetra_rule()
points = np.einsum('qj,tjk->tqk', bary, p).reshape(-1, 3)
values = np.einsum('qj,tjkl->tqkl', bary, raw[tet]).reshape(-1, 3, 3)
return points, np.repeat(volume/4, 4), values
def initial_field(x, tet):
p = x[tet]
volume = abs(np.linalg.det(p[:, 1:]-p[:, :1]))/6
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)
tensor, _, meta = node_tensor(x, tet, mass, exact_distance(x, 'square_rod'), graph_from_edges(len(x), edges), steps=0)
return tensor, float(volume.sum()), meta
def kernel_reference(anchors, radius, order):
nodes, weights = np.polynomial.legendre.leggauss(order)
xy = .1*(nodes+1)
xx, yy = np.meshgrid(xy, xy, indexing='ij')
ww = .01*np.outer(weights, weights)
cache, results = {}, []
for x, y, z in anchors:
end_distance = min(z, 8-z, radius)
key = (float(x), float(y), float(end_distance))
if key not in cache:
rho2 = (xx-x)**2+(yy-y)**2
A = 1-rho2/radius**2
cap = np.sqrt(np.maximum(radius**2-rho2, 0))
low, high = np.maximum(-cap, -end_distance), cap
def primitive(t):
return A*A*t-2*A*t**3/(3*radius**2)+t**5/(5*radius**4)
integrand = np.where(A>0, primitive(high)-primitive(low), 0)
cache[key] = float(np.sum(ww*integrand))
results.append(cache[key])
return np.array(results)
def integrate(anchors, sample_x, sample_mass, sample_tensor, hz, contract, reference, reference_ok):
radius = contract['radius']
tree = cKDTree(sample_x)
n = len(anchors)
tensor = np.zeros((n, 3, 3))
denominator, effective, eigen_min = np.zeros(n), np.zeros(n), np.zeros(n)
layer_count = np.zeros(n, int)
axial_span = np.zeros(n)
batch_size = contract['query_batch_size']
for begin in range(0, n, batch_size):
neighbors = tree.query_ball_point(anchors[begin:begin+batch_size], radius)
for offset, indices in enumerate(neighbors):
i = begin+offset
ids = np.asarray(indices, int)
delta = sample_x[ids]-anchors[i]
kernel = np.maximum(1-np.sum(delta*delta, axis=1)/radius**2, 0)**2
weight = sample_mass[ids]*kernel
good = weight>0
ids, delta, weight = ids[good], delta[good], weight[good]
total = float(weight.sum())
if not np.isfinite(total) or total<=0:
raise ValueError('Nonfinite or empty positive-volume quadrature')
denominator[i] = total
wn = weight/total
tensor[i] = np.einsum('i,ijk->jk', wn, sample_tensor[ids])
effective[i] = 1/np.sum(wn*wn)
mean = wn@delta
covariance = (delta*wn[:, None]).T@delta-np.outer(mean, mean)
eigen_min[i] = np.linalg.eigvalsh(covariance)[0]/radius**2
bins = np.floor(sample_x[ids, 2]/hz+.5+1e-12).astype(int)
layer_mass = np.bincount(bins, weights=wn)
layer_count[i] = int(np.sum(layer_mass >= contract['support_resolved']['minimum_layer_mass_fraction']))
axial_span[i] = np.ptp(sample_x[ids, 2])
relative_mass_error = abs(denominator/reference-1)
support = (layer_count >= contract['support_resolved']['minimum_effective_axial_layers']) & (eigen_min > contract['support_resolved']['minimum_relative_support_second_moment_eigenvalue'])
quality = reference_ok & (relative_mass_error <= contract['quadrature_quality']['kernel_mass_relative_error_max']) & (effective >= contract['quadrature_quality']['effective_quadrature_samples_min'])
return dict(tensor=tensor, kernel_mass=denominator, reference_kernel_mass=reference,
relative_kernel_mass_error=relative_mass_error, effective_samples=effective,
minimum_relative_support_eigenvalue=eigen_min, effective_axial_layers=layer_count,
axial_span=axial_span, support_resolved=support, quadrature_quality=quality)
def region_masks(anchors):
end = np.minimum(anchors[:, 2], 8-anchors[:, 2]) <= .5+1e-12
wall = (np.minimum(anchors[:, :2], .2-anchors[:, :2]).min(1) <= .05+1e-12) & ~end
return {'all': np.ones(len(anchors), bool), 'interior': ~(end|wall), 'wall': wall, 'end': end}
def main():
parser = argparse.ArgumentParser()
parser.add_argument('output', type=Path)
out = parser.parse_args().output
contract_path = out/'execution_contract.json'
contract = json.loads(contract_path.read_text())['O2']
with (out/'O2.started.json').open('x') as stream:
json.dump({'contract_sha256':hashlib.sha256(contract_path.read_bytes()).hexdigest()}, stream)
started = time.monotonic()
source = Path(contract['anchor_source'])
assert hashlib.sha256(source.read_bytes()).hexdigest() == contract['anchor_source_sha256']
anchors = np.load(source)['query']
assert len(anchors) == contract['anchor_count']
regions = region_masks(anchors)
assert np.all(sum(m.astype(int) for key,m in regions.items() if key!='all')==1)
ref24 = kernel_reference(anchors, .5, 24)
ref48 = kernel_reference(anchors, .5, 48)
reference_error = abs(ref24/ref48-1)
reference_ok = reference_error <= contract['quadrature_quality']['reference_relative_agreement_max']
np.savez_compressed(out/'kernel_mass_reference.npz', query=anchors, order24=ref24, order48=ref48, relative_agreement=reference_error)
results, arrays = {}, {}
center = np.flatnonzero(np.linalg.norm(anchors-[.1,.1,4.], axis=1)<1e-12)
assert len(center)==1
for nz in contract['z_cells']:
x, tet, _ = voxel_mesh([np.linspace(0,.2,13), np.linspace(0,.2,13), np.linspace(0,8,nz+1)], 'six_tets')
distance, _ = cKDTree(x).query(anchors)
assert np.max(distance)<1e-10
raw, volume, meta = initial_field(x, tet)
assert np.isclose(volume,.32)
for rule in contract['weights']:
name = f'z{nz}_{rule}'
tick = time.monotonic()
sx, sm, st = volume_samples(x,tet,raw,rule)
assert np.isclose(sm.sum(),volume) and np.all(sm>0)
a = integrate(anchors,sx,sm,st,8/nz,contract,ref48,reference_ok)
modes = grouped(a['tensor'],.1)['code']
a['mode'] = modes
np.savez_compressed(out/(name+'.npz'), query=anchors, **a)
arrays[name] = a
regional = {}
for region,mask in regions.items():
n = int(mask.sum())
regional[region] = dict(queries=n, support_resolved_count=int(np.sum(mask&a['support_resolved'])),
quadrature_quality_count=int(np.sum(mask&a['quadrature_quality'])),
support_and_quality_count=int(np.sum(mask&a['support_resolved']&a['quadrature_quality'])),
mode_counts={str(c):int(np.sum(mask&(modes==c))) for c in [-1,0,1,2,3]},
kernel_mass_error=statistics(a['relative_kernel_mass_error'][mask]),
minimum_effective_layers=int(a['effective_axial_layers'][mask].min()) if n else None,
effective_samples=statistics(a['effective_samples'][mask]))
oracle,_ = center_oracle(a['tensor'][center[0]])
oracle.update(support_resolved=bool(a['support_resolved'][center[0]]), quadrature_quality=bool(a['quadrature_quality'][center[0]]))
result = dict(name=name,z_cells=nz,rule=rule,nodes=len(x),tets=len(tet),samples=len(sx),
source_field_sha256=hashlib.sha256(raw.tobytes()).hexdigest(),
mesh_sha256=hashlib.sha256(x.tobytes()+tet.tobytes()).hexdigest(),
initial_field=meta,regions=regional,center=oracle,wall_seconds=time.monotonic()-tick)
(out/(name+'.json')).write_text(json.dumps(result,indent=2,allow_nan=False)+'\n')
results[name] = result
print(name,regional['all'],flush=True)
comparisons = {}
pairs = [('weight_z24','z24_lumped_vertex','z24_tetra_four_point'),('weight_z48','z48_lumped_vertex','z48_tetra_four_point'),
('resolution_lumped','z24_lumped_vertex','z48_lumped_vertex'),('resolution_four_point','z24_tetra_four_point','z48_tetra_four_point')]
for label, first, second in pairs:
a,b = arrays[first],arrays[second]
fa,fb = grouped(a['tensor'],.1),grouped(b['tensor'],.1)
qa = a['support_resolved']&a['quadrature_quality']
qb = b['support_resolved']&b['quadrature_quality']
same = fa['code']==fb['code']
eligible = qa&qb&same&np.isin(fa['code'],[1,2])
pe = np.linalg.norm(fa['projector']-fb['projector'],axis=(2,3)).max(1)
regions_out = {}
for region,mask in regions.items():
entry = funnel(a['tensor'],b['tensor'],mask)
entry.update(support_quality_A_count=int(np.sum(mask&qa)),support_quality_B_count=int(np.sum(mask&qb)),
support_quality_both_count=int(np.sum(mask&qa&qb)),
physical_gates_and_same_two_group_projector=statistics(pe[mask&eligible]),
mode_flips_among_support_quality_both=int(np.sum(mask&qa&qb&~same)),
all_anchor_tensor_difference=statistics(np.linalg.norm(a['tensor']-b['tensor'],axis=(1,2))[mask]))
regions_out[region] = entry
comparisons[label] = dict(first=first,second=second,regions=regions_out)
result = dict(contract=contract,reference_mass_max_relative_disagreement=float(reference_error.max()),estimates=results,
comparisons=comparisons,wall_seconds=time.monotonic()-started,peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
full_acceptance='NOT_ESTABLISHED; preregistered numerical engineering gates only',O2_S='NOT_RUN')
(out/'O2_result.json').write_text(json.dumps(result,indent=2,allow_nan=False)+'\n')
if __name__=='__main__':
main()