"""Run exact rank scans and numerical equivariance checks. Run from any directory.""" import argparse from fractions import Fraction as F from itertools import permutations, product import json from pathlib import Path import numpy as np import scipy import sympy as sp from exact_ranks import NINE, SOLIDS, direct_cubic_witness, nine_polynomial_scan, orbit_gram_scan from frames import action, charts, harmonics, parseval, quadrature from smooth import smooth_operator def signed_permutations(dim=3): for p in permutations(range(dim)): for signs in product((-1, 1), repeat=dim): mat = np.zeros((dim, dim), dtype=int) mat[np.arange(dim), p] = signs yield mat def extremal_groups(): nine = np.asarray(NINE, dtype=int) six = np.concatenate((np.eye(3, dtype=int), -np.eye(3, dtype=int))) sizes = {} for name, pts, label in (("nine_unmarked", nine, [0]*9), ("six_two_colors", six, [1]*3+[0]*3), ("six_unmarked", six, [0]*6)): records = sorted((tuple(v), c) for v, c in zip(pts, label)) accepted = [g for g in signed_permutations() if sorted((tuple(g@v), c) for v,c in zip(pts,label)) == records] expected = 48 if name == "six_unmarked" else 6 assert len(accepted) == expected flips = [int(np.prod(g[g!=0])) for g in accepted] assert ((-1 not in flips) == (expected == 6)) sizes[name] = dict(group_order=len(accepted), cubic_xyz_allowed=(-1 not in flips)) return sizes def numerical(): ident = np.eye(3, dtype=int) mirror = np.diag([1, 1, -1]) oh = list(signed_permutations()) td = [m for m in oh if np.prod(m[m != 0]) == 1] s3 = [m for m in oh if np.all(m >= 0)] d4h = [m for m in oh if abs(m[2, 2]) == 1] square = SOLIDS["square"][0] tag = [(int(i == 0),) for i in range(4)] marked_group = [m for m in d4h if np.array_equal(m @ square[0], square[0])] planar = [(0, 0, 0), (2, 0, 0), (0, 1, 0)] labelled_3d = [(0, 0, 0), (2, 0, 0), (0, 3, 0), (0, 0, 5)] # A connected directed incidence pattern distinguishes two co-located vertices. duplicate = planar + [planar[0]] duplicate_edges = tuple(tuple(int((i, j) in ((0, 1), (0, 2), (3, 1))) for j in range(4)) for i in range(4)) fixtures = [ ("tetrahedron", SOLIDS["tetrahedron"][0], None, None, td, (3, 6, 15)), ("square", square, None, None, d4h, (4, 5, 8)), ("marked_square", square, tag, None, marked_group, (1, 3)), ("octahedron", SOLIDS["octahedron"][0], None, None, oh, (6, 12)), ("cube", SOLIDS["cube"][0], None, None, oh, (4, 12)), ("nine_points", NINE, None, None, s3, (2, 3, 7)), ("scalene_plane", planar, None, None, [ident, mirror], (0, 1, 4)), ("asymmetric_3d", labelled_3d, None, None, [ident], (0, 1, 5)), ("coincident_graph", duplicate, None, duplicate_edges, [ident, mirror], (1, 3)), ("line_symmetric", [(-1, 0, 0), (1, 0, 0)], None, None, None, (0, 1, 2, 3)), ("line_asymmetric", [(0, 0, 0), (1, 0, 0), (4, 0, 0)], None, None, None, (1, 2)), ("point", [(1, 2, 3)] * 2, None, None, None, (0, 1, 3))] normal = (1, 2, 3) reflect = np.asarray([[F(int(i == j)) - F(normal[i]*normal[j], 7) for j in range(3)] for i in range(3)], dtype=object) rotate = reflect @ np.diag([-1, 1, 1]) rng = np.random.default_rng(2731) examples = [] for name, pts, labels, edges, group, degrees in fixtures: chart = charts(pts, labels, edges) test_transforms = [] for transform in (rotate, reflect): perm = rng.permutation(len(pts)).tolist() moving = [(transform @ np.array(pts[i], dtype=object) + np.array([9, -4, 2])).tolist() for i in perm] new_labels = None if labels is None else [labels[i] for i in perm] new_edges = None if edges is None else [[edges[i][j] for j in perm] for i in perm] test_transforms.append((transform.astype(float), charts(moving, new_labels, new_edges))) for ell, twist in product(degrees, (0, 1)): mat = parseval(chart, ell, twist) if group is not None: known = sum(action(ell, g, twist) for g in group) / len(group) elif name == "point": known = np.eye(2*ell+1) * int(ell == 0 and not twist) else: y = harmonics(ell, [[1., 0., 0.]]) known = y @ y.T * (4*np.pi/(2*ell+1)) if twist or (name == "line_symmetric" and ell % 2): known[:] = 0. defect = float(np.linalg.norm(mat @ mat.T - known, ord=2)) equiv = max(float(np.linalg.norm(parseval(target, ell, twist) - action(ell, t, twist) @ mat, ord=2)) for t, target in test_transforms) singular = np.linalg.svd(mat, compute_uv=False) sv_defect = float(np.max(np.minimum(abs(singular), abs(1-singular)))) assert max(defect, equiv, sv_defect) < 1e-10, (name, ell, twist, defect, equiv) rank = int(sum(singular > 0.5)) assert rank == int(round(np.trace(known))) examples.append(dict(fixture=name, degree=ell, twist=twist, rank=rank, projector_error=defect, equivariance_error=equiv, singular_value_error=sv_defect)) return examples def scalar_rescue(): pts = np.asarray(NINE, dtype=float) v = -np.sum(np.sum(pts**2, axis=1)[:, None] * pts, axis=0) assert np.array_equal(v, [18.,18.,18.]) y = harmonics(3, [v / np.linalg.norm(v)])[:, 0] visible = np.sum(harmonics(3, np.eye(3)), axis=1) residual = y - visible * (visible @ y) / (visible @ visible) energy = float((residual @ residual)/(y @ y)) assert abs(energy - 5/9) < 1e-14 return {"residual_fraction_squared_exact": "5/9", "float64": energy} def rigid_orbit_benchmark(count=256): """Exact target rule; independent quadrature target, measured float64 errors.""" from scipy.spatial.transform import Rotation rng = np.random.default_rng(4117) grid, analysis = quadrature(3) target_scale = np.sqrt(105 / (4 * np.pi)) points = np.asarray(NINE, dtype=float) baseline_errors, repaired_errors = [], [] for index in range(count): transform = Rotation.from_quat(rng.normal(size=4)).as_matrix() if index % 2: transform[:, 2] *= -1 moved = (points @ transform.T)[rng.permutation(len(points))] + rng.normal(size=3) centered_points = moved - moved.mean(axis=0) radius2 = np.sum(centered_points**2, axis=1) unit_shell = centered_points[np.isclose(radius2, 1., atol=1.e-12, rtol=0.)] a = harmonics(3, unit_shell).sum(axis=1) global_moment = -np.sum(radius2[:, None] * centered_points, axis=0) b = harmonics(3, [global_moment / np.linalg.norm(global_moment)])[:, 0] residual = b - a * ((a @ b) / (a @ a)) target = (target_scale * np.prod(grid @ transform, axis=1)) @ analysis assert abs(np.linalg.norm(target) - 1.) < 1e-13 baseline = a * ((a @ target) / (a @ a)) predicted = residual / np.linalg.norm(residual) baseline_errors.append(float(np.sum((target - baseline)**2))) repaired_errors.append(float(np.sum((target - predicted)**2))) assert max(abs(x - 1.) for x in baseline_errors) < 1e-12 assert max(repaired_errors) < 1e-25 return dict(poses=count, proper=count//2, improper=count//2, seed=4117, mean_pair_span_squared_error=float(np.mean(baseline_errors)), mean_repaired_squared_error=float(np.mean(repaired_errors)), max_repaired_squared_error=float(max(repaired_errors))) def smooth_checks(): fixtures = [ ("square_l2", np.asarray(SOLIDS["square"][0], dtype=float)/2, None, 2, (1, 0)), ("square_l4", np.asarray(SOLIDS["square"][0], dtype=float)/2, None, 4, (2, 0)), ("tetra_l3", np.asarray(SOLIDS["tetrahedron"][0], dtype=float)/2, None, 3, (1, 0)), ("tetra_l6", np.asarray(SOLIDS["tetrahedron"][0], dtype=float)/2, None, 6, (1, 1))] for height in (0., .05, .2): pts = np.array([[1,0,height],[-1,0,height],[0,1,-height],[0,-1,-height]]) fixtures.append((f"marked_height_{height}", pts, np.arange(4), 1, (2, 1) if height == 0. else (3, 3))) output = [] mirror = np.array([[0.,-1.,0.],[0.,0.,1.],[1.,0.,0.]]) for name, points, labels, ell, expected in fixtures: for bandwidth, twist in product((.2, .4, .8), (0, 1)): mat = smooth_operator(points, ell, twist, bandwidth, labels) eig = np.linalg.eigvalsh(mat) scale = max(1., abs(eig).max()) tol = 1.e-9 * scale assert eig.min() >= -tol, (name, eig) rank = int(np.count_nonzero(eig > tol)) assert rank == expected[twist], (name, twist, bandwidth, eig) transformed = smooth_operator((points @ mirror.T)[::-1]+[[2.,-4.,1.]], ell, twist, bandwidth, None if labels is None else labels[::-1]) rep = action(ell, mirror, twist) err = float(np.linalg.norm(transformed-rep@mat@rep.T,ord=2)/scale) assert err < 1.e-9, (name, bandwidth, err) output.append(dict(case=name, degree=ell, twist=twist, bandwidth=bandwidth, rank=rank, normalized_covariance_error=err, eigenvalues=eig.tolist())) return output def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", help="Optional path at which to write the JSON report.") args = parser.parse_args() data = dict(versions={"numpy": np.__version__, "scipy": scipy.__version__, "sympy": sp.__version__}, regular_shapes=orbit_gram_scan(), nine_point_exact=nine_polynomial_scan(), extremal_groups=extremal_groups(), witnesses=direct_cubic_witness(), moment_rescue=scalar_rescue(), orbit_benchmark=rigid_orbit_benchmark(), frame_checks=numerical(), smooth_kernel_checks=smooth_checks()) tests = data["frame_checks"] data["summary"] = dict(shape_degree_rows=sum(map(len, data["regular_shapes"].values())), nine_point_degrees=len(data["nine_point_exact"]), frame_cases=len(tests), smooth_kernel_cases=len(data["smooth_kernel_checks"]), transformations_per_case=2, max_projector_error=max(row["projector_error"] for row in tests), max_equivariance_error=max(row["equivariance_error"] for row in tests), max_singular_value_error=max(row["singular_value_error"] for row in tests)) print(json.dumps(data["summary"], indent=2)) if args.output: Path(args.output).write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") if __name__ == "__main__": main()