| |
| """ |
| Validator for problem 048: Dense Lattice Packing in Dimension 12 |
| |
| The sphere packing problem in ℝ¹² asks for the lattice with highest |
| packing density. Current best: K₁₂ with density ≈ 0.0494. |
| |
| This validator: |
| 1. Verifies the basis matrix defines a valid lattice |
| 2. Computes the exact shortest nonzero vector length via fpylll (LLL + SVP enumeration) |
| 3. Computes the packing density |
| |
| Uses fpylll's Fincke–Pohst enumeration for exact SVP, which is tractable in |
| dimension 12 (sub-second on a modern machine). |
| |
| Expected input format: |
| {"basis": [[b₁₁, ...], [b₂₁, ...], ...]} 12×12 basis matrix (rows are basis vectors) |
| |
| Metric key: "packing_density" (maximize). |
| """ |
|
|
| import argparse |
| import math |
| from fractions import Fraction |
| from typing import Any, Tuple |
|
|
| import numpy as np |
| from fpylll import IntegerMatrix, LLL, Enumeration, EvaluatorStrategy |
| from fpylll.fplll.gso import MatGSO |
|
|
| from . import ValidationResult, load_solution, output_result, success, failure |
|
|
|
|
| DIMENSION = 12 |
| TOL_DET = 1e-12 |
| MAX_ABS_ENTRY = 1e6 |
| MAX_COND = 1e12 |
|
|
|
|
| def sphere_volume(r: float, n: int) -> float: |
| """Volume of n-dimensional ball of radius r.""" |
| return (math.pi ** (n / 2.0)) * (r ** n) / math.gamma(n / 2.0 + 1.0) |
|
|
|
|
| def _float_to_rational(x: float, max_denom: int = 10**9) -> Fraction: |
| """Convert a float to an exact Fraction with bounded denominator.""" |
| return Fraction(x).limit_denominator(max_denom) |
|
|
|
|
| def basis_to_integer_matrix(B: np.ndarray) -> Tuple[IntegerMatrix, float]: |
| """ |
| Convert a floating-point basis matrix to an fpylll IntegerMatrix. |
| |
| Strategy: |
| 1. If all entries are already integers (within tolerance), use them directly. |
| 2. Otherwise, convert entries to rationals, find the LCM of denominators, |
| and scale the entire basis to make it integral. |
| |
| Returns: |
| (A, scale_factor) where A is the IntegerMatrix and scale_factor is the |
| multiplier applied (so the original lattice vector lengths are recovered |
| by dividing integer lattice vector lengths by scale_factor). |
| """ |
| n = B.shape[0] |
|
|
| |
| B_rounded = np.round(B) |
| if np.allclose(B, B_rounded, atol=1e-9): |
| A = IntegerMatrix(n, n) |
| for i in range(n): |
| for j in range(n): |
| A[i, j] = int(B_rounded[i, j]) |
| return A, 1.0 |
|
|
| |
| lcm_denom = 1 |
| fracs = [] |
| for i in range(n): |
| row = [] |
| for j in range(n): |
| f = _float_to_rational(B[i, j]) |
| row.append(f) |
| lcm_denom = math.lcm(lcm_denom, f.denominator) |
| fracs.append(row) |
|
|
| scale = lcm_denom |
|
|
| A = IntegerMatrix(n, n) |
| for i in range(n): |
| for j in range(n): |
| |
| A[i, j] = int(fracs[i][j] * scale) |
|
|
| return A, float(scale) |
|
|
|
|
| def shortest_vector_length(B: np.ndarray) -> float: |
| """ |
| Compute the exact shortest nonzero vector length of the lattice |
| generated by the rows of B, using fpylll's SVP enumeration. |
| |
| Uses LLL reduction followed by Schnorr–Euchner enumeration via |
| fpylll's low-level Enumeration API (avoids the high-level SVP |
| wrapper which requires a strategies file that may not be present |
| in pip-installed fpylll). |
| |
| Args: |
| B: n×n matrix where rows are basis vectors. |
| |
| Returns: |
| The Euclidean length of the shortest nonzero lattice vector. |
| """ |
| A, scale = basis_to_integer_matrix(B) |
| n = A.nrows |
|
|
| |
| LLL.reduction(A) |
|
|
| |
| M = MatGSO(A) |
| M.update_gso() |
|
|
| |
| max_dist = float('inf') |
| for i in range(n): |
| row_norm2 = sum(int(A[i, j]) ** 2 for j in range(n)) |
| if row_norm2 < max_dist: |
| max_dist = row_norm2 |
| max_dist = float(max_dist) |
|
|
| |
| E = Enumeration(M, strategy=EvaluatorStrategy.BEST_N_SOLUTIONS, nr_solutions=1) |
| solutions = E.enumerate(0, n, max_dist, 0) |
|
|
| if solutions: |
| sq_len_scaled = solutions[0][0] |
| return math.sqrt(sq_len_scaled) / scale |
|
|
| |
| |
| return math.sqrt(max_dist) / scale |
|
|
|
|
| def validate(solution: Any) -> ValidationResult: |
| """ |
| Validate a lattice packing in dimension 12. |
| |
| Args: |
| solution: Dict with 'basis' key (12×12 matrix) |
| |
| Returns: |
| ValidationResult with packing density |
| """ |
| 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 = np.array(basis_data, dtype=np.float64) |
| except (ValueError, TypeError) as e: |
| return failure(f"Failed to parse basis: {e}") |
|
|
| if B.ndim != 2: |
| return failure(f"Basis must be 2D array, got {B.ndim}D") |
|
|
| n, m = B.shape |
| if n != DIMENSION or m != DIMENSION: |
| return failure(f"Basis must be {DIMENSION}×{DIMENSION}, got {n}×{m}") |
|
|
| if not np.all(np.isfinite(B)): |
| return failure("Basis contains non-finite entries") |
|
|
| if float(np.max(np.abs(B))) > MAX_ABS_ENTRY: |
| return failure(f"Basis entries too large (>|{MAX_ABS_ENTRY:g}|)") |
|
|
| det = float(np.linalg.det(B)) |
| 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)) |
| if not np.isfinite(cond) or cond > MAX_COND: |
| return failure(f"Basis is ill-conditioned (cond={cond:.3e} > {MAX_COND:g})") |
|
|
| try: |
| min_length = shortest_vector_length(B) |
| except Exception as e: |
| return failure(f"SVP computation failed: {e}") |
|
|
| if not np.isfinite(min_length) or min_length <= 0: |
| return failure("Failed to compute a valid shortest vector length") |
|
|
| packing_radius = min_length / 2.0 |
| density = sphere_volume(packing_radius, DIMENSION) / covolume |
|
|
| return success( |
| f"Lattice in ℝ¹²: shortest vector ≈ {min_length:.8f}, " |
| f"packing density ≈ {density:.12f}", |
| dimension=DIMENSION, |
| determinant=det, |
| covolume=covolume, |
| min_vector_length=min_length, |
| packing_radius=packing_radius, |
| packing_density=density, |
| metric_key="packing_density", |
| ) |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description='Validate lattice packing in dimension 12') |
| parser.add_argument('solution', help='Solution as JSON string or path to JSON file') |
| args = parser.parse_args() |
|
|
| solution = load_solution(args.solution) |
| result = validate(solution) |
| output_result(result) |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|