File size: 7,077 Bytes
848d4b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env python3
"""
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]

    # Check if already integer
    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

    # Convert to rationals and find LCM of all denominators
    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):
            # fracs[i][j] * scale is guaranteed to be an integer
            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-reduce (makes subsequent SVP enumeration much faster)
    LLL.reduction(A)

    # Compute Gram-Schmidt information
    M = MatGSO(A)
    M.update_gso()

    # Upper bound for enumeration: squared norm of shortest basis vector
    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)

    # Exact SVP via Schnorr–Euchner enumeration
    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

    # Fallback: shortest basis vector (this branch should not be reached
    # after LLL reduction, since the first basis vector is always found)
    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()