"""Numerical contracts for the shared BUG primitives."""
import unittest
import numpy as np
from pytc.solver.bug_core import truncate_sym
[docs]
class TestTruncationRules(unittest.TestCase):
"""Each rule keeps exactly the modes its threshold bounds."""
[docs]
def setUp(self):
rng = np.random.default_rng(5)
self.Q = np.linalg.qr(rng.normal(size=(6, 6)))[0]
self.lam = np.array([0.4, -0.2, 0.05, 1e-3, -2e-4, 1e-5])
self.M = (self.Q * self.lam) @ self.Q.T
G = rng.normal(size=(6, 6))
self.G = G @ G.T
self.e = self.lam * np.einsum('ji,jk,ki->i', self.Q, self.G, self.Q)
[docs]
def kept(self, tau, rule):
W, s, info = truncate_sym(self.M, tau, rule=rule, energy_metric=self.G)
return np.sort(np.abs(s)), info
[docs]
def test_relative_and_absolute_cuts(self):
rel, _ = self.kept(1e-2, 'relative') # keeps |s| > 4e-3
ab, _ = self.kept(1e-2, 'absolute') # keeps |s| > 1e-2
np.testing.assert_allclose(rel, [0.05, 0.2, 0.4])
np.testing.assert_allclose(ab, [0.05, 0.2, 0.4])
ab, _ = self.kept(1e-4, 'absolute')
np.testing.assert_allclose(ab, [2e-4, 1e-3, 0.05, 0.2, 0.4])
# Scaling the core moves a relative cut with it, an absolute one not.
W, s, _ = truncate_sym(0.1 * self.M, 1e-2, rule='absolute')
self.assertEqual(len(s), 2)
[docs]
def test_energy_cut_and_discarded_energy(self):
eta = np.sort(np.abs(self.e))[2] * 1.0001
s, info = self.kept(eta, 'energy')
keep = np.abs(self.e) > eta
np.testing.assert_allclose(s, np.sort(np.abs(self.lam[keep])))
self.assertAlmostEqual(info.discarded_energy, self.e[~keep].sum(), delta=1e-15)
# Every rule reports the energy it drops.
_, info = self.kept(1e-2, 'relative')
self.assertAlmostEqual(info.discarded_energy, self.e[np.abs(self.lam) <= 4e-3].sum(),
delta=1e-15)
if __name__ == '__main__':
unittest.main()
[docs]
class TestDirectionSelection(unittest.TestCase):
[docs]
def test_saturated_basis_adds_no_directions(self):
"""Once U spans the pair space the projected residual is roundoff. Every
selector must then add nothing; unit-norm SVD vectors of that noise must
not pass the drop rule."""
import jax
jax.config.update("jax_enable_x64", True)
from pytc.solver.bug_core import orth_directions, project_directions
rng = np.random.default_rng(0)
U = np.linalg.qr(rng.standard_normal((30, 30)))[0]
D = rng.standard_normal((30, 30))
for how in ("residual", "top", "svd"):
with self.subTest(how=how):
Q = orth_directions(project_directions(U, D, kabs=8, how=how))
self.assertEqual(Q.shape[1], 0)
# and a genuine external residual is still selected
Q = orth_directions(project_directions(U[:, :20], D, kabs=8, how="svd"))
self.assertEqual(Q.shape[1], 8)