Source code for pytc.solver.test.test_bug_mp2

"""Tests for low-rank DF BUG-MP2.

Dense references are built from the same DF factor, so the kernel tests check
the contraction algebra alone; PySCF DF-MP2 checks the front door end to end."""

import unittest

import numpy as np
from pyscf import gto, mp, scf

from pytc.solver.bug_mp2 import (bug_mp2_amplitudes, bug_mp2_energy, df_kernel, kernel,
                                 low_rank_mp2)


[docs] def _dense(B_ov): return np.einsum('iaQ,jbQ->iajb', B_ov, B_ov)
[docs] def _amp(res): """``(U, S)`` of a :class:`~pytc.solver.bug_core.LowRankResult`.""" return res.U, res.S
[docs] class TestBugMP2(unittest.TestCase):
[docs] def test_df_kernels_match_dense_integrals(self): rng = np.random.default_rng(5) B_ov = rng.standard_normal((4, 6, 9)) V = rng.standard_normal((4, 6, 3)) eri = _dense(B_ov) direct = np.einsum('iajb,jbk->iak', eri, V) exchange = np.einsum('ibja,jbk->iak', eri, V) np.testing.assert_allclose(df_kernel(B_ov, direct_only=True)(V), direct, atol=1e-11) np.testing.assert_allclose(df_kernel(B_ov)(V), 2 * direct - exchange, atol=1e-11) self.assertGreater(np.abs(direct - exchange).max(), 1.0) # the two differ
[docs] def test_kernels_act_columnwise_and_stay_on_device(self): import jax rng = np.random.default_rng(0) B_ov = rng.standard_normal((4, 6, 5)) V = rng.standard_normal((4, 6, 3)) mv = df_kernel(B_ov) full = mv(V) self.assertIsInstance(full, jax.Array) for z in range(3): np.testing.assert_allclose(full[:, :, z:z + 1], mv(V[:, :, z:z + 1]), atol=1e-11)
[docs] def test_kernel_uses_direct_amplitudes_and_pair_energy(self): """The amplitude numerator is J; the energy contracts with 2J - K. Wiring one kernel to both is wrong by ~0.15 Ha on water, so pin the pairing.""" rng = np.random.default_rng(9) o, v = 4, 6 B_ov = rng.standard_normal((o, v, 7)) * 0.3 eia = -(np.linspace(0.9, 2.4, o * v).reshape(o, v)) eri = _dense(B_ov) denom = eia[:, :, None, None] + eia[None, None] exact = float(np.sum(eri / denom * (2 * eri - eri.transpose(0, 3, 2, 1)))) e = kernel(B_ov, eia, tau=1e-10, maxiter=40).energy self.assertLess(abs(e - exact), 1e-9) U, S = _amp(bug_mp2_amplitudes(df_kernel(B_ov), eia, maxiter=40)) self.assertGreater(abs(bug_mp2_energy(U, S, df_kernel(B_ov)) - exact), 1e-3)
[docs] def test_front_door_matches_pyscf_df_mp2(self): mf = scf.RHF(gto.M(atom='O 0 0 0; H 0 0.757 0.587; H 0 -0.757 0.587', basis='6-31g', verbose=0)).density_fit().run(conv_tol=1e-10) for frozen in (0, 1): with self.subTest(frozen=frozen): ref = mp.MP2(mf, frozen=frozen or None).run().e_corr got = low_rank_mp2(mf, tau=1e-10, frozen=frozen).energy self.assertLess(abs(got - ref), 1e-9)
[docs] def test_zero_plateau_tolerance_disables_the_energy_stop(self): """An explicit 0.0 is a request, not a missing value: it must not fall back to the default plateau tolerance.""" rng = np.random.default_rng(3) B_ov = rng.standard_normal((3, 5, 12)) * 0.1 eia = -1.0 - rng.random((3, 5)) out = bug_mp2_amplitudes(df_kernel(B_ov), eia, tau=1e-6, conv=1e-30, maxiter=12, energy_plateau_tolerance=0.0) self.assertEqual(out.stop_reason, 'maxiter')
[docs] def test_require_float64_inspects_the_runtime(self): """The gate must read the live x64 setting, not merely exist. Parity here is quoted at ~1e-8 Ha and float32 agrees to ~1e-7 on everything, so a wrong dtype reads as success rather than as an error.""" import jax.numpy as jnp from pytc.solver.bug_core import Float64NotEnabled, require_float64 if jnp.zeros(1, dtype=jnp.float64).dtype == jnp.float64: self.assertTrue(require_float64() is True) else: with self.assertRaises(Float64NotEnabled): require_float64()
[docs] def test_amplitude_step_sees_a_rotation_the_eigenvalues_do_not(self): """A stop that compares kept eigenvalues only lets a basis still rotating at fixed S look converged. The Gram step must report the change of T = U diag(S) U^T itself.""" from pytc.solver.bug_core import amplitude_step rng = np.random.default_rng(0) U = np.linalg.qr(rng.standard_normal((16, 3)))[0] S = np.array([0.3, -0.1, 0.02]) c, s_ = np.cos(0.2), np.sin(0.2) R = np.eye(16) R[[0, 0, 5, 5], [0, 5, 0, 5]] = c, -s_, s_, c U2 = R @ U T, T2 = (U * S) @ U.T, (U2 * S) @ U2.T got, valid = amplitude_step(S, S, U2.T @ U, U2, U, conv=1e-10) self.assertTrue(valid) self.assertAlmostEqual(got, np.linalg.norm(T2 - T), places=13) self.assertGreater(got, 1e-2)
[docs] def test_amplitude_step_resolves_steps_below_the_gram_roundoff(self): """The Gram difference cancels to ~sqrt(eps)|T|, so a 1e-9 step can read as zero. Near a stop threshold the step must come from the cancellation-free form, for unequal ranks too.""" from pytc.solver.bug_core import amplitude_step rng = np.random.default_rng(1) n = 40 U = np.linalg.qr(rng.standard_normal((n, 5)))[0] S = np.array([0.4, -0.2, 0.05, 0.01, -1e-3]) for theta, ds, keep in ((1e-9, 0.0, 5), (0.0, 3e-10, 5), (2e-10, 1e-10, 4)): with self.subTest(theta=theta, ds=ds, keep=keep): G = np.zeros((n, n)) G[0, 7], G[7, 0] = theta, -theta w, V = np.linalg.eig(G) R = np.real(V @ np.diag(np.exp(w)) @ np.linalg.inv(V)) U2 = (R @ U)[:, :keep] S2 = S[:keep] + ds T, T2 = (U * S) @ U.T, (U2 * S2) @ U2.T ref = np.linalg.norm(T2 - T) got, valid = amplitude_step(S2, S, U2.T @ U, U2, U, conv=1e-10, block_rows=16) self.assertTrue(valid) self.assertAlmostEqual(got, ref, delta=1e-6 * ref + 1e-16)
[docs] def test_amplitude_is_pinned_by_U_S_UT_not_by_U(self): """``U`` is only defined up to column sign, and eigenvector signs are not stable across BLAS/XLA backends. The JAX kernels reproduce the earlier numpy result in ``S`` and in ``U S U^T`` to ~1e-14 while individual columns flip sign, so any regression check must compare the physical object. Comparing ``U`` elementwise reports a difference of 1.0 and means nothing. """ from pytc.solver.bug_mp2 import bug_mp2_amplitudes, df_kernel rng = np.random.default_rng(7) o, v, naux = 5, 9, 13 B_ov = rng.standard_normal((o, v, naux)) * 0.3 eia = -(rng.random((o, v)) + 0.8) U1, S1 = _amp(bug_mp2_amplitudes(df_kernel(B_ov), eia, seed=3)) U2, S2 = _amp(bug_mp2_amplitudes(df_kernel(B_ov), eia, seed=3)) A = U1.reshape(o * v, -1) C = U2.reshape(o * v, -1) self.assertTrue(np.abs(S1 - S2).max() < 1e-12) T1 = A @ np.diag(S1) @ A.T T2 = C @ np.diag(S2) @ C.T self.assertTrue(np.abs(T1 - T2).max() < 1e-10) # and a column sign flip must leave the amplitude untouched flip = np.ones(A.shape[1]); flip[::2] = -1.0 Af = A * flip self.assertTrue(np.abs(Af @ np.diag(S1) @ Af.T - T1).max() < 1e-12)
if __name__ == '__main__': unittest.main()