Files
MeltMind/tools/validate_distance_extensions.py
T

78 lines
4.3 KiB
Python

"""Finite cylinder and union-of-boxes tests on the existing distance estimator."""
import argparse
import json
from pathlib import Path
import time
import numpy as np
if __package__:
from .boundary_distance import SurfaceDistance,triangle_distance_squared
else:
from boundary_distance import SurfaceDistance,triangle_distance_squared
def cylinder(n):
theta=np.arange(n)*2*np.pi/n
bottom=np.c_[np.cos(theta),np.sin(theta),np.zeros(n)];top=bottom+np.array([0,0,4.]);tri=[]
for i in range(n):
j=(i+1)%n
tri.extend([[bottom[i],bottom[j],top[j]],[bottom[i],top[j],top[i]],[[0,0,0],bottom[j],bottom[i]],[[0,0,4],top[i],top[j]]])
return np.array(tri)
def t_union(n):
# Two boxes [-2,2]x[-.5,.5]x[-.5,.5] and [-.5,.5]x[-.5,2]x[-.5,.5].
axes=[np.unique(np.concatenate([np.linspace(a,b,n+1) for a,b in zip(breaks,breaks[1:])])) for breaks in [[-2,-.5,.5,2],[-.5,.5,2],[-.5,.5]]]
shape=tuple(len(a)-1 for a in axes);inside=np.zeros(shape,dtype=bool)
for idx in np.ndindex(shape):
x,y,z=[(axes[k][idx[k]]+axes[k][idx[k]+1])/2 for k in range(3)]
inside[idx]=(y<.5 or abs(x)<.5)
triangles=[];rectangles=[]
for idx in np.ndindex(shape):
if not inside[idx]:continue
low=np.array([axes[k][idx[k]] for k in range(3)]);high=np.array([axes[k][idx[k]+1] for k in range(3)])
for fixed in range(3):
other=[k for k in range(3) if k!=fixed]
for side,step in [(0,-1),(1,1)]:
neighbor=list(idx);neighbor[fixed]+=step
if 0<=neighbor[fixed]<shape[fixed] and inside[tuple(neighbor)]:continue
a=low.copy();b=high.copy();a[fixed]=b[fixed]=low[fixed] if side==0 else high[fixed]
vertices=[]
for s,t in [(0,0),(1,0),(1,1),(0,1)]:
v=a.copy();v[other[0]]=b[other[0]] if s else a[other[0]];v[other[1]]=b[other[1]] if t else a[other[1]];vertices.append(v)
v=np.array(vertices);triangles.extend([v[[0,1,2]],v[[0,2,3]]]);rectangles.append((a,b))
return np.array(triangles),np.array(rectangles)
def main():
p=argparse.ArgumentParser();p.add_argument('output',type=Path);a=p.parse_args()
if a.output.exists():raise FileExistsError(a.output)
rng=np.random.default_rng(1729);theta=rng.uniform(0,2*np.pi,200);r=rng.uniform(0,.95,200);z=rng.uniform(0,4,200)
points=np.c_[r*np.cos(theta),r*np.sin(theta),z]
points=np.r_[points,[[0,0,2],[.9,0,.1],[.9,0,3.9],[.3,.4,.5],[0,0,0],[0,0,4]]]
analytic=np.minimum(1-np.linalg.norm(points[:,:2],axis=1),np.minimum(points[:,2],4-points[:,2]))
rows=[];previous=None;start=time.monotonic()
for n in [16,32,64,128]:
triangles=cylinder(n);actual=SurfaceDistance(triangles).query(points)
brute=np.array([np.sqrt(triangle_distance_squared(x,triangles).min()) for x in points]);sag=1-np.cos(np.pi/n)
err=float(abs(actual-analytic).max());bruteerr=float(abs(actual-brute).max())
if bruteerr>4e-9 or err>sag+4e-9:raise AssertionError('Cylinder failed')
row=dict(facets=n,queries=len(points),same_surface_brute_max_error=bruteerr,smooth_max_error=err,sag_bound=float(sag))
if previous is not None:row['difference_previous_mesh_max']=float(abs(actual-previous).max())
previous=actual;rows.append(row)
query=rng.uniform([-2,-.5,-.5],[2,2,.5],(150,3));query=query[(query[:,1]<=.5)|(abs(query[:,0])<=.5)]
query=np.r_[query,[[0,.45,0],[0,.5,0],[.5,.5,0],[0,0,0]]]
unions=[];reference=None
for n in [1,2,4]:
tri,rect=t_union(n);actual=SurfaceDistance(tri).query(query)
brute=np.array([np.sqrt(triangle_distance_squared(x,tri).min()) for x in query])
rectangle_reference=np.array([np.linalg.norm(x-np.clip(x,rect[:,0],rect[:,1]),axis=1).min() for x in query])
error=float(abs(actual-rectangle_reference).max());bruteerror=float(abs(actual-brute).max())
if error>4e-9 or bruteerror>4e-9:raise AssertionError('T union failed')
row=dict(refinement=n,triangles=len(tri),queries=len(query),rectangle_reference_error=error,brute_error=bruteerror,internal_face_counterexample=dict(point=[0,.45,0],union_distance=float(actual[-4]),wrong_min_separate_box_distances=.05))
if reference is not None:row['remesh_max_distance_change']=float(abs(actual-reference).max())
reference=actual;unions.append(row)
result=dict(status='pass',cylinder=rows,t_union=unions,wall_seconds=time.monotonic()-start,scope='Analytic surfaces only; no physical thickness or real-CAD remeshing claim. T reference uses exposed rectangles, with all internal faces removed.')
a.output.write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
if __name__=='__main__':main()