Source code for pytc.solver.test.test_bug_t

"""BUG-(T) must reproduce canonical (T) exactly when no rank is discarded.

At full rank the pair basis is complete, so the factorised route is an identity
rearrangement of pyscf's own expression -- any disagreement is an algebra bug,
not an approximation.
"""
import itertools
import unittest

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

import jax

from pytc.solver.bug_core import LowRankResult
from pytc.solver.bug_t import (low_rank_t, core_W, core_W_blocked, core_V, sylvester_divide, energy,
                               energy_prepared, energy_cycle, energy_trans, prepare_energy)

jax.config.update("jax_enable_x64", True)
from pytc.solver.bug_core import extract_df_factors

H2O = 'O 0 0 0.1173; H 0 0.7572 -0.4692; H 0 -0.7572 -0.4692'

R3_TERMS = [(4.0, (0, 1, 2)), (1.0, (2, 0, 1)), (1.0, (1, 2, 0)),
            (-2.0, (2, 1, 0)), (-2.0, (0, 2, 1)), (-2.0, (1, 0, 2))]


[docs] def _cycle_term(C_sym, C_hat, U, sig): A = np.tensordot(U, C_sym, axes=([2], [0])) P = np.tensordot(U, U, axes=([1], [1])) if sig[2] == 0: T1 = np.tensordot(P, A, axes=([0, 3], [0, 3])) T2 = np.tensordot(T1, P, axes=([1, 3], [0, 3])) T3 = np.tensordot(T2, C_hat, axes=([0, 2], [2, 1])) return float(np.tensordot(T3, U, axes=([0, 1, 2], [1, 0, 2]))) T1 = np.tensordot(P, A, axes=([0, 3], [0, 2])) T2 = np.tensordot(T1, P, axes=([1, 3], [0, 3])) T3 = np.tensordot(T2, C_hat, axes=([0, 2], [1, 2])) return float(np.tensordot(T3, U, axes=([0, 1, 2], [1, 0, 2])))
[docs] def _transp_term(C_sym, C_hat, U, sig): aligned = [m for m in range(3) if sig[m] == m][0] order = [aligned] + [m for m in range(3) if m != aligned] Cs = C_sym.transpose(order) Ch = C_hat.transpose(order) P1 = np.tensordot(Cs, U, axes=([1], [2])) P2 = np.tensordot(Ch, U, axes=([1], [2])) M = np.tensordot(P1, P2, axes=([0, 3], [0, 3])) R = np.tensordot(U, U, axes=([1], [1])).transpose(1, 0, 3, 2) return float(np.tensordot(M, R, axes=([0, 1, 2, 3], [0, 3, 2, 1])))
[docs] def _energy_reference(C_W, C_hat, U): C_sym = sum(C_W.transpose(p) for p in itertools.permutations((0, 1, 2))) et = 0.0 for coef, sig in R3_TERMS: nfixed = sum(sig[m] == m for m in range(3)) if nfixed == 3: term = float(np.dot(C_sym.reshape(-1), C_hat.reshape(-1))) elif nfixed == 1: term = _transp_term(C_sym, C_hat, U, sig) else: term = _cycle_term(C_sym, C_hat, U, sig) et += coef * term return 2 * et
[docs] def _factorise(t2): """t2's pair matrix is SYMMETRIC, so the factorisation is an eigen- decomposition with SIGNED eigenvalues. An SVD returns V = -U on the negative branch and t2 = U S U^T would be wrong there.""" nocc, _, nvir, _ = t2.shape n = nocc * nvir T = t2.transpose(0, 2, 1, 3).reshape(n, n) T = 0.5 * (T + T.T) lam, U = np.linalg.eigh(T) order = np.argsort(-np.abs(lam)) return lam[order], np.ascontiguousarray(U[:, order])
[docs] class TestBugT(unittest.TestCase):
[docs] def test_gemm_cores_match_frozen_contractions(self): rng = np.random.default_rng(81) nocc, nvir, rank, naux = 3, 5, 4, 7 U = np.linalg.qr(rng.standard_normal((nocc * nvir, rank)))[0] U = U.reshape(nocc, nvir, rank) S = rng.standard_normal(rank) B_oo = rng.standard_normal((nocc, nocc, naux)) B_ov = rng.standard_normal((nocc, nvir, naux)) B_vv = rng.standard_normal((nvir, nvir, naux)) b = np.einsum('iax,iaQ->Qx', U, B_ov) g = np.einsum('abQ,jay,jbz->Qyz', B_vv, U, U, optimize=True) h = np.einsum('ijQ,jby,ibz->Qyz', B_oo, U, U, optimize=True) CW_ref = np.einsum('Qx,Qyz->xzy', b, g - h, optimize=True) CW_ref *= S[None, None, :] np.testing.assert_allclose( core_W(U, S, B_oo, B_ov, B_vv), CW_ref, rtol=1e-13, atol=1e-13) np.testing.assert_allclose( core_W_blocked(U, S, B_oo, B_ov, B_vv, block_q=3), CW_ref, rtol=1e-13, atol=1e-13) t1 = rng.standard_normal((nocc, nvir)) fvo = rng.standard_normal((nvir, nocc)) tau = np.einsum('iax,ia->x', U, t1) phi = np.einsum('iax,ai->x', U, fvo) CV_ref = (b.T @ b)[:, :, None] * tau[None, None, :] idx = np.arange(rank) CV_ref[idx, idx, :] += S[:, None] * phi[None, :] np.testing.assert_allclose( core_V(U, S, t1, fvo, B_ov), CV_ref, rtol=1e-13, atol=1e-13) C = rng.standard_normal((rank, rank, rank)) mo_e = np.r_[np.linspace(-2.0, -1.0, nocc), np.linspace(0.2, 1.0, nvir)] got, Vr = sylvester_divide(C, U, mo_e, nocc, block_r=2) d = (mo_e[:nocc, None] - mo_e[None, nocc:]).reshape(-1) P = U.reshape(nocc * nvir, rank) A = (P * d[:, None]).T @ P lam, Vr_ref = np.linalg.eigh((A + A.T) / 2) def rotate(X, M): for _ in range(3): X = np.tensordot(X, M, axes=([0], [0])) return X C_ref = rotate(C, Vr_ref) C_ref /= (lam[:, None, None] + lam[None, :, None] + lam[None, None, :]) C_ref = rotate(C_ref, Vr_ref.T) Vr = np.asarray(Vr) # eigenvector signs are free np.testing.assert_allclose(Vr.T @ A @ Vr, np.diag(lam), atol=1e-12) np.testing.assert_allclose(got, C_ref, rtol=1e-13, atol=1e-13)
[docs] def test_matches_canonical_at_full_rank(self): for basis in ('sto-3g', '3-21g'): with self.subTest(basis=basis): mol = gto.M(atom=H2O, basis=basis, verbose=0) mf = scf.RHF(mol).density_fit().run() mycc = cc.CCSD(mf).run() eris = mycc.ao2mo() t1, t2 = mycc.t1, mycc.t2 nocc, nvir = t1.shape et_ref = mycc.ccsd_t() lam, Uf = _factorise(t2) U = Uf.reshape(nocc, nvir, nocc * nvir) B_oo, B_ov, B_vv = extract_df_factors(mf, nocc) CW = core_W(U, lam, B_oo, B_ov, B_vv) np.testing.assert_allclose( core_W_blocked(U, lam, B_oo, B_ov, B_vv, 2), CW, rtol=1e-12, atol=1e-12) CV = core_V(U, lam, t1, eris.fock[nocc:, :nocc], B_ov) Chat, _ = sylvester_divide( CW + 0.5 * CV, U, eris.mo_energy, nocc) self.assertLess(abs(energy(CW, Chat, U, block_v=2) - et_ref), 1e-10) res = LowRankResult(energy=None, U=Uf, S=lam, iterations=0, converged=True, stop_reason='amplitude-step', t1=t1) self.assertLess(abs(low_rank_t(mf, res, block_q=2, block_v=2) - et_ref), 1e-10)
[docs] def test_fused_energy_matches_six_term_reference(self): rng = np.random.default_rng(7) # Neither occupied nor virtual extent divides its block size; the # padding paths must be as exact as the unblocked contraction. o, v, r = 3, 5, 5 U = np.linalg.qr(rng.standard_normal((o * v, r)))[0].reshape(o, v, r) CW = rng.standard_normal((r, r, r)) Chat = rng.standard_normal((r, r, r)) ref = _energy_reference(CW, Chat, U) static = ('block_v', 'block_o') got = jax.jit(energy, static_argnames=static)(CW, Chat, U, block_v=2, block_o=2) prepared = prepare_energy(CW, Chat) got_prepared = jax.jit(energy_prepared, static_argnames=static)( *prepared, U, block_v=2, block_o=2) et, Csym, Ch_cycle, Ch_trans = prepared got_split = 2.0 * ( jax.jit(energy_cycle, static_argnames=static)(et, Csym, Ch_cycle, U, block_v=2, block_o=2) - 2.0 * jax.jit(energy_trans, static_argnames=static)(Csym, Ch_trans, U, block_v=2, block_o=2)) for val in (got, got_prepared, got_split): np.testing.assert_allclose(float(val), ref, rtol=1e-12, atol=1e-12)
[docs] def test_front_door_requires_float64(self): from unittest import mock from pytc.solver import bug_t from pytc.solver.bug_core import Float64NotEnabled with mock.patch.object(bug_t, "require_float64", side_effect=Float64NotEnabled("x64")): with self.assertRaises(Float64NotEnabled): low_rank_t(None, None)
[docs] def test_factorisation_needs_signed_eigenvalues(self): """The real t2 is indefinite, so unsigned factorisation is wrong.""" mol = gto.M(atom=H2O, basis='3-21g', verbose=0) mf = scf.RHF(mol).density_fit().run() mycc = cc.CCSD(mf).run() lam, _ = _factorise(mycc.t2) self.assertTrue((lam < 0).any() and (lam > 0).any())
if __name__ == '__main__': unittest.main()