"""Numerical test of the quartic chamber description and the complex cubic description (IIS-L-26806)."""
import numpy as np, random, cmath
rng = np.random.default_rng(7)

def strictly_convex(pts, tol=1e-9):
    """All points are vertices of their convex hull, no three hull-collinear (2 points: distinct)."""
    pts = list(pts); n = len(pts)
    if n == 2: return abs(pts[0] - pts[1]) > tol
    c = sum(pts) / n
    pts.sort(key=lambda z: cmath.phase(z - c))
    if min(abs(z - c) for z in pts) < tol: return False
    for i in range(n):
        a, b, d = pts[i - 1], pts[i], pts[(i + 1) % n]
        if ((b - a).conjugate() * (d - b)).imag <= tol: return False
    return True

def direct(p, q, r):
    P = np.poly1d([1, 0, p, q, r])
    return all(strictly_convex(P.deriv(k).roots) for k in range(3))

def criterion(p, q, r):
    if p == 0 or q == 0 or 8 * p**3 + 27 * q**2 <= 0: return False
    q = abs(q)
    Q = lambda x: x**4 + p * x**2 + q * x
    crit = [z.real for z in np.roots([4, 0, 2 * p, q]) if abs(z.imag) < 1e-9]
    rp = -min(Q(x) for x in crit)
    g = lambda b: 20 * b**3 + 2 * p * b - q
    hi = 1.0
    while g(hi) <= 0: hi *= 2
    lo = hi
    while g(lo) > 0 and lo > 1e-12: lo /= 2          # last sign change before hi
    bc = max(z.real for z in np.roots([20, 0, 2 * p, -q]) if abs(z.imag) < 1e-9 and z.real > 0)
    rm = -Q(bc)
    return r > rp or r < rm

bad = 0; tot = 0; inside = 0; signs = set(); near = 0
for _ in range(200000):
    p, q, r = rng.normal(0, 2), rng.normal(0, 2), rng.normal(0, 4)
    d, c = direct(p, q, r), criterion(p, q, r)
    tot += 1; inside += d
    if d: signs.add((p > 0, q > 0, r > 0))
    if d != c:
        # ignore points within numerical tolerance of a boundary
        if any(direct(p + e1, q + e2, r + e3) != d for e1, e2, e3 in [(1e-5,0,0),(-1e-5,0,0),(0,1e-5,0),(0,-1e-5,0),(0,0,1e-5),(0,0,-1e-5)]): near += 1
        else: bad += 1; print('MISMATCH', p, q, r, d, c)
print(f'quartics: {tot} samples, {inside} in the locus, sign patterns seen {len(signs)}, mismatches {bad}, boundary-close {near}')

bad = 0; n_in = 0
for _ in range(100000):
    w = complex(rng.normal(0, 2), rng.normal(0, 0.7))
    roots = np.roots([1, 0, -3, w])
    d = strictly_convex(roots, 1e-7)
    c = not (abs(w.imag) < 1e-12 and abs(w.real) <= 2)
    n_in += d
    if d != c: bad += 1
for x in np.linspace(-2, 2, 2001):
    if strictly_convex(np.roots([1, 0, -3, x]), 1e-7): bad += 1
print(f'cubics: forbidden set = [-2,2] check, mismatches {bad}')
