Download approximation_reference.py from PureOne/Aeonixi-1.0-Shuffled-Regression: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/datasets/PureOne/Aeonixi-1.0-Shuffled-Regression/resolve/main/approximation_reference.py
- Command line
-
hf download hf://datasets/PureOne/Aeonixi-1.0-Shuffled-Regression/approximation_reference.py
-
curl -L -o approximation_reference.py https://huggingface.co/datasets/PureOne/Aeonixi-1.0-Shuffled-Regression/resolve/main/approximation_reference.py
12.4 kB
| """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 | |
| 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)) | |