"""Tests for geometry.algebra.fields: elements of a multiquadratic extension. The independent oracle of this suite is a dyadic-interval evaluator written entirely on the test side: math.isqrt gives the rigorous bracket isqrt(d*4**n)/2**n <= sqrt(d) <= (isqrt(d*4**n)+1)/2**n of width 2**-n, and test-side expression trees (sums of rational multiples of products of square roots) are evaluated with interval arithmetic that widens conservatively, always with Fraction endpoints. The oracle shares no code with the module, so sign() and approx(bits) are checked against an independent source of truth. The norm is the product over every automorphism of the prime tower the value lives in, each generator sqrt(p) flipped to -sqrt(p), so the tower step of norm() and inverse() must use A**2 - p*B**2; the exact norm and inverse laws below double as regression tests for that formula. """ import json import math import random from fractions import Fraction as F from itertools import combinations import pytest from geometry.algebra import fields from geometry.algebra.fields import Ext, ExtError, SurdTriple from geometry.kernels.common import Surd ZERO = F(0) ONE = F(1) def iv_sqrt(d, n): """The rigorous dyadic bracket of sqrt(d) at scale 2**-n via math.isqrt.""" scale = 2 ** n r = math.isqrt(d * scale * scale) return (F(r, scale), F(r + 1, scale)) def iv_add(a, b): # conservative widening of a sum of intervals return (a[0] + b[0], a[1] + b[1]) def iv_mul(a, b): # conservative widening across the four corner products corners = (a[0] * b[0], a[0] * b[1], a[1] * b[0], a[1] * b[1]) return (min(corners), max(corners)) def iv_neg(a): return (-a[1], -a[0]) def iv_eval(node, n): """Evaluate a test-side expression tree as a dyadic interval at scale n.""" kind = node[0] if kind == "rat": return (node[1], node[1]) if kind == "sqrt": return iv_sqrt(node[1], n) if kind == "neg": return iv_neg(iv_eval(node[1], n)) out, op = ((ZERO, ZERO), iv_add) if kind == "add" else ((ONE, ONE), iv_mul) for sub in node[1]: out = op(out, iv_eval(sub, n)) return out def iv_sign(iv): # 1, -1, or 0 when the interval does not exclude zero return 1 if iv[0] > 0 else (-1 if iv[1] < 0 else 0) def oracle_decides(tree, n_start=12, n_cap=64): """Refine the oracle bracket until it excludes zero; return (sign, interval).""" n = n_start iv = iv_eval(tree, n) while iv_sign(iv) == 0 and n < n_cap: n *= 2 iv = iv_eval(tree, n) return iv_sign(iv), iv PRIMES = (2, 3, 5, 7, 11) # atoms span at most two primes, so seeded expressions stay within the limit SQUAREFREE_ATOMS = tuple(sorted( set(PRIMES) | {p * q for p, q in combinations(PRIMES, 2)})) def rand_element(rng, primes=None): """A random nonzero element whose basis is exactly the given primes.""" primes = list(primes) if primes else list(rng.sample(PRIMES, rng.randint(1, 3))) monos = [math.prod(c) for t in range(len(primes) + 1) for c in combinations(primes, t)] full = monos[-1] x = Ext.zero() for d in monos: if d != full and rng.randint(0, 2): continue c = F(rng.randint(1, 9), rng.choice((1, 2, 3))) * rng.choice((1, -1)) x = x + (Ext.of(c) if d == 1 else Ext.of(c) * Ext.monomial(d)) return x def rand_expr(rng, depth=2): """A random expression as an Ext and as a mirror tree for the oracle.""" if depth == 0: c = F(rng.randint(1, 9), rng.choice((1, 2, 3))) * rng.choice((1, -1)) if rng.randint(0, 100) < 30: return Ext.of(c), ("rat", c) d = rng.choice(SQUAREFREE_ATOMS) return Ext.of(c) * Ext.sqrt(d), ("mul", [("rat", c), ("sqrt", d)]) kind = rng.choice(("add", "add", "mul", "mul", "neg")) a, ta = rand_expr(rng, depth - 1) if kind == "neg": return -a, ("neg", ta) b, tb = rand_expr(rng, depth - 1) return (a + b, ("add", [ta, tb])) if kind == "add" else (a * b, ("mul", [ta, tb])) def test_field_axioms_on_seeded_elements(): """Distributivity, additive inverses and powers on 60 seeded elements.""" rng = random.Random(23) for _ in range(60): x, y, z = rand_element(rng), rand_element(rng), rand_element(rng) assert (x + y) * z == x * z + y * z and x * (y + z) == x * y + x * z assert x * (-x) == -(x * x) and x / 1 == x and x / Ext.one() == x assert x - y + y == x and -(-x) == x and x ** 0 == Ext.one() assert x ** 3 == x * x * x and x + Ext.zero() == x and Ext.one() * x == x def test_inverse_field_laws(): """Exact inverse laws on random multiquadratic elements, exact comparisons.""" rng = random.Random(23) for _ in range(40): x, y = rand_element(rng), rand_element(rng) assert x.inverse() * x == Ext.one() assert (x.inverse() * x).to_json() == {"sq": {"1": "1"}} assert Ext.one() / x == x.inverse() assert (x * y).inverse() == y.inverse() * x.inverse() assert x.sign() == x.inverse().sign() def test_tower_regression_exact_values(): """The exact norm and inverse of the two elements of the reported defect.""" assert (Ext.of(-5) + Ext.of(F(4, 3)) * Ext.sqrt(11)).norm() == F(49, 9) x = Ext.of(F(-7, 3)) * Ext.sqrt(22) assert x.inverse() == Ext.of(F(-3, 154)) * Ext.sqrt(22) assert x * x.inverse() == Ext.one() and x.sign() == x.inverse().sign() == -1 def test_canonical_form_is_stable_across_constructions(): """Values built in different ways agree and print with identical terms.""" assert Ext.sqrt(8) == 2 * Ext.sqrt(2) and str(Ext.sqrt(8)) == "2*sqrt(2)" assert Ext.sqrt(8).to_json() == (2 * Ext.sqrt(2)).to_json() assert Ext.sqrt(12) - Ext.sqrt(3) == Ext.sqrt(3) assert str(Ext.sqrt(12) - Ext.sqrt(3)) == "sqrt(3)" assert Ext.sqrt(F(1, 2)) == Ext.sqrt(2) / 2 assert str(Ext.sqrt(F(1, 2))) == "1/2*sqrt(2)" and str(Ext.sqrt(18)) == "3*sqrt(2)" assert Ext.sqrt(2) * Ext.sqrt(3) == Ext.sqrt(6) assert (Ext.sqrt(2) * Ext.sqrt(3)).to_json() == Ext.sqrt(6).to_json() assert (Ext.sqrt(2) + Ext.sqrt(3)) * (Ext.sqrt(2) - Ext.sqrt(3)) == Ext.of(-1) def test_basic_constructors_and_predicates(): """zero, one, of, monomial build canonical elements; is_zero, is_rational are methods.""" z = Ext.zero() assert z.is_zero() and z.is_rational() assert str(z) == "0" and repr(z) == "Ext(0)" assert Ext.one() == 1 and 1 == Ext(1) and Ext.one().is_zero() is False assert Ext.monomial(1) == Ext.one() and Ext.monomial(6) == Ext.sqrt(6) assert str(Ext.monomial(2)) == "sqrt(2)" assert Ext.of(F(3, 4)).to_fraction() == F(3, 4) and Ext("3/4") == F(3, 4) assert Ext(" -2/5 ") == F(-2, 5) and Ext(F(2, 4)) == Ext.of(F(1, 2)) assert Ext.sqrt(6).is_rational() is False and Ext.sqrt(6).is_zero() is False assert Ext.of(F(3, 2)).inverse().to_fraction() == F(2, 3) assert Ext.one() / Ext.sqrt(2) == Ext.sqrt(2) / 2 def test_sqrt_on_seeded_rationals(): """sqrt squares back exactly; perfect squares collapse; products combine.""" assert Ext.sqrt(F(4, 9)) == F(2, 3) and Ext.sqrt(16) == 4 and Ext.sqrt(0).is_zero() rng = random.Random(29) for _ in range(60): c = F(rng.randint(1, 30), rng.randint(1, 9)) r = c * c root = Ext.sqrt(r) assert root.is_rational() and root.to_fraction() == c and root * root == Ext.of(r) q = F(rng.randint(1, 200), rng.randint(1, 17)) s = Ext.sqrt(q) assert s * s == Ext.of(q) and s.sign() == 1 rng = random.Random(31) for _ in range(50): a = F(rng.randint(1, 30), rng.randint(1, 7)) b = F(rng.randint(1, 30), rng.randint(1, 7)) p = Ext.sqrt(a) * Ext.sqrt(b) assert p * p == Ext.of(a * b) and p.sign() == 1 assert Ext.sqrt(a / b) * Ext.sqrt(a * b) == Ext.of(a) def test_sign_basic_laws(): """sign(0)=0, sign(-x)=-sign(x), sign is multiplicative, rationals keep their sign.""" rng = random.Random(33) assert Ext.zero().sign() == 0 for _ in range(60): x, y = rand_element(rng), rand_element(rng) assert x.sign() in (-1, 1) and (-x).sign() == -x.sign() assert (x - x).sign() == 0 and (x * y).sign() == x.sign() * y.sign() for _ in range(40): c = F(rng.randint(-20, 20), rng.randint(1, 7)) assert Ext.of(c).sign() == ((c > 0) - (c < 0)) def test_severe_cancellation_expands_to_a_pell_pair(): """(sqrt(2)+sqrt(3))**8 - 9602 collapses to 1960*sqrt(6) - 4801 of a Pell identity. x**8 = 4801 + 1960*sqrt(6), so y = x**8 - 9602 = 1960*sqrt(6) - 4801, and 4801**2 - 6*1960**2 = 23049601 - 23049600 = 1, hence 4801 > 1960*sqrt(6) and the oracle brackets y strictly below zero near -1/(4801+1960*sqrt(6)). """ x = Ext.sqrt(2) + Ext.sqrt(3) assert x ** 4 == Ext.of(49) + Ext.of(20) * Ext.sqrt(6) assert x ** 8 == Ext.of(4801) + Ext.of(1960) * Ext.sqrt(6) y = x ** 8 - 9602 assert y == Ext.of(1960) * Ext.sqrt(6) - 4801 y4 = x ** 4 - 98 # 49**2 - 6*20**2 = 1 as well assert y4 == Ext.of(20) * Ext.sqrt(6) - 49 tree = ("add", [("rat", F(-4801)), ("mul", [("rat", F(1960)), ("sqrt", 6)])]) decided, iv = oracle_decides(tree) assert decided == -1 and abs(iv[1]) < F(1, 9000) tree4 = ("add", [("rat", F(-49)), ("mul", [("rat", F(20)), ("sqrt", 6)])]) assert oracle_decides(tree4)[0] == -1 def test_severe_cancellation_and_isolation_signs_are_exact(): """The tiny Pell pair and a decidable two-prime combination keep their true signs.""" x = Ext.sqrt(2) + Ext.sqrt(3) y = x ** 8 - 9602 assert y.sign() == -1 and (-y).sign() == 1 and y.norm() == 1 y4 = x ** 4 - 98 assert y4.sign() == -1 and y4.norm() == 1 x2 = Ext.of(-5) - Ext.of(2) * Ext.sqrt(2) + Ext.of(F(7, 2)) * Ext.sqrt(5) assert x2.sign() == -1 # the oracle decides -1 and the exact norm certifies it def test_sign_confirmed_by_dyadic_oracle(): """sign() must agree with the independent oracle on at least 150 seeded elements.""" rng = random.Random(101) confirmed = 0 total = 0 refusals = 0 while total < 175: x, tree = rand_expr(rng) if x.is_zero(): continue total += 1 decided, _ = oracle_decides(tree, n_start=14, n_cap=64) if decided == 0: continue try: assert x.sign() == decided confirmed += 1 except ExtError: refusals += 1 assert confirmed >= 150 and refusals == 0 def test_approx_inside_dyadic_oracle(): """approx(bits) must lie inside the oracle bracket for bits 10, 20 and 30.""" rng = random.Random(102) checked = 0 for _ in range(160): x, tree = rand_expr(rng) if x.is_zero(): continue for bits in (10, 20, 30): lo, hi = iv_eval(tree, bits) assert lo <= x.approx(bits) <= hi checked += 1 assert checked >= 400 def test_norm_of_rationals_and_single_quadratic_surd_formula(): """A rational has an empty tower, so its norm is the value itself; for one prime the norm in Q(sqrt(m)) is a*a - b*b*m, as in kernels.Surd.norm.""" rng = random.Random(10) for _ in range(40): c = F(rng.randint(-9, 9), 3) assert Ext.of(c).norm() == c assert Ext.zero().norm() == 0 rng = random.Random(37) for _ in range(60): m = rng.choice((2, 3, 5, 7, 11)) a = F(rng.randint(-6, 6)) b = F(rng.randint(-5, 5), rng.randint(1, 3)) x = Ext.of(a) + Ext.of(b) * Ext.sqrt(m) if b == 0: assert x.is_rational() and x.norm() == a else: assert x.norm() == a * a - b * b * m assert x.norm() == Surd.make(a, b, m).norm() assert Ext.monomial(2).norm() == -2 and (2 * Ext.sqrt(2)).norm() == -8 def test_norm_equals_product_of_conjugate_flips(): """norm() is the product of conjugate_flips(), for 1, 2 and 3 basis primes.""" rng = random.Random(41) pool = (2, 3, 5, 7, 11) for k in (1, 2, 3): for _ in range(10): x = rand_element(rng, primes=pool[:k]) flips = x.conjugate_flips() assert len(flips) == 2 ** k prod = Ext.one() for fl in flips: prod = prod * fl assert prod.is_rational() and prod.to_fraction() == x.norm() != 0 x = Ext.sqrt(2) + Ext.sqrt(3) assert (x ** 8 - 9602).norm() == 1 assert Ext.monomial(30030).norm() == F(30030) ** 32 def test_norm_multiplicative_and_rational_scaling(): """In one shared prime basis the norm is multiplicative and scaling exact. The norm lives in the tower of the primes that occur, so the product law needs all three elements in the same tower: rand_element forces the full product monomial into each factor, and the guard keeps only products that cancel none of the shared primes. """ rng = random.Random(43) pool = (2, 3, 5, 7, 11) same_basis = 0 for _ in range(40): primes = pool[: rng.randint(1, 3)] x, y = rand_element(rng, primes), rand_element(rng, primes) product = x * y if len(product.conjugate_flips()) == 2 ** len(primes): assert product.norm() == x.norm() * y.norm() same_basis += 1 n_flips = len(x.conjugate_flips()) # n_flips = 2**k for k basis primes r = F(rng.randint(-8, 8), rng.randint(1, 5)) assert (r * x).norm() == r ** n_flips * x.norm() assert same_basis >= 25 # seed 43 gives 26 exact multiplicativity checks def test_surd_triple_shape_and_bad_radicands(): """as_surd gives the (a, b, m) triple; multi-prime and bad radicands refuse.""" x = Ext.of(F(3, 2)) - Ext.of(2) * Ext.sqrt(3) assert x.as_surd() == SurdTriple(F(3, 2), F(-2), F(3)) assert Ext.of(F(5)).as_surd() == SurdTriple(F(5), F(0), F(0)) assert Ext.zero().as_surd() == SurdTriple(F(0), F(0), F(0)) with pytest.raises(ExtError, match="single quadratic"): (Ext.sqrt(2) + Ext.sqrt(3)).as_surd() with pytest.raises(ExtError, match="negative radicand"): Ext.from_surd(Surd(F(1), F(1), F(-3))) with pytest.raises(ExtError, match="not an integer after reduction"): Ext.from_surd(Surd(F(1), F(1), F(1, 2))) def test_cross_family_surd_roundtrip_and_arithmetic(): """Ext.from_surd must round-trip and match kernels.Surd sums and products.""" rng = random.Random(61) cases = 0 for _ in range(60): m = rng.choice((2, 3, 5, 6, 7, 8, 12, 18)) a = F(rng.randint(-6, 6)) b = F(rng.randint(-5, 5), rng.randint(1, 3)) if rng.randint(0, 4) == 0: b = F(0) # the canonical rational case b == 0 s = Surd.make(a, b, m) e = Ext.from_surd(s) if m == 6 and b != 0: with pytest.raises(ExtError, match="single quadratic"): e.as_surd() # squarefree 6 = 2*3 spans two primes by design else: assert Ext.from_surd(e.as_surd()) == e if b == 0: assert e.as_surd() == SurdTriple(s.a, F(0), F(0)) and e == s.a s2 = Surd.make(F(rng.randint(-6, 6)), F(rng.randint(-5, 5), rng.randint(1, 3)), m) e2 = Ext.from_surd(s2) assert Ext.from_surd(s + s2) == e + e2 and Ext.from_surd(s * s2) == e * e2 cases += 1 assert cases == 60 def test_cross_family_inverse_and_norm_match_surd(): """Ext.inverse equals the Surd reciprocal; the norms follow the documented tower convention, so Ext.norm = Surd.norm ** (2**(k-1)) for k tower primes.""" rng = random.Random(61) for _ in range(60): m = rng.choice((2, 3, 5, 6, 7, 8, 12, 18)) s = Surd.make(F(rng.randint(-6, 6)), F(rng.randint(-5, 5), rng.randint(1, 3)), m) e = Ext.from_surd(s) if s.norm() != 0: assert e.inverse() == Ext.from_surd(Surd(F(1)) / s) if e.is_rational(): assert e.norm() == s.a and s.norm() == s.a * s.a else: assert e.norm() == s.norm() ** (len(e.conjugate_flips()) // 2) def test_json_roundtrip_on_seeded_elements(): """to_json/from_json round-trip through json.dumps on 40 seeded elements.""" rng = random.Random(53) seen = 0 for _ in range(40): x = rand_element(rng) payload = json.loads(json.dumps(x.to_json())) assert payload == x.to_json() and set(payload) == {"sq"} for key, value in payload["sq"].items(): assert isinstance(key, str) and isinstance(value, str) assert Ext.from_json(payload) == x seen += 1 assert seen == 40 exact = Ext.of(F(3, 2)) - Ext.of(2) * Ext.sqrt(6) assert exact.to_json() == {"sq": {"1": "3/2", "6": "-2"}} assert str(exact) == "3/2 -2*sqrt(6)" assert Ext.from_json({"sq": {"1": "3/2", "6": "-2"}}) == exact assert Ext.zero().to_json() == {"sq": {}} and Ext.from_json({}) == Ext.zero() def test_from_json_rejects_bad_encodings(): """The decoder must refuse unknown keys, bad indices, and inexact values.""" bad = [([1, 2], "must be a mapping"), ({"terms": {}}, "unknown key"), ({"sq": 5}, "sq block must be a mapping"), ({"sq": {"6": "0"}}, "zero coefficient"), ({"sq": {"12": "1"}}, "not a squarefree positive integer"), ({"sq": {"-2": "1"}}, "not a squarefree index"), ({"sq": {"2.5": "1"}}, "not a squarefree index"), ({"sq": {2: "1", "2": "1"}}, "duplicate information"), ({"sq": {True: "1"}}, "keys must be ASCII strings"), ({"sq": {"2": "3.5"}}, "bad coefficient"), ({"sq": {"2": True}}, "exact ASCII strings")] for payload, msg in bad: with pytest.raises(ExtError, match=msg): Ext.from_json(payload) def test_rejects_inexact_and_invalid_input(): """Floats, booleans, bad strings, zero divisors and bad indices are rejected.""" half = 3 / 4 # a float value produced without a float literal assert isinstance(half, float) guarded = [(lambda: Ext(half), TypeError, "exact arithmetic"), (lambda: Ext.sqrt(half), TypeError, "exact arithmetic"), (lambda: Ext.of(1) * half, TypeError, "exact arithmetic"), (lambda: Ext(True), TypeError, "booleans"), (lambda: Ext.of(False), TypeError, "booleans"), (lambda: Ext.sqrt(-1), ExtError, "negative radicand"), (lambda: Ext.sqrt(F(-3, 4)), ExtError, "negative radicand"), (lambda: Ext.one() / Ext.zero(), ExtError, "division by zero"), (lambda: Ext.zero().inverse(), ExtError, "division by zero"), (lambda: Ext.sqrt(2) / 0, ExtError, "division by zero"), (lambda: Ext("1.25"), ExtError, "not an exact integer or fraction"), (lambda: Ext("1/0"), ExtError, "not an exact integer or fraction"), (lambda: Ext.monomial(0), ExtError, "monomial index"), (lambda: Ext.monomial(-6), ExtError, "monomial index"), (lambda: Ext.sqrt(2) ** -1, ExtError, "negative powers"), (lambda: Ext.sqrt(2) ** True, ExtError, "non-negative integer"), (lambda: Ext.sqrt(2) ** F(2), ExtError, "non-negative integer"), (lambda: Ext.sqrt(2).approx(0), ExtError, "positive number of bits"), (lambda: Ext.sqrt(2).approx(True), ExtError, "positive number of bits"), (lambda: Ext.sqrt(2).to_fraction(), ExtError, "value is irrational")] for action, exc, msg in guarded: with pytest.raises(exc, match=msg): action() assert not (Ext(1) == True) and Ext(1) != True def test_prime_basis_limit_is_six_primes(): """More than six independent primes must be refused with ExtError.""" assert fields.MAX_INDEPENDENT_PRIMES == 6 assert fields.TRIAL_DIVISION_LIMIT == 10 ** 6 x7 = Ext.one() for p in (2, 3, 5, 7, 11, 13, 17): x7 = x7 * Ext.sqrt(p) assert x7 == Ext.monomial(510510) assert x7.sign() == 1 # the coarse enclosure already excludes zero with pytest.raises(ExtError, match="limit of 6 primes"): x7.norm() # 1429 - 2*sqrt(510510) = 1/(1429 + 2*sqrt(510510)) > 0, but its first # enclosure brackets zero, so the isolating bound is needed and seven # primes push it past the limit near_zero = Ext.of(1429) - Ext.of(2) * x7 with pytest.raises(ExtError, match="more than 6 independent primes"): near_zero.sign() six = x7 / Ext.sqrt(17) assert six == Ext.monomial(30030) and six.sign() == 1 def test_comparison_matches_sign_and_sorting(): """Ordering must agree with sign(y-x), sort consistently, and be total.""" rng = random.Random(79) equal_pairs = 0 for i in range(100): x = rand_element(rng) y = x + Ext.zero() if i % 9 == 0 else rand_element(rng) s = (y - x).sign() assert (x < y) == (s > 0) and (x > y) == (s < 0) assert (x <= y) == (s >= 0) and (x >= y) == (s <= 0) assert not (x < y and y < x) and (x < y) + (x == y) + (x > y) == 1 if s == 0: equal_pairs += 1 assert equal_pairs >= 5 xs = [rand_element(rng) for _ in range(40)] ordered = sorted(xs) for i in range(len(ordered) - 1): assert ordered[i] <= ordered[i + 1] def test_equality_hash_printing_and_negative_control(): """Equality is canonical, hash matches Fractions, printing is exact, and the false claim sqrt(2)+sqrt(3) == sqrt(5) must fail with the oracle sign.""" a = Ext.of(F(1, 2)) assert a == F(1, 2) and a == Ext(F(2, 4)) and hash(a) == hash(F(1, 2)) assert not (a == F(2, 3)) s2 = Ext.sqrt(2) assert s2 == Ext.sqrt(8) / 2 and s2 == Ext.monomial(2) assert hash(s2) == hash(Ext.sqrt(8) / 2) assert len({s2, Ext.sqrt(8) / 2, Ext.monomial(2)}) == 1 assert Ext.sqrt(2) != Ext.sqrt(3) assert str(Ext.of(F(1, 2)) * s2) == "1/2*sqrt(2)" assert str(Ext.sqrt(3) - s2) == "-sqrt(2) +sqrt(3)" assert str(Ext.one() + s2) == "1 +sqrt(2)" assert repr(Ext.one() + s2) == "Ext(1 +sqrt(2))" and str(Ext.of(F(-1, 3))) == "-1/3" claimed = Ext.monomial(5) true_value = Ext.monomial(2) + Ext.monomial(3) assert not (true_value == claimed) and true_value != claimed assert true_value.to_json() != claimed.to_json() diff = true_value - claimed assert not diff.is_zero() and diff.sign() == 1 # (sqrt2+sqrt3)**2 = 5 + 2*sqrt6 > 5 tree = ("add", [("mul", [("rat", F(1)), ("sqrt", 2)]), ("mul", [("rat", F(1)), ("sqrt", 3)]), ("neg", ("mul", [("rat", F(1)), ("sqrt", 5)]))]) decided, iv = oracle_decides(tree) assert decided == 1 and iv[0] > 0 and diff.sign() == decided