"""Numerical regressions and convention tests; these are not RH certificates."""
import json
import unittest

import mpmath as mp

from kernel import (Compact, Gaussian, GaussianCorrelation, arithmetic_entry,
                    dispatch, prime_powers, quadratic, xi, zero_matrix)


class KernelTests(unittest.TestCase):
    def setUp(self):
        self.context = mp.workdps(35)
        self.context.__enter__()

    def tearDown(self):
        self.context.__exit__(None, None, None)

    def test_xi_removable_limits_and_trivial_zero_locations(self):
        self.assertEqual(xi(0), mp.mpf("0.5"))
        self.assertEqual(xi(1), mp.mpf("0.5"))
        for s in (-2, -4, mp.mpc("0.3", "4.2")):
            self.assertLess(abs(xi(s) - xi(1-s)), mp.mpf("1e-32"))
        self.assertLess(abs(xi(mp.mpf("1e-25")) - mp.mpf("0.5")), mp.mpf("1e-25"))

    def test_compact_inverse_moments_and_support(self):
        g = Compact("0.8", "1.3")
        self.assertEqual(g.g_log(g.L), 0)
        self.assertEqual(g.g_log(-g.L), 0)
        for s in (0, 1):
            self.assertLess(abs(g.direct_G(s)), mp.mpf("1e-28"))
        for x in (mp.exp(-1), mp.mpf("0.8"), mp.mpf(1), mp.exp(1)):
            self.assertLess(abs(g.inverse(x) - g.h(x)), mp.mpf("1e-28"))
        s = mp.mpc("0.4", "2.1")
        self.assertLess(abs(g.direct_G(s) - g.G(s)), mp.mpf("1e-28"))

    def test_gaussian_differential_identity(self):
        g = Gaussian("0.25", "3.2", "0.1")
        u = mp.mpf("0.3")
        direct = mp.diff(g.h_log, u, 2) + mp.diff(g.h_log, u)
        self.assertLess(abs(direct - g.g_log(u)), mp.mpf("1e-30"))
        self.assertEqual(g.G(0), 0)
        self.assertEqual(g.G(1), 0)

    def test_cross_correlation_and_reflected_mellin_product(self):
        result = dispatch({"operation": "correlation", "dps": 35,
                           "t_i": 3, "t_j": 14, "center_i": ".2", "center_j": "-.1",
                           "s": [".4", 8]})
        self.assertEqual(result["status"], "numerical evidence")
        for key in ("correlation_residual", "Mellin_identity_residual"):
            z = result["result"][key]
            self.assertLess(abs(mp.mpc(z["re"], z["im"])), mp.mpf("1e-28"))

    def test_real_place_removable_singularity(self):
        c = GaussianCorrelation(Gaussian(".25", 14, ".1"), Gaussian(".25", 3, "-.2"))
        self.assertEqual(c.real_place_integrand(0), c.c0 / 2)
        tiny = mp.mpf("1e-25")
        self.assertLess(abs(c.real_place_integrand(tiny) - c.c0 / 2), mp.mpf("1e-18"))
        u = mp.mpf("0.12")
        direct = (mp.exp(u/2)*(c.C(u)+c.C(-u))-2*c.c0)/(2*mp.sinh(u))
        self.assertLess(abs(c.real_place_integrand(u)-direct), mp.mpf("1e-28"))

    def test_prime_powers_are_once_each_and_include_endpoint(self):
        self.assertEqual(prime_powers(10), ((2, 2, 1), (3, 3, 1), (4, 2, 2), (5, 5, 1), (7, 7, 1), (8, 2, 3), (9, 3, 2)))
        self.assertIn((16, 2, 4), prime_powers(16))

    def test_complex_matrix_orientation_and_mixed_terms(self):
        basis = [Gaussian(".25", 0, ".1"), Gaussian(".25", 14, "-.1")]
        zeros = [mp.mpc(".5", 14), mp.mpc(".5", -14)]
        matrix = zero_matrix(basis, zeros)
        c = [mp.mpc(1, 2), mp.mpc("-.3", ".7")]
        combined = mp.fsum(abs(mp.fsum(cj*gj.G(rho) for cj, gj in zip(c, basis)))**2 for rho in zeros)
        self.assertLess(abs(quadratic(matrix, c)-combined), mp.mpf("1e-28"))
        self.assertGreater(abs(mp.im(matrix[0,1])), mp.mpf(".01"))
        self.assertLess(mp.norm(matrix-matrix.transpose_conj()), mp.mpf("1e-28"))
        diagonal = mp.fsum(abs(cj)**2*matrix[j,j] for j,cj in enumerate(c))
        self.assertGreater(abs(diagonal-combined), mp.mpf(".01"))

    def test_arithmetic_shifted_orientation_is_hermitian(self):
        a,b = Gaussian(".25", 0, ".1"), Gaussian(".25", 14, "-.1")
        ab = arithmetic_entry(GaussianCorrelation(a,b), 100)["arithmetic_value"]
        ba = arithmetic_entry(GaussianCorrelation(b,a), 100)["arithmetic_value"]
        self.assertLess(abs(ab-mp.conj(ba)), mp.mpf("1e-27"))

    def test_midpoint_prime_power_jump(self):
        result = dispatch({"operation":"prime_zero", "x":8, "zero_count":1, "dps":25})
        r=result["result"]
        expected=mp.log(2)*mp.mpf("2.5")+mp.log(3)+mp.log(5)+mp.log(7)
        self.assertLess(abs(mp.mpf(r["weighted_prime_power_psi0"])-expected),mp.mpf("1e-22"))
        self.assertEqual(r["prime_count_pi"],4)

    def test_synthetic_pair_is_labelled_and_cannot_certify_RH(self):
        result=dispatch({"operation":"checker", "claim":"synthetic_pair"})
        self.assertIn("synthetic",result["result"]["classification"])
        self.assertEqual(result["result"]["paired_value"]["re"],"-2.0")
        self.assertEqual(result["status"],"numerical evidence")
        self.assertEqual(dispatch({"operation":"checker", "claim":"negative_form", "value":"-1"})["status"],"inconclusive")

    def test_json_errors_and_endpoint(self):
        for payload in ({"operation":"zeta", "s":1}, {"operation":"zeta", "s":-2},
                        {"operation":"matrix", "dps":5}, {"operation":"no_such_op"}):
            json.dumps(dispatch(payload), allow_nan=False)
        self.assertEqual(dispatch({"operation":"matrix", "dps":5})["status"],"error")


if __name__ == "__main__":
    unittest.main(verbosity=2)
