File size: 12,431 Bytes
6635906 | 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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | """Exact-rational reference FPTAS for partial shuffled linear regression.
The implementation follows partial_proof.md, including allowed edges,
positive edge confidence weights, nonnegative additive penalties, intrinsic
source/response rank reduction, and a squared-objective (1 + epsilon) bound.
It is exhaustive and intended for small verification instances, not as a
large-scale solver. SymPy is used for exact rational preprocessing only;
grid evaluation and the cubic Hungarian oracle use fractions.Fraction.
Run: python approximation_reference.py
"""
from dataclasses import dataclass
from fractions import Fraction as F
from itertools import combinations, permutations, product
from math import isqrt
import json
import sympy as sp
def frac(x):
if isinstance(x, (float, sp.Float)):
raise TypeError("Use integers or exact rational values, not floats")
q = sp.Rational(x)
return F(int(q.p), int(q.q))
def matrix_fraction(A):
return [[frac(A[i, j]) for j in range(A.cols)] for i in range(A.rows)]
def mm(A, B):
return [[sum((A[i][k] * B[k][j] for k in range(len(B))), F(0))
for j in range(len(B[0]))] for i in range(len(A))]
def floor_dyadic_sqrt(q):
q = frac(q)
if q <= 0:
raise ValueError("A positive rational is required")
h = F(1)
while h * h > q:
h /= 2
while 4 * h * h <= q:
h *= 2
return h
def ceil_dyadic_sqrt(q):
h = floor_dyadic_sqrt(q)
return h if h * h == q else 2 * h
def hungarian(cost):
"""Minimum square assignment, with exact Fraction costs, O(n^3)."""
n = len(cost)
if n == 0:
return F(0), []
if any(len(row) != n for row in cost):
raise ValueError("The cost matrix must be square")
u, v = [F(0)] * (n + 1), [F(0)] * (n + 1)
p, way = [0] * (n + 1), [0] * (n + 1)
for i in range(1, n + 1):
p[0] = i
j0 = 0
minv, used = [None] * (n + 1), [False] * (n + 1)
while True:
used[j0] = True
i0, delta, j1 = p[j0], None, 0
for j in range(1, n + 1):
if not used[j]:
cur = cost[i0 - 1][j - 1] - u[i0] - v[j]
if minv[j] is None or cur < minv[j]:
minv[j], way[j] = cur, j0
if delta is None or minv[j] < delta:
delta, j1 = minv[j], j
if delta is None:
raise RuntimeError("No augmenting assignment path")
for j in range(n + 1):
if used[j]:
u[p[j]] += delta
v[j] -= delta
elif minv[j] is not None:
minv[j] -= delta
j0 = j1
if p[j0] == 0:
break
while True:
j1 = way[j0]
p[j0] = p[j1]
j0 = j1
if j0 == 0:
break
assignment = [(p[j] - 1, j - 1) for j in range(1, n + 1)]
return sum((cost[i][j] for i, j in assignment), F(0)), assignment
def k_matching(costs, N, M, k):
"""Dictionary entries are allowed nonnegative edge costs."""
forbidden = F(1) + sum(costs.values(), F(0))
n = N + M - k
square = [[F(0) for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
if i < N and j < M:
square[i][j] = costs.get((i, j), forbidden)
elif i >= N and j >= M:
square[i][j] = forbidden
value, assignment = hungarian(square)
if value >= forbidden:
return None
real = tuple(sorted((i, j) for i, j in assignment if i < N and j < M))
if len(real) != k or any(edge not in costs for edge in real):
raise AssertionError("Padding invariant failed")
return value, real
@dataclass
class Result:
squared_cost: F
matching: tuple
coefficients: list
source_rank: int
response_rank: int
epsilon: F
coarse_squared_cost: F
candidates: int
def solve_fptas(X, Y, k, epsilon=F(1, 2), allowed=None,
weights=None, penalties=None, candidate_limit=None):
Xs, Ys = sp.Matrix(X), sp.Matrix(Y)
if any(isinstance(x, sp.Float) for x in list(Xs) + list(Ys)):
raise TypeError("Use integers or exact rational matrix entries, not floats")
N, d, M, m = Xs.rows, Xs.cols, Ys.rows, Ys.cols
eps = frac(epsilon)
if not (1 <= k <= min(N, M)) or not (0 < eps <= 1):
raise ValueError("Require 1 <= k <= min(N,M), 0 < epsilon <= 1")
edge_set = set(product(range(N), range(M))) if allowed is None else set(allowed)
if any(not (0 <= i < N and 0 <= j < M) for i, j in edge_set):
raise ValueError("Invalid edge index")
weights, penalties = weights or {}, penalties or {}
a = {e: frac(weights.get(e, 1)) for e in edge_set}
b = {e: frac(penalties.get(e, 0)) for e in edge_set}
if any(q <= 0 for q in a.values()) or any(q < 0 for q in b.values()):
raise ValueError("Require strictly positive confidence and nonnegative penalties")
pivots = tuple(Xs.rref()[1])
response_rows = tuple(Ys.T.rref()[1])
p, t = len(pivots), len(response_rows)
zero_costs = {e: a[e] * sum((frac(Ys[e[1], c]) ** 2 for c in range(m)), F(0)) + b[e]
for e in edge_set}
initial = k_matching(zero_costs, N, M, k)
if initial is None:
raise ValueError("No allowed k-matching exists")
if p == 0 or t == 0 or initial[0] == 0:
return Result(initial[0], initial[1], [[F(0)] * m for _ in range(d)],
p, t, eps, initial[0], 1)
Xr = Xs[:, list(pivots)]
H = Ys[list(response_rows), :]
L, D = (H * H.T).LDLdecomposition(hermitian=False)
hs = [ceil_dyadic_sqrt(frac(D[c, c])) for c in range(t)]
R = L.T.inv() * sp.diag(*[sp.Rational(h.denominator, h.numerator) for h in hs])
Ts = R.T * H
Ks = Ts * Ts.T
assert all(Ks[c, q] == 0 for c in range(t) for q in range(t) if c != q)
assert all(F(1, 4) <= frac(Ks[c, c]) <= 1 for c in range(t))
Zs = Ys * Ts.T * Ks.inv()
assert Zs * Ts == Ys
Z, T = matrix_fraction(Zs), matrix_fraction(Ts)
metric = [frac(Ks[c, c]) for c in range(t)]
best_value, best_matching = initial
best_A = [[F(0)] * t for _ in range(p)]
candidates = 1
def evaluate(pred, A):
nonlocal best_value, best_matching, best_A, candidates
candidates += 1
if candidate_limit is not None and candidates > candidate_limit:
raise RuntimeError("Candidate limit reached; no FPTAS result returned")
costs = {(i, j): a[i, j] * sum((metric[c] * (pred[i][c] - Z[j][c]) ** 2
for c in range(t)), F(0)) + b[i, j]
for i, j in edge_set}
value, matching = k_matching(costs, N, M, k)
if value < best_value:
best_value, best_matching, best_A = value, matching, A
anchors = []
for r in range(1, min(p, k) + 1):
for B in combinations(range(N), r):
XB = Xr[list(B), :]
if XB.rank() != r:
continue
inverse_s = XB.T * (XB * XB.T).inv()
inverse, C = matrix_fraction(inverse_s), matrix_fraction(Xr * inverse_s)
for J in permutations(range(M), r):
if any((B[l], J[l]) not in edge_set for l in range(r)):
continue
P0 = [Z[j][:] for j in J]
evaluate(mm(C, P0), mm(inverse, P0))
anchors.append((r, B, J, inverse, C, P0))
coarse = best_value
if coarse != 0:
Ubar = ceil_dyadic_sqrt(coarse)
eta = floor_dyadic_sqrt(2 * eps)
h = isqrt(t)
if h * h < t:
h += 1
Q = 0
while 4 ** Q < 16 * (p + 1) * k:
Q += 1
for r, B, J, inverse, C, P0 in anchors:
delta = eta / (r * h)
grid_max = (4 * delta.denominator + delta.numerator - 1) // delta.numerator
base = [2 * Ubar / ceil_dyadic_sqrt(a[B[l], J[l]]) for l in range(r)]
for qs in product(range(Q + 1), repeat=r):
scales = [base[l] / (2 ** qs[l]) for l in range(r)]
for theta in product(range(-grid_max, grid_max + 1), repeat=r * t):
P = [[P0[l][c] + scales[l] * delta * theta[l * t + c]
for c in range(t)] for l in range(r)]
evaluate(mm(C, P), mm(inverse, P))
reduced_W = mm(best_A, T)
W = [[F(0)] * m for _ in range(d)]
for q, original in enumerate(pivots):
W[original] = reduced_W[q]
return Result(best_value, best_matching, W, p, t, eps, coarse, candidates)
def exact_optimum(X, Y, k, allowed=None, weights=None, penalties=None):
"""Independent exhaustive matching and exact weighted-LS oracle for tiny tests."""
Xs, Ys = sp.Matrix(X), sp.Matrix(Y)
N, M = Xs.rows, Ys.rows
edges = set(product(range(N), range(M))) if allowed is None else set(allowed)
weights, penalties = weights or {}, penalties or {}
best = None
for I in combinations(range(N), k):
A = Xs[list(I), :]
for J in permutations(range(M), k):
P = tuple(zip(I, J))
if any(e not in edges for e in P):
continue
alphas = [sp.Rational(weights.get(e, 1)) for e in P]
Aw = sp.diag(*alphas)
B = Ys[list(J), :]
G = A.T * Aw * A
W = G.pinv() * A.T * Aw * B
E = A * W - B
value = frac(sum(alphas[q] * sum(E[q, c] ** 2 for c in range(Ys.cols))
+ sp.Rational(penalties.get(P[q], 0)) for q in range(k)))
if best is None or value < best[0]:
best = (value, P)
return best
def run_validation():
cases = [
dict(name="weighted_masked_rank1", X=[[1], [2], [4]], Y=[[1], [3], [9]], k=2,
allowed={(0, 0), (0, 1), (1, 0), (1, 2), (2, 1), (2, 2)},
weights={(0, 0): F(1, 16), (0, 1): 3, (1, 0): 2,
(1, 2): F(1, 4), (2, 1): 5, (2, 2): F(1, 2)},
penalties={(0, 0): F(1, 13), (2, 2): F(1, 7)}),
dict(name="response_rank2", X=[[1], [2]], Y=[[1, 0], [0, 1]], k=2),
dict(name="response_rank_reduction", X=[[1], [2]], Y=[[1, 2, 3], [3, 6, 9]], k=2),
dict(name="source_rank_reduction", X=[[1, 2], [2, 4]], Y=[[1], [3]], k=2),
dict(name="source_rank2_grid", X=[[1, 0], [0, 1], [1, 1]], Y=[[1], [2], [4]], k=3,
allowed={(0, 0), (1, 1), (2, 2)}),
dict(name="rank_zero_source", X=[[0], [0]], Y=[[1], [3]], k=1),
dict(name="zero_fit", X=[[1], [2]], Y=[[3], [6]], k=2),
dict(name="zero_response_penalties", X=[[1], [2]], Y=[[0], [0]], k=1,
penalties={(0, 0): F(2), (0, 1): F(3), (1, 0): F(4), (1, 1): F(5)}),
]
report = []
for spec in cases:
name = spec.pop("name")
result = solve_fptas(**spec, epsilon=F(1, 2), candidate_limit=100000)
exact = exact_optimum(**spec)
assert exact is not None
assert exact[0] <= result.squared_cost <= F(3, 2) * exact[0]
# Direct substitution checks the returned original-coordinate matrix.
Xs, Ys, Ws = sp.Matrix(spec["X"]), sp.Matrix(spec["Y"]), sp.Matrix(result.coefficients)
weights, penalties = spec.get("weights", {}), spec.get("penalties", {})
direct = sum(sp.Rational(weights.get((i, j), 1)) * sum(
((Xs * Ws)[i, c] - Ys[j, c]) ** 2 for c in range(Ys.cols))
+ sp.Rational(penalties.get((i, j), 0)) for i, j in result.matching)
assert frac(direct) == result.squared_cost
report.append(dict(name=name, exact_squared=str(exact[0]),
returned_squared=str(result.squared_cost),
coarse_squared=str(result.coarse_squared_cost),
source_rank=result.source_rank, response_rank=result.response_rank,
candidates=result.candidates, passed=True))
# Independent assignment check, including a mask that forbids a full matching.
assert k_matching({(0, 0): F(1)}, 2, 2, 2) is None
return {"scope": "Small exact-rational verification cases; not a formal proof or a performance benchmark",
"squared_approximation_factor": "3/2", "tests": report}
if __name__ == "__main__":
print(json.dumps(run_validation(), indent=2))
|