File size: 22,849 Bytes
166cfb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
"""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