示例#1
0
    def base_test(self, system, method, kind):
        hf = cache.hfdata[system]
        refdata = cache.reference_data[system]
        ref = refdata[method][kind]
        n_ref = len(ref["eigenvectors_singles"])

        refstate = adcc.ReferenceState(hf)
        groundstate = adcc.LazyMp(refstate)

        mtms = [
            compute_modified_transition_moments(
                groundstate, refstate.operators.electric_dipole[i], "adc2")
            for i in range(3)
        ]

        for i in range(n_ref):
            ref_s = ref["eigenvectors_singles"][i]
            ref_d = ref["eigenvectors_doubles"][i]
            mtm_np_s = [mtms[i]['s'].to_ndarray() for i in range(3)]
            mtm_np_d = [mtms[i]['d'].to_ndarray() for i in range(3)]
            # computing the scalar product of the eigenvector
            # and the modified transition moments yields
            # the transition dipole moment (doi.org/10.1063/1.1752875)
            res_tdm = -1.0 * np.array([
                np.sum(ref_s * mtm_s) + np.sum(ref_d * mtm_d)
                for mtm_s, mtm_d in zip(mtm_np_s, mtm_np_d)
            ])
            ref_tdm = ref["transition_dipole_moments"][i]

            # Test norm and actual values
            res_tdm_norm = np.sum(res_tdm * res_tdm)
            ref_tdm_norm = np.sum(ref_tdm * ref_tdm)
            assert res_tdm_norm == approx(ref_tdm_norm, abs=1e-8)
            np.testing.assert_allclose(res_tdm, ref_tdm, atol=1e-8)
示例#2
0
    def test_product_trace_nonsymmetric(self):
        ref = cache.refstate["cn_sto3g"]
        dipx_mo = ref.operators.electric_dipole[0]
        mp2diff_mo = adcc.LazyMp(ref).mp2_diffdm
        mp2diff_nosym = OneParticleOperator(ref.mospaces, is_symmetric=False)
        mp2diff_nosym.set_block("o1o1", mp2diff_mo["o1o1"])
        mp2diff_nosym.set_block("o1v1", mp2diff_mo["o1v1"])
        mp2diff_nosym.set_block("v1v1", mp2diff_mo["v1v1"])
        mp2diff_nosym.set_block("v1o1",
                                zeros_like(mp2diff_mo["o1v1"].transpose()))
        mp2diff_ao = mp2diff_nosym.to_ao_basis(ref)

        mp2a = mp2diff_ao[0].to_ndarray()
        mp2b = mp2diff_ao[1].to_ndarray()
        dipx_ao = ref.operators.provider_ao.electric_dipole[0]
        dipx_ref = np.sum(mp2a * dipx_ao) + np.sum(mp2b * dipx_ao)

        oo = np.sum(mp2diff_nosym["o1o1"].to_ndarray() *
                    dipx_mo["o1o1"].to_ndarray())
        ov = np.sum(mp2diff_nosym["o1v1"].to_ndarray() *
                    dipx_mo["o1v1"].to_ndarray())
        vo = np.sum(mp2diff_nosym["v1o1"].to_ndarray() *
                    dipx_mo["o1v1"].to_ndarray().T)
        vv = np.sum(mp2diff_nosym["v1v1"].to_ndarray() *
                    dipx_mo["v1v1"].to_ndarray())
        dipx_np = oo + ov + vo + vv

        assert dipx_np == approx(product_trace(mp2diff_nosym, dipx_mo))
        assert product_trace(mp2diff_nosym, dipx_mo) == approx(dipx_ref)
        assert product_trace(dipx_mo, mp2diff_nosym) == approx(dipx_ref)
示例#3
0
    def test_obtain_guesses_by_inspection(self):
        from adcc.workflow import obtain_guesses_by_inspection

        refstate = cache.refstate["h2o_sto3g"]
        ground_state = adcc.LazyMp(refstate)
        matrix2 = adcc.AdcMatrix("adc2", ground_state)
        matrix1 = adcc.AdcMatrix("adc1", ground_state)

        # Test that the right number of guesses is returned ...
        for mat in [matrix1, matrix2]:
            for i in range(4, 9):
                res = obtain_guesses_by_inspection(mat,
                                                   n_guesses=i,
                                                   kind="singlet")
                assert len(res) == i

        for i in range(4, 9):
            res = obtain_guesses_by_inspection(matrix2,
                                               n_guesses=i,
                                               kind="triplet",
                                               n_guesses_doubles=2)
            assert len(res) == i

        with pytest.raises(InputError):
            obtain_guesses_by_inspection(matrix1,
                                         n_guesses=4,
                                         kind="any",
                                         n_guesses_doubles=2)
        with pytest.raises(InputError):
            obtain_guesses_by_inspection(matrix1, n_guesses=40, kind="any")
示例#4
0
    def test_product_trace_both_nonsymmetric(self):
        ref = cache.refstate["cn_sto3g"]
        dipx_mo = ref.operators.electric_dipole[0]
        mp2diff_mo = adcc.LazyMp(ref).mp2_diffdm
        mp2diff_nosym = OneParticleOperator(ref.mospaces, is_symmetric=False)
        dipx_nosym = OneParticleOperator(ref.mospaces, is_symmetric=False)

        mp2diff_nosym.oo = mp2diff_mo.oo
        mp2diff_nosym.ov = mp2diff_mo.ov
        mp2diff_nosym.vv = mp2diff_mo.vv
        mp2diff_nosym.vo = zeros_like(mp2diff_mo.ov.transpose())
        mp2diff_ao = mp2diff_nosym.to_ao_basis(ref)

        dipx_nosym.oo = dipx_mo.oo
        dipx_nosym.ov = dipx_mo.ov
        dipx_nosym.vv = dipx_mo.vv
        dipx_nosym.vo = zeros_like(dipx_mo.ov.transpose())
        dipx_ao = dipx_nosym.to_ao_basis(ref)

        mp2a = mp2diff_ao[0].to_ndarray()
        mp2b = mp2diff_ao[1].to_ndarray()
        dipxa = dipx_ao[0].to_ndarray()
        dipxb = dipx_ao[1].to_ndarray()
        dipx_ref = np.sum(mp2a * dipxa) + np.sum(mp2b * dipxb)

        oo = np.sum(mp2diff_nosym.oo.to_ndarray() * dipx_nosym.oo.to_ndarray())
        ov = np.sum(mp2diff_nosym.ov.to_ndarray() * dipx_nosym.ov.to_ndarray())
        vo = np.sum(mp2diff_nosym.vo.to_ndarray() * dipx_nosym.vo.to_ndarray())
        vv = np.sum(mp2diff_nosym.vv.to_ndarray() * dipx_nosym.vv.to_ndarray())
        dipx_np = oo + ov + vo + vv

        assert dipx_np == approx(product_trace(mp2diff_nosym, dipx_nosym))
        assert product_trace(mp2diff_nosym, dipx_nosym) == approx(dipx_ref)
        assert product_trace(dipx_nosym, mp2diff_nosym) == approx(dipx_ref)
示例#5
0
class TestAdcMatrixInterface(unittest.TestCase):
    def test_properties_adc2(self):
        case = "h2o_sto3g"
        method = "adc2"

        reference_state = cache.refstate[case]
        ground_state = adcc.LazyMp(reference_state)
        matrix = adcc.AdcMatrix(method, ground_state)

        assert matrix.ndim == 2
        assert not matrix.is_core_valence_separated
        assert matrix.shape == (1640, 1640)
        assert len(matrix) == 1640

        assert matrix.axis_blocks == ["ph", "pphh"]
        assert sorted(matrix.axis_spaces.keys()) == matrix.axis_blocks
        assert sorted(matrix.axis_lengths.keys()) == matrix.axis_blocks
        assert matrix.axis_spaces["ph"] == ["o1", "v1"]
        assert matrix.axis_spaces["pphh"] == ["o1", "o1", "v1", "v1"]
        assert matrix.axis_lengths["ph"] == 40
        assert matrix.axis_lengths["pphh"] == 1600

        assert matrix.reference_state == reference_state
        assert matrix.mospaces == reference_state.mospaces
        assert isinstance(matrix.timer, adcc.timings.Timer)
示例#6
0
 def test_intermediates_adc2(self):
     ground_state = adcc.LazyMp(cache.refstate["h2o_sto3g"])
     matrix = adcc.AdcMatrix("adc2", ground_state)
     assert isinstance(matrix.intermediates, Intermediates)
     intermediates = Intermediates(ground_state)
     matrix.intermediates = intermediates
     assert matrix.intermediates == intermediates
示例#7
0
class TestAdcMatrixInterface(unittest.TestCase):
    def test_properties_adc2(self):
        case = "h2o_sto3g"
        method = "adc2"

        reference_state = cache.refstate[case]
        ground_state = adcc.LazyMp(reference_state)
        matrix = adcc.AdcMatrix(method, ground_state)

        assert matrix.ndim == 2
        assert not matrix.is_core_valence_separated
        assert matrix.shape == (1640, 1640)
        assert len(matrix) == 1640

        assert matrix.blocks == ["s", "d"]
        assert matrix.has_block("s")
        assert matrix.has_block("d")
        assert not matrix.has_block("t")
        assert matrix.block_spaces("s") == ["o1", "v1"]
        assert matrix.block_spaces("d") == ["o1", "o1", "v1", "v1"]

        assert matrix.reference_state == reference_state
        assert matrix.mospaces == reference_state.mospaces
        assert isinstance(matrix.timer, adcc.timings.Timer)
        assert isinstance(matrix.to_cpp(), libadcc.AdcMatrix)
示例#8
0
class TestAdcMatrixShifted(unittest.TestCase):
    def construct_matrices(self, case, shift):
        reference_state = cache.refstate[case]
        ground_state = adcc.LazyMp(reference_state)
        matrix = adcc.AdcMatrix("adc3", ground_state)
        shifted = AdcMatrixShifted(matrix, shift)
        return matrix, shifted
示例#9
0
    def test_to_ndarray(self):
        mp2diff = adcc.LazyMp(cache.refstate["h2o_sto3g"]).mp2_diffdm

        dm_oo = mp2diff["o1o1"].to_ndarray()
        dm_ov = mp2diff["o1v1"].to_ndarray()
        dm_vv = mp2diff["v1v1"].to_ndarray()

        dm_o = np.hstack((dm_oo, dm_ov))
        dm_v = np.hstack((dm_ov.transpose(), dm_vv))
        dm_full = np.vstack((dm_o, dm_v))

        np.testing.assert_almost_equal(dm_full,
                                       mp2diff.to_ndarray(),
                                       decimal=12)
示例#10
0
    def test_estimate_n_guesses(self):
        from adcc.workflow import estimate_n_guesses

        refstate = cache.refstate["h2o_sto3g"]
        ground_state = adcc.LazyMp(refstate)
        matrix = adcc.AdcMatrix("adc2", ground_state)

        # Check minimal number of guesses is 4 and at some point
        # we get more than four guesses
        assert 4 == estimate_n_guesses(matrix, n_states=1, singles_only=True)
        assert 4 == estimate_n_guesses(matrix, n_states=2, singles_only=True)
        for i in range(3, 20):
            assert i <= estimate_n_guesses(
                matrix, n_states=i, singles_only=True)
示例#11
0
 def test_functionality(self):
     ground_state = adcc.LazyMp(cache.refstate["h2o_sto3g"])
     matrix = adcc.AdcMatrix("adc2", ground_state)
     vectors = [adcc.guess_zero(matrix) for i in range(2)]
     for vec in vectors:
         vec.set_random()
     v, w = vectors
     with pytest.raises(AttributeError):
         v.pph
     with pytest.raises(AttributeError):
         v.pph = w.ph
     # setattr with expression
     z = adcc.zeros_like(v)
     z.ph = v.ph + w.ph
     z -= w
     np.testing.assert_allclose(v.ph.to_ndarray(), z.ph.to_ndarray())
示例#12
0
    def test_copy(self):
        ref = cache.refstate["h2o_sto3g"]
        mp2diff = adcc.LazyMp(ref).mp2_diffdm
        cpy = mp2diff.copy()

        assert cpy.blocks == mp2diff.blocks
        assert cpy.blocks_nonzero == mp2diff.blocks_nonzero
        assert cpy.reference_state == mp2diff.reference_state
        assert cpy.mospaces == mp2diff.mospaces

        for b in mp2diff.blocks:
            assert cpy.is_zero_block(b) == mp2diff.is_zero_block(b)
            if not mp2diff.is_zero_block(b):
                assert_equal(
                    cpy.block(b).to_ndarray(),
                    mp2diff.block(b).to_ndarray())
                assert cpy.block(b) is not mp2diff.block(b)
示例#13
0
    def template_singles_view(self, method):
        if "cvs" in method:
            reference_state = cache.refstate_cvs["h2o_sto3g"]
            shape = (8, 8)
            spaces_s = ["o2", "v1"]
        else:
            reference_state = cache.refstate["h2o_sto3g"]
            shape = (40, 40)
            spaces_s = ["o1", "v1"]
        matrix = adcc.AdcMatrix(method, adcc.LazyMp(reference_state))
        view = adcc.AdcBlockView(matrix, "s")

        assert view.ndim == 2
        assert view.is_core_valence_separated == ("cvs" in method)
        assert view.shape == shape
        assert len(view) == shape[0]

        assert view.blocks == ["s"]
        assert view.has_block("s")
        assert not view.has_block("d")
        assert not view.has_block("t")
        assert view.block_spaces("s") == spaces_s

        assert view.reference_state == reference_state
        assert view.mospaces == reference_state.mospaces
        assert isinstance(view.timer, adcc.timings.Timer)
        assert view.to_cpp() == matrix.to_cpp()

        # Check diagonal
        diff = matrix.diagonal("s") - view.diagonal("s")
        assert diff.dot(diff) < 1e-12

        # Check @ (one vector and multiple vectors)
        invec = adcc.guess_zero(matrix)
        invec["s"].set_random()
        # "d" left as zero
        invec_singles = adcc.AmplitudeVector(invec["s"])

        ref = matrix @ invec
        res = view @ invec_singles
        diff = res["s"] - ref["s"]
        assert diff.dot(diff) < 1e-12

        res = view @ [invec_singles, invec_singles, invec_singles]
        diff = [res[i]["s"] - ref["s"] for i in range(3)]
        assert max(d.dot(d) for d in diff) < 1e-12
示例#14
0
    def template_singles_view(self, method):
        if "cvs" in method:
            reference_state = cache.refstate_cvs["h2o_sto3g"]
            shape = (8, 8)
            spaces_ph = ["o2", "v1"]
        else:
            reference_state = cache.refstate["h2o_sto3g"]
            shape = (40, 40)
            spaces_ph = ["o1", "v1"]
        matrix = adcc.AdcMatrix(method, adcc.LazyMp(reference_state))
        view = matrix.block_view("ph_ph")

        assert view.ndim == 2
        assert view.is_core_valence_separated == ("cvs" in method)
        assert view.shape == shape
        assert len(view) == shape[0]

        assert view.axis_blocks == ["ph"]
        assert sorted(view.axis_spaces.keys()) == view.axis_blocks
        assert sorted(view.axis_lengths.keys()) == view.axis_blocks
        assert view.axis_spaces["ph"] == spaces_ph
        assert view.axis_lengths["ph"] == shape[0]

        assert view.reference_state == reference_state
        assert view.mospaces == reference_state.mospaces
        assert isinstance(view.timer, adcc.timings.Timer)

        # Check diagonal
        diff = matrix.diagonal().ph - view.diagonal().ph
        assert diff.dot(diff) < 1e-12

        # Check @ (one vector and multiple vectors)
        invec = adcc.guess_zero(matrix)
        invec.ph.set_random()
        # "d" left as zero
        invec_singles = adcc.AmplitudeVector(ph=invec.ph)

        ref = matrix @ invec
        res = view @ invec_singles
        diff = res.ph - ref.ph
        assert diff.dot(diff) < 1e-12

        res = view @ [invec_singles, invec_singles, invec_singles]
        diff = [res[i].ph - ref.ph for i in range(3)]
        assert max(d.dot(d) for d in diff) < 1e-12
示例#15
0
    def test_matvec_adc2(self):
        ground_state = adcc.LazyMp(cache.refstate["h2o_sto3g"])
        matrix = adcc.AdcMatrix("adc2", ground_state)

        vectors = [adcc.guess_zero(matrix) for i in range(3)]
        for vec in vectors:
            vec.set_random()
        v, w, x = vectors

        # Compute references:
        refv = matrix.matvec(v)
        refw = matrix.matvec(w)
        refx = matrix.matvec(x)

        # @ operator (1 vector)
        resv = matrix @ v
        diffv = refv - resv
        assert diffv.ph.dot(diffv.ph) < 1e-12
        assert diffv.pphh.dot(diffv.pphh) < 1e-12

        # @ operator (multiple vectors)
        resv, resw, resx = matrix @ [v, w, x]
        diffs = [refv - resv, refw - resw, refx - resx]
        for i in range(3):
            assert diffs[i].ph.dot(diffs[i].ph) < 1e-12
            assert diffs[i].pphh.dot(diffs[i].pphh) < 1e-12

        # compute matvec
        resv = matrix.matvec(v)
        diffv = refv - resv
        assert diffv.ph.dot(diffv.ph) < 1e-12
        assert diffv.pphh.dot(diffv.pphh) < 1e-12

        resv = matrix.rmatvec(v)
        diffv = refv - resv
        assert diffv.ph.dot(diffv.ph) < 1e-12
        assert diffv.pphh.dot(diffv.pphh) < 1e-12

        # Test apply
        resv.ph = matrix.block_apply("ph_ph", v.ph)
        resv.ph += matrix.block_apply("ph_pphh", v.pphh)
        refv = matrix.matvec(v)
        diffv = resv.ph - refv.ph
        assert diffv.dot(diffv) < 1e-12
示例#16
0
    def test_product_trace_symmetric(self):
        ref = cache.refstate["h2o_sto3g"]
        dipx_mo = ref.operators.electric_dipole[0]
        mp2diff_mo = adcc.LazyMp(ref).mp2_diffdm
        mp2diff_ao = mp2diff_mo.to_ao_basis(ref)

        mp2a = mp2diff_ao[0].to_ndarray()
        mp2b = mp2diff_ao[1].to_ndarray()
        dipx_ao = ref.operators.provider_ao.electric_dipole[0]
        dipx_ref = np.sum(mp2a * dipx_ao) + np.sum(mp2b * dipx_ao)

        oo = np.sum(mp2diff_mo.oo.to_ndarray() * dipx_mo.oo.to_ndarray())
        ov = 2.0 * np.sum(mp2diff_mo.ov.to_ndarray() * dipx_mo.ov.to_ndarray())
        vv = np.sum(mp2diff_mo.vv.to_ndarray() * dipx_mo.vv.to_ndarray())
        dipx_np = oo + ov + vv

        assert dipx_np == approx(product_trace(mp2diff_mo, dipx_mo))
        assert product_trace(mp2diff_mo, dipx_mo) == approx(dipx_ref)
        assert product_trace(dipx_mo, mp2diff_mo) == approx(dipx_ref)
示例#17
0
    def test_diagonalise_adcmatrix(self):
        from adcc.workflow import diagonalise_adcmatrix

        refdata = cache.reference_data["h2o_sto3g"]
        matrix = adcc.AdcMatrix("adc2",
                                adcc.LazyMp(cache.refstate["h2o_sto3g"]))

        res = diagonalise_adcmatrix(matrix,
                                    n_states=3,
                                    kind="singlet",
                                    eigensolver="davidson")
        ref_singlets = refdata["adc2"]["singlet"]["eigenvalues"]
        assert res.converged
        assert res.eigenvalues == approx(ref_singlets[:3])

        guesses = adcc.guesses_singlet(matrix, n_guesses=6, block="ph")
        res = diagonalise_adcmatrix(matrix,
                                    n_states=3,
                                    kind="singlet",
                                    guesses=guesses)
        ref_singlets = refdata["adc2"]["singlet"]["eigenvalues"]
        assert res.converged
        assert res.eigenvalues == approx(ref_singlets[:3])

        with pytest.raises(InputError):  # Too low tolerance
            res = diagonalise_adcmatrix(matrix,
                                        n_states=9,
                                        kind="singlet",
                                        eigensolver="davidson",
                                        conv_tol=1e-14)

        with pytest.raises(InputError):  # Wrong solver method
            res = diagonalise_adcmatrix(matrix,
                                        n_states=9,
                                        kind="singlet",
                                        eigensolver="blubber")

        with pytest.raises(InputError):  # Too few guesses
            res = diagonalise_adcmatrix(matrix,
                                        n_states=9,
                                        kind="singlet",
                                        eigensolver="davidson",
                                        guesses=guesses)
示例#18
0
    def test_matvec_adc2(self):
        ground_state = adcc.LazyMp(cache.refstate["h2o_sto3g"])
        matrix = adcc.AdcMatrix("adc2", ground_state)
        cppmatrix = libadcc.AdcMatrix("adc2", ground_state)

        vectors = [adcc.guess_zero(matrix) for i in range(3)]
        for vec in vectors:
            vec["s"].set_random()
            vec["d"].set_random()
        v, w, x = vectors

        # Compute references:
        refv = adcc.empty_like(v)
        refw = adcc.empty_like(w)
        refx = adcc.empty_like(x)
        cppmatrix.compute_matvec(v.to_cpp(), refv.to_cpp())
        cppmatrix.compute_matvec(w.to_cpp(), refw.to_cpp())
        cppmatrix.compute_matvec(x.to_cpp(), refx.to_cpp())

        # @ operator (1 vector)
        resv = matrix @ v
        diffv = refv - resv
        assert diffv["s"].dot(diffv["s"]) < 1e-12
        assert diffv["d"].dot(diffv["d"]) < 1e-12

        # @ operator (multiple vectors)
        resv, resw, resx = matrix @ [v, w, x]
        diffs = [refv - resv, refw - resw, refx - resx]
        for i in range(3):
            assert diffs[i]["s"].dot(diffs[i]["s"]) < 1e-12
            assert diffs[i]["d"].dot(diffs[i]["d"]) < 1e-12

        # compute matvec
        matrix.compute_matvec(v, resv)
        diffv = refv - resv
        assert diffv["s"].dot(diffv["s"]) < 1e-12
        assert diffv["d"].dot(diffv["d"]) < 1e-12

        matrix.compute_apply("ss", v["s"], resv["s"])
        cppmatrix.compute_apply("ss", v["s"], refv["s"])
        diffv = resv["s"] - refv["s"]
        assert diffv.dot(diffv) < 1e-12
#!/usr/bin/env python3
## vi: tabstop=4 shiftwidth=4 softtabstop=4 expandtab
import adcc

from import_data import import_data
from adcc.caching_policy import GatherStatisticsPolicy

# Gather precomputed data
data = import_data()

# Initialise the caching policy:
statistics_policy = GatherStatisticsPolicy()

mp = adcc.LazyMp(adcc.ReferenceState(data), statistics_policy)

# Run an adc2 calculation:
singlets = adcc.adc2x(mp, n_singlets=5, conv_tol=1e-8)
triplets = adcc.adc2x(mp, n_triplets=5, conv_tol=1e-8)
print(singlets.describe())
print(triplets.describe())

print("Tensor cache statistics:")
print(statistics_policy.call_count)
示例#20
0
 def test_diagonal_adc2(self):
     ground_state = adcc.LazyMp(cache.refstate["h2o_sto3g"])
     matrix = adcc.AdcMatrix("adc2", ground_state)
     cppmatrix = libadcc.AdcMatrix("adc2", ground_state)
     diff = cppmatrix.diagonal("s") - matrix.diagonal("s")
     assert diff.dot(diff) < 1e-12
示例#21
0
        assert sorted(matrix.axis_lengths.keys()) == matrix.axis_blocks
        assert matrix.axis_spaces["ph"] == ["o1", "v1"]
        assert matrix.axis_spaces["pphh"] == ["o1", "o1", "v1", "v1"]
        assert matrix.axis_lengths["ph"] == 40
        assert matrix.axis_lengths["pphh"] == 1600

        assert matrix.reference_state == reference_state
        assert matrix.mospaces == reference_state.mospaces
        assert isinstance(matrix.timer, adcc.timings.Timer)

    def test_properties_cvs_adc1(self):
        case = "h2o_sto3g"
        method = "cvs-adc1"

        reference_state = cache.refstate_cvs[case]
        ground_state = adcc.LazyMp(reference_state)
        matrix = adcc.AdcMatrix(method, ground_state)

        assert matrix.ndim == 2
        assert matrix.is_core_valence_separated
        assert matrix.shape == (8, 8)
        assert len(matrix) == 8

        assert matrix.axis_blocks == ["ph"]
        assert sorted(matrix.axis_spaces.keys()) == matrix.axis_blocks
        assert sorted(matrix.axis_lengths.keys()) == matrix.axis_blocks
        assert matrix.axis_spaces["ph"] == ["o2", "v1"]
        assert matrix.axis_lengths["ph"] == 8

        assert matrix.reference_state == reference_state
        assert matrix.mospaces == reference_state.mospaces
示例#22
0
    def test_construct_adcmatrix(self):
        from adcc.workflow import construct_adcmatrix

        #
        # Construction from hfdata
        #
        hfdata = cache.hfdata["h2o_sto3g"]

        res = construct_adcmatrix(hfdata, method="adc3")
        assert isinstance(res, adcc.AdcMatrix)
        assert res.method == adcc.AdcMethod("adc3")
        assert res.mospaces.core_orbitals == []
        assert res.mospaces.frozen_core == []
        assert res.mospaces.frozen_virtual == []

        res = construct_adcmatrix(hfdata, method="cvs-adc3", core_orbitals=1)
        assert isinstance(res, adcc.AdcMatrix)
        assert res.method == adcc.AdcMethod("cvs-adc3")
        assert res.mospaces.core_orbitals == [0, 7]
        assert res.mospaces.frozen_core == []
        assert res.mospaces.frozen_virtual == []

        res = construct_adcmatrix(hfdata, method="adc2", frozen_core=1)
        assert res.mospaces.core_orbitals == []
        assert res.mospaces.frozen_core == [0, 7]
        assert res.mospaces.frozen_virtual == []

        res = construct_adcmatrix(hfdata, method="adc2", frozen_virtual=1)
        assert res.mospaces.core_orbitals == []
        assert res.mospaces.frozen_core == []
        assert res.mospaces.frozen_virtual == [6, 13]

        res = construct_adcmatrix(hfdata,
                                  method="adc2",
                                  frozen_virtual=1,
                                  frozen_core=1)
        assert res.mospaces.core_orbitals == []
        assert res.mospaces.frozen_core == [0, 7]
        assert res.mospaces.frozen_virtual == [6, 13]

        invalid_cases = [
            dict(),  # Missing method
            dict(method="dadadad"),  # Unknown method
            dict(frozen_core=1),  # Missing method
            dict(frozen_virtual=3),  # Missing method
            dict(core_orbitals=4),  # Missing method
            dict(method="cvs-adc2"),  # No core_orbitals
            dict(method="cvs-adc2", frozen_core=1),
            dict(method="adc2", core_orbitals=3),  # Extra core parameter
            dict(method="adc2", core_orbitals=3, frozen_virtual=2),
        ]
        for case in invalid_cases:
            with pytest.raises(InputError):
                construct_adcmatrix(hfdata, **case)

        #
        # Construction from LazyMp or ReferenceState
        #
        refst_ful = cache.refstate["h2o_sto3g"]
        refst_cvs = cache.refstate_cvs["h2o_sto3g"]
        gs_ful, gs_cvs = adcc.LazyMp(refst_ful), adcc.LazyMp(refst_cvs)

        for obj in [gs_ful, refst_ful]:
            res = construct_adcmatrix(obj, method="adc2")
            assert isinstance(res, adcc.AdcMatrix)
            assert res.method == adcc.AdcMethod("adc2")

            with pytest.raises(InputError, match=r"Cannot run a core-valence"):
                construct_adcmatrix(obj, method="cvs-adc2x")
            with pytest.warns(UserWarning,
                              match=r"^Ignored frozen_core parameter"):
                construct_adcmatrix(obj, frozen_core=3, method="adc1")
            with pytest.warns(UserWarning,
                              match=r"^Ignored frozen_virtual parameter"):
                construct_adcmatrix(obj, frozen_virtual=1, method="adc3")

        for obj in [gs_cvs, refst_cvs]:
            res = construct_adcmatrix(obj, method="cvs-adc2x")
            assert isinstance(res, adcc.AdcMatrix)
            assert res.method == adcc.AdcMethod("cvs-adc2x")

            with pytest.raises(InputError):
                construct_adcmatrix(obj)  # Missing method
            with pytest.raises(InputError, match=r"Cannot run a general"):
                construct_adcmatrix(obj, method="adc2")
            with pytest.warns(UserWarning,
                              match=r"^Ignored core_orbitals parameter"):
                construct_adcmatrix(obj, core_orbitals=2, method="cvs-adc1")

        #
        # Construction from ADC matrix
        #
        mtx_ful = adcc.AdcMatrix("adc2", gs_ful)
        mtx_cvs = adcc.AdcMatrix("cvs-adc2", gs_cvs)
        assert construct_adcmatrix(mtx_ful) == mtx_ful
        assert construct_adcmatrix(mtx_ful, method="adc2") == mtx_ful
        assert construct_adcmatrix(mtx_cvs) == mtx_cvs
        assert construct_adcmatrix(mtx_cvs, method="cvs-adc2") == mtx_cvs

        with pytest.warns(UserWarning, match=r"Ignored method parameter"):
            construct_adcmatrix(mtx_ful, method="adc3")
        with pytest.warns(UserWarning,
                          match=r"^Ignored core_orbitals parameter"):
            construct_adcmatrix(mtx_cvs, core_orbitals=2)
        with pytest.warns(UserWarning,
                          match=r"^Ignored frozen_core parameter"):
            construct_adcmatrix(mtx_ful, frozen_core=3)
        with pytest.warns(UserWarning,
                          match=r"^Ignored frozen_virtual parameter"):
            construct_adcmatrix(mtx_cvs, frozen_virtual=1)
示例#23
0
    def test_extra_term(self):
        ground_state = adcc.LazyMp(cache.refstate["h2o_sto3g"])
        matrix_adc1 = adcc.AdcMatrix("adc1", ground_state)
        with pytest.raises(TypeError):
            matrix_adc1 += 42
        matrix = adcc.AdcMatrix("adc2", ground_state)

        with pytest.raises(TypeError):
            adcc.AdcMatrix("adc2", ground_state, diagonal_precomputed=42)
        with pytest.raises(ValueError):
            adcc.AdcMatrix("adc2",
                           ground_state,
                           diagonal_precomputed=matrix.diagonal() + 42)
        with pytest.raises(TypeError):
            AdcExtraTerm(matrix, "fail")
        with pytest.raises(TypeError):
            AdcExtraTerm(matrix, {"fail": "not_callable"})

        shift = -0.3
        shifted = AdcMatrixShifted(matrix, shift)
        # TODO: need to use AmplitudeVector to differentiate between
        # diagonals for ph and pphh
        # if we just pass numbers, i.e., shift
        # we get 2*shift on the diagonal
        ones = matrix.diagonal().ones_like()

        def __shift_ph(hf, mp, intermediates):
            def apply(invec):
                return adcc.AmplitudeVector(ph=shift * invec.ph)

            diag = adcc.AmplitudeVector(ph=shift * ones.ph)
            return AdcBlock(apply, diag)

        def __shift_pphh(hf, mp, intermediates):
            def apply(invec):
                return adcc.AmplitudeVector(pphh=shift * invec.pphh)

            diag = adcc.AmplitudeVector(pphh=shift * ones.pphh)
            return AdcBlock(apply, diag)

        extra = AdcExtraTerm(matrix, {
            'ph_ph': __shift_ph,
            'pphh_pphh': __shift_pphh
        })
        # cannot add to 'pphh_pphh' in ADC(1) matrix
        with pytest.raises(ValueError):
            matrix_adc1 += extra

        shifted_2 = matrix + extra
        shifted_3 = extra + matrix
        for manual in [shifted_2, shifted_3]:
            assert_allclose(shifted.diagonal().ph.to_ndarray(),
                            manual.diagonal().ph.to_ndarray(),
                            atol=1e-12)
            assert_allclose(shifted.diagonal().pphh.to_ndarray(),
                            manual.diagonal().pphh.to_ndarray(),
                            atol=1e-12)
            vec = adcc.guess_zero(matrix)
            vec.set_random()
            ref = shifted @ vec
            ret = manual @ vec
            diff_s = ref.ph - ret.ph
            diff_d = ref.pphh - ret.pphh
            assert np.max(np.abs(diff_s.to_ndarray())) < 1e-12
            assert np.max(np.abs(diff_d.to_ndarray())) < 1e-12
示例#24
0
 def test_reference_cn_adc3(self):
     ground_state = adcc.LazyMp(cache.refstate["cn_sto3g"])
     matrix = adcc.AdcMatrix("adc3", ground_state)
     self.base_reference(matrix, self.get_ref_cn())
示例#25
0
 def test_reference_h2o_adc2x(self):
     ground_state = adcc.LazyMp(cache.refstate["h2o_sto3g"])
     matrix = adcc.AdcMatrix("adc2x", ground_state)
     self.base_reference(matrix, self.get_ref_h2o())