#!/usr/bin/env python3 """ Validator for problem 047a: Improve a 10D Lattice Packing (Λ10 Baseline) Input: {"basis": [[...],[...],...]} 10x10 matrix whose ROWS are basis vectors in R^10. The lattice is L = { z^T B : z in Z^10 }. We compute the shortest nonzero vector length via Schnorr-Euchner enumeration on an LLL-reduced basis, then compute packing density: density = Vol(Ball_10(r)) / covolume r = (shortest_vector_length)/2 covolume = |det(B)| Metric key: "packing_density" (maximize). """ import argparse import math from typing import Any, Tuple, Optional import numpy as np from . import ValidationResult, load_solution, output_result, success, failure DIMENSION = 10 TOL_DET = 1e-12 MAX_ABS_ENTRY = 1e3 MAX_COND = 1e10 def sphere_volume(r: float, n: int) -> float: return (math.pi ** (n / 2.0)) * (r ** n) / math.gamma(n / 2.0 + 1.0) def gram_schmidt_cols(B: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Classical Gram-Schmidt on column basis. Args: B: (m,n) with columns as basis vectors. Returns: Bstar: (m,n) orthogonalized columns mu: (n,n) GS coefficients bstar_norm2: (n,) squared norms of Bstar columns """ m, n = B.shape Bstar = np.zeros((m, n), dtype=np.float64) mu = np.zeros((n, n), dtype=np.float64) bstar_norm2 = np.zeros(n, dtype=np.float64) for i in range(n): v = B[:, i].copy() for j in range(i): denom = bstar_norm2[j] if denom <= 0: mu[i, j] = 0.0 continue mu[i, j] = float(np.dot(B[:, i], Bstar[:, j]) / denom) v -= mu[i, j] * Bstar[:, j] Bstar[:, i] = v bstar_norm2[i] = float(np.dot(v, v)) if bstar_norm2[i] <= 0: bstar_norm2[i] = 0.0 return Bstar, mu, bstar_norm2 def lll_reduce_cols(B: np.ndarray, delta: float = 0.99, max_iter: int = 5000) -> np.ndarray: """ Basic floating-point LLL reduction on column basis (10D only). """ B = B.copy().astype(np.float64) n = B.shape[1] it = 0 k = 1 Bstar, mu, bstar_norm2 = gram_schmidt_cols(B) while k < n and it < max_iter: it += 1 # Size reduction for j in range(k - 1, -1, -1): q = int(np.round(mu[k, j])) if q != 0: B[:, k] -= q * B[:, j] Bstar, mu, bstar_norm2 = gram_schmidt_cols(B) if bstar_norm2[k] == 0 or bstar_norm2[k - 1] == 0: return B # caller will reject if degenerate # Lovasz condition if bstar_norm2[k] >= (delta - mu[k, k - 1] ** 2) * bstar_norm2[k - 1]: k += 1 else: B[:, [k, k - 1]] = B[:, [k - 1, k]] Bstar, mu, bstar_norm2 = gram_schmidt_cols(B) k = max(k - 1, 1) return B def _enum_se( R: np.ndarray, target: np.ndarray, best: float, require_nonzero: bool = False ) -> Tuple[float, Optional[np.ndarray]]: """ Schnorr-Euchner enumeration for CVP/SVP in upper-triangular coordinates. Minimizes ||R z - target||^2 over z in Z^n. If require_nonzero=True, excludes z=0 (useful for SVP with target=0). """ n = R.shape[0] z = np.zeros(n, dtype=np.int64) best_z: Optional[np.ndarray] = None def rec(k: int, dist2: float): nonlocal best, best_z if dist2 >= best: return if k < 0: if require_nonzero and np.all(z == 0): return best = dist2 best_z = z.copy() return s = float(target[k]) if k + 1 < n: s -= float(np.dot(R[k, k + 1 :], z[k + 1 :])) Rkk = float(R[k, k]) if abs(Rkk) < 1e-18: rec(k - 1, dist2 + s * s) return c = s / Rkk m = int(np.round(c)) step = 0 while True: if step == 0: candidates = [m] d = abs(c - m) if dist2 + (Rkk * d) ** 2 >= best: break else: d_plus = abs(c - (m + step)) d_minus = abs(c - (m - step)) if dist2 + (Rkk * min(d_plus, d_minus)) ** 2 >= best: break candidates = [m + step, m - step] for t in candidates: z[k] = int(t) diff = s - Rkk * float(t) rec(k - 1, dist2 + diff * diff) step += 1 rec(n - 1, 0.0) return best, best_z def shortest_vector_length(B_cols: np.ndarray) -> float: """ Compute shortest nonzero vector length of lattice generated by columns of B_cols. """ B_red = lll_reduce_cols(B_cols) Q, R = np.linalg.qr(B_red) # Initial bound from shortest basis vector col_norm2 = np.sum(B_red * B_red, axis=0) best = float(np.min(col_norm2)) if not np.isfinite(best) or best <= 0: best = float("inf") best, z_best = _enum_se(R, target=np.zeros(DIMENSION), best=best, require_nonzero=True) if z_best is None or not np.isfinite(best) or best <= 0: return float(np.sqrt(np.min(col_norm2))) return float(np.sqrt(best)) def validate(solution: Any) -> ValidationResult: try: if isinstance(solution, dict) and "basis" in solution: basis_data = solution["basis"] elif isinstance(solution, list): basis_data = solution else: return failure("Invalid format: expected dict with 'basis' or 2D list") B_rows = np.array(basis_data, dtype=np.float64) except (ValueError, TypeError) as e: return failure(f"Failed to parse basis: {e}") if B_rows.shape != (DIMENSION, DIMENSION): return failure(f"Basis must be {DIMENSION}x{DIMENSION}, got {B_rows.shape}") if not np.all(np.isfinite(B_rows)): return failure("Basis contains non-finite entries") if float(np.max(np.abs(B_rows))) > MAX_ABS_ENTRY: return failure(f"Basis entries too large (>|{MAX_ABS_ENTRY}|)") # Rows -> columns B_cols = B_rows.T.copy() det = float(np.linalg.det(B_cols)) if not np.isfinite(det) or abs(det) < TOL_DET: return failure("Basis is singular (determinant ~ 0)") covolume = abs(det) cond = float(np.linalg.cond(B_cols)) if not np.isfinite(cond) or cond > MAX_COND: return failure(f"Basis is ill-conditioned (cond={cond:.3e} > {MAX_COND:g})") min_len = shortest_vector_length(B_cols) if not np.isfinite(min_len) or min_len <= 0: return failure("Failed to compute a valid shortest vector length") packing_radius = min_len / 2.0 density = sphere_volume(packing_radius, DIMENSION) / covolume return success( f"Lattice in R^{DIMENSION}: shortest vector ~ {min_len:.8f}, packing density ~ {density:.12f}", dimension=DIMENSION, determinant=float(det), covolume=float(covolume), min_vector_length=float(min_len), packing_radius=float(packing_radius), packing_density=float(density), metric_key="packing_density", ) def main(): parser = argparse.ArgumentParser(description="Validate lattice sphere packing in dimension 10") parser.add_argument("solution", help="Solution as JSON string or path to JSON file") args = parser.parse_args() sol = load_solution(args.solution) result = validate(sol) output_result(result) if __name__ == "__main__": main()