Ejemplo n.º 1
0
def test_cc():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]

    mol.basis = {
        'H': '3-21g',
        'O': '3-21g',
    }
    mol.build()
    rhf = scf.RHF(mol)
    rhf = scf.density_fit(scf.RHF(mol))
    rhf.scf()  # -76.0267656731
    from tcc.rccsd_mul import RCCSD_MUL_RI
    from tcc.rccsd_cpd import RCCSD_CPD_LS_T
    from tcc.cc_solvers import (residual_diis_solver, classic_solver,
                                root_solver)

    cc1 = RCCSD_CPD_LS_T(rhf, rankt={'t2': 20})
    cc2 = RCCSD_MUL_RI(rhf)

    converged1, energy1, amps1 = classic_solver(cc1, max_cycle=150)

    converged2, energy2, amps2 = classic_solver(cc2, max_cycle=150)
Ejemplo n.º 2
0
def test_cpd_equals_ncpd():
    from tcc.hubbard import hubbard_from_scf
    from pyscf import scf
    N = 6
    U = 4
    USE_PBC = 'y'
    rhf = hubbard_from_scf(scf.RHF, N, N, U, USE_PBC)
    rhf.scf()  # -76.0267656731

    from tcc.rccsd_cpd import (RCCSD_nCPD_LS_T_HUB, RCCSD_CPD_LS_T_HUB)

    cc1 = RCCSD_CPD_LS_T_HUB(rhf, rankt={'t2': 30})
    cc2 = RCCSD_nCPD_LS_T_HUB(rhf, rankt={'t2': 30})

    from tcc.cc_solvers import (residual_diis_solver, update_diis_solver,
                                classic_solver)
    cc1._converged = False
    converged1, energy1, amps1 = classic_solver(cc1,
                                                conv_tol_energy=1e-8,
                                                conv_tol_res=1e-8,
                                                lam=3,
                                                max_cycle=140)

    cc2._converged = False
    converged2, energy2, amps2 = classic_solver(cc2,
                                                conv_tol_energy=1e-8,
                                                conv_tol_res=1e-8,
                                                lam=3,
                                                max_cycle=140)

    print(energy2 - energy1)
Ejemplo n.º 3
0
def test_cc():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]

    mol.basis = {
        'H': 'sto-3g',
        'O': 'sto-3g',
    }
    mol.build()
    uhf = scf.UHF(mol)
    uhf.scf()  # -76.0267656731
    rhf = scf.RHF(mol)
    rhf.scf()  # -76.0267656731

    from tcc.uccsd_dir import UCCSD
    from tcc.rccsd import RCCSD
    cc1 = UCCSD(uhf)
    cc2 = RCCSD(rhf)

    from tcc.cc_solvers import classic_solver

    converged1, energy1, amps1 = classic_solver(cc1,
                                                conv_tol_energy=1e-8,
                                                max_cycle=100)

    converged2, energy2, amps2 = classic_solver(cc2,
                                                conv_tol_energy=1e-8,
                                                max_cycle=100)
Ejemplo n.º 4
0
    def test_classic_solver(self):
        from tcc.cc_solvers import classic_solver
        from tcc.rccsd import RCCSD

        cc = RCCSD(self.rhf)
        converged, energy, amps = classic_solver(cc)
        self.assertEqual(converged, True)
        self.assertEqual(np.allclose(energy, -0.2133432609672395, 1e-5), True)

        converged, energy, _ = classic_solver(cc,
                                              amps,
                                              lam=3,
                                              conv_tol_energy=1e-10)
        self.assertEqual(converged, True)
        self.assertEqual(np.allclose(energy, -0.2133432609672395, 1e-5), True)
Ejemplo n.º 5
0
def test_cc_step():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]

    mol.basis = {
        'H': 'sto-3g',
        'O': 'sto-3g',
    }
    mol.build()
    rhf = scf.RHF(mol)
    rhf.scf()  # -76.0267656731

    from tcc.cc_solvers import step_solver, classic_solver
    from tcc.rccsd import RCCSD
    cc = RCCSD(rhf)

    converged1, energy1, _ = classic_solver(cc,
                                            conv_tol_energy=1e-10,
                                            conv_tol_res=1e-10,
                                            max_cycle=20)
    cc._converged = False

    converged2, energy2, _ = step_solver(cc,
                                         conv_tol_energy=1e-10,
                                         beta=0.5,
                                         max_cycle=100)
Ejemplo n.º 6
0
def test_cc_unit():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]
    mol.basis = {
        'H': '3-21g',
        'O': '3-21g',
    }
    mol.build()
    rhf = scf.RHF(mol)
    rhf = scf.density_fit(scf.RHF(mol))
    rhf.scf()

    from tcc.rccsdt_ri import RCCSDT_UNIT_RI
    from tcc.cc_solvers import (classic_solver, update_diis_solver)
    cc = RCCSDT_UNIT_RI(rhf)

    converged, energy, amps = classic_solver(cc,
                                             conv_tol_energy=1e-8,
                                             max_cycle=100)
    cc._converged = False
    converged, energy, amps = update_diis_solver(cc,
                                                 conv_tol_energy=1e-8,
                                                 max_cycle=100)

    print('dE: {}'.format(energy - -1.304738e-01))
Ejemplo n.º 7
0
    def test_rccsd_mul_ri(self):
        from pyscf import gto
        from pyscf import scf
        mol = gto.Mole()
        mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                    [1, (0., 0.757, 0.587)]]

        mol.basis = {
            'H': 'sto-3g',
            'O': 'sto-3g',
        }
        mol.build(parse_arg=False)
        rhfri = scf.density_fit(scf.RHF(mol))
        rhfri.scf()  # -74.961181409648674

        from tcc.cc_solvers import classic_solver
        from tcc.rccsd_mul import RCCSD_MUL_RI
        cc = RCCSD_MUL_RI(rhfri)

        converged, energy, _ = classic_solver(cc,
                                              conv_tol_amps=1e-8,
                                              conv_tol_energy=1e-8)

        self.assertEqual(np.allclose(energy, -0.049399404240317468, 1e-6),
                         True)
Ejemplo n.º 8
0
def test_cc_t2f():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [
        [8, (0., 0., 0.)],
        [1, (0.,  -0.757, 0.587)],
        [1, (0., 0.757, 0.587)]]
    mol.basis = {'H': '3-21g',
                 'O': '3-21g', }
    mol.build()
    rhf = scf.RHF(mol)
    rhf.scf()
    rhfri = scf.density_fit(scf.RHF(mol))
    rhfri.scf()

    from tcc.rccsdt import RCCSDT, RCCSDT_UNIT
    from tcc.rccsdt_cpd import (RCCSDT_UNIT_nCPD_LS_T,
                                RCCSDT_UNIT_nCPD_T_LS_T)
    from tcc.cc_solvers import (classic_solver, step_solver)

    cc1 = RCCSDT_UNIT(rhf)
    cc2 = RCCSDT_UNIT_nCPD_T_LS_T(rhfri, rankt={'t3': 40})

    converged1, energy1, amps1 = classic_solver(
        cc1, conv_tol_energy=1e-7, lam=3,
        max_cycle=100)

    converged2, energy2, amps2 = step_solver(
        cc2, conv_tol_energy=1e-7, beta=1 - 1 / 5,
        max_cycle=100)

    print('E(full) - E(T2 CPD): {}'.format(energy2 - energy1))
Ejemplo n.º 9
0
def test_cc():  # pragma: nocover
    from pyscf import scf
    from tcc.hubbard import hubbard_from_scf
    rhf = hubbard_from_scf(scf.RHF, 10, 10, 4, 'y')
    rhf.scf()

    from tcc.rccsdt import RCCSDT_UNIT
    from tcc.cc_solvers import residual_diis_solver, classic_solver
    cc = RCCSDT(rhf)

    converged, energy, amps = classic_solver(cc,
                                             conv_tol_energy=1e-12,
                                             conv_tol_res=1e-12,
                                             lam=17,
                                             max_cycle=1000)

    h = cc.create_ham()
    res = cc.calc_residuals(h, amps)
    r3 = res.t3
    # Apply n_body symmetry
    r3 = (+r3 + r3.transpose([1, 2, 0, 4, 5, 3]) +
          r3.transpose([2, 0, 1, 5, 3, 4]) + r3.transpose([0, 2, 1, 3, 5, 4]) +
          r3.transpose([2, 1, 0, 5, 4, 3]) +
          r3.transpose([1, 0, 2, 4, 3, 5])) / 6

    import numpy as np
    norms = res.map(np.linalg.norm)
    print('E: {}'.format(energy))
    print('r1: {}, r2: {}, r3: {}, r3_nbody: {}'.format(
        norms.t1, norms.t2, norms.t3, np.linalg.norm(r3)))
    print('dE: {}'.format(energy - -1.311811e-01))
Ejemplo n.º 10
0
def test_cpd_unf():
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]

    mol.basis = {
        'H': '3-21g',
        'O': '3-21g',
    }
    mol.build()
    rhf_ri = scf.density_fit(scf.RHF(mol))
    rhf_ri.scf()  # -76.0267656731

    from tcc.rccsd import RCCSD, RCCSD_DIR_RI
    from tcc.rccsd_cpd import (RCCSD_nCPD_LS_T, RCCSD_CPD_LS_T)

    from tcc.cc_solvers import (classic_solver, step_solver)

    cc1 = RCCSD_DIR_RI(rhf_ri)
    cc2 = RCCSD_nCPD_LS_T(rhf_ri, rankt={'t2': 30})
    cc3 = RCCSD_CPD_LS_T(rhf_ri, rankt={'t2': 30})

    converged1, energy1, amps1 = classic_solver(
        cc1,
        conv_tol_energy=1e-8,
    )

    converged2, energy2, amps2 = classic_solver(cc2,
                                                conv_tol_energy=1e-8,
                                                max_cycle=50)

    converged2, energy2, amps2 = step_solver(cc2,
                                             conv_tol_energy=1e-8,
                                             beta=0,
                                             max_cycle=150)

    converged3, energy3, amps3 = classic_solver(cc3,
                                                conv_tol_energy=1e-8,
                                                max_cycle=50)

    converged3, energy3, amps3 = step_solver(cc3,
                                             conv_tol_energy=1e-8,
                                             beta=0,
                                             max_cycle=150)
Ejemplo n.º 11
0
def compare_to_aq():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]
    mol.basis = {
        'H': '3-21g',
        'O': '3-21g',
    }
    mol.build()
    rhf = scf.RHF(mol)
    rhf.scf()  # -76.0267656731

    # load reference arrays
    import h5py
    import numpy as np
    f1 = h5py.File('data/test_references/aq_ccsd_amps.h5', 'r')
    # use amplitudes from the last iteration
    num_steps = int(len(f1.keys()) / 2)
    t1 = f1['t1_' + str(num_steps)][()].T
    t2 = f1['t2_' + str(num_steps)][()].T
    f1.close()

    f1 = h5py.File('data/test_references/aq_ccsd_mos.h5', 'r')
    CA = np.hstack((f1['cI'][()].T, f1['cA'][()].T))
    CB = np.hstack((f1['ci'][()].T, f1['ca'][()].T))
    f1.close()

    # permute AO indices to match pyscf order
    perm = [0, 1, 2, 4, 5, 3, 7, 8, 6, 9, 10, 11, 12]
    from tcc.utils import perm_matrix
    m = perm_matrix(perm)
    CA_perm = m.dot(CA)

    from tcc.cc_solvers import residual_diis_solver
    from tcc.cc_solvers import step_solver, classic_solver
    from tcc.rccsd import RCCSD
    cc = RCCSD(rhf, mo_coeff=CA_perm)

    converged, energy, amps = classic_solver(cc,
                                             conv_tol_energy=1e-14,
                                             conv_tol_res=1e-10,
                                             max_cycle=200)

    print('dt1: {}'.format(np.max(t1 - amps.t1)))
    print('dt2: {}'.format(np.max(t2 - amps.t2)))

    from tcc.tensors import Tensors
    test_amps = Tensors(t1=t1, t2=t2)
    h = cc.create_ham()
    r = cc.calc_residuals(h, test_amps)

    print('max r1: {}'.format(np.max(r.t1)))
    print('max r2: {}'.format(np.max(r.t2)))
Ejemplo n.º 12
0
def test_hubbard():  # pragma: nocover
    from pyscf import scf
    from tcc.hubbard import hubbard_from_scf
    rhf = hubbard_from_scf(scf.RHF, 6, 6, 1, 'y')
    rhf.damp = -4.0
    rhf.scf()

    from tcc.cc_solvers import (classic_solver, root_solver)
    from tcc.rccsd_mul import RCCSD_MUL_RI_HUB
    from tcc.rccsd_cpd import RCCSD_CPD_LS_T_HUB

    cc1 = RCCSD_MUL_RI_HUB(rhf)
    cc2 = RCCSD_CPD_LS_T_HUB(rhf, rankt={'t2': 30})

    converged1, energy1, amps1 = classic_solver(cc1, lam=5, max_cycle=50)

    converged2, energy2, amps2 = classic_solver(cc2,
                                                lam=1,
                                                conv_tol_energy=1e-8,
                                                max_cycle=500)
Ejemplo n.º 13
0
    def test_rccsd_unit(self):
        from tcc.cc_solvers import classic_solver, residual_diis_solver
        from tcc.rccsd import RCCSD, RCCSD_UNIT

        cc1 = RCCSD(self.rhf)
        cc2 = RCCSD_UNIT(self.rhf)
        converged1, energy1, amps = classic_solver(cc1)
        converged2, energy2, _ = classic_solver(cc2)

        self.assertEqual(converged1, converged2)

        self.assertEqual(np.allclose(energy1, -0.2133432609672395, 1e-5), True)
        self.assertEqual(np.allclose(energy1, energy2, 1e-5), True)
        
        converged1, energy1, _ = residual_diis_solver(cc1, amps=amps,
                                                         conv_tol_energy=1e-10)
        converged2, energy2, _ = residual_diis_solver(cc2, amps=amps,
                                                conv_tol_energy=1e-10)
        
        self.assertEqual(np.allclose(energy1, -0.2133432609672395, 1e-5), True)
        self.assertEqual(np.allclose(energy1, energy2, 1e-5), True)
Ejemplo n.º 14
0
def test_compare_to_hirata():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = """
    # H2O
    H    0.000000000000000   1.079252144093028   1.474611055780858
    O    0.000000000000000   0.000000000000000   0.000000000000000
    H    0.000000000000000   1.079252144093028  -1.474611055780858
    """
    mol.unit = 'Bohr'
    mol.basis = {
        'H':
        gto.basis.parse("""
            H         S
                      3.42525091         0.15432897
                      0.62391373         0.53532814
                      0.16885540         0.44463454
            """),
        'O':
        gto.basis.parse("""
            O         S
                    130.70932000         0.15432897
                     23.80886100         0.53532814
                      6.44360830         0.44463454
            O         S
                      5.03315130        -0.09996723
                      1.16959610         0.39951283
                      0.38038900         0.70011547
            O         P
                      5.03315130         0.15591627
                      1.16959610         0.60768372
                      0.38038900         0.39195739
            """),
    }
    mol.build()
    rhf = scf.RHF(mol)
    rhf.scf()

    from tcc.cc_solvers import classic_solver, update_diis_solver
    from tcc.rccsdt import RCCSDT, RCCSDT_UNIT, RCCSDT_UNIT_ANTI
    cc1 = RCCSDT(rhf)

    converged, energy, amps = classic_solver(cc1,
                                             conv_tol_energy=1e-11,
                                             lam=3,
                                             conv_tol_res=1e-11,
                                             max_cycle=200)

    print('E_cc: {}'.format(energy))
    print('E_tot: {}'.format(rhf.e_tot + energy))
    print('delta E: {}'.format(energy - -0.0502322580))
Ejemplo n.º 15
0
def test_compare_to_aq():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]
    mol.basis = {
        'H': '3-21g',
        'O': '3-21g',
    }
    mol.build()
    rhf = scf.RHF(mol)
    rhf.scf()  # -76.0267656731

    # load reference arrays
    import h5py
    import numpy as np
    f1 = h5py.File('data/test_references/aq_ccsdt_amps.h5', 'r')
    # use amplitudes from the last iteration
    num_steps = int(len(f1.keys()) / 4)
    t1 = f1['t1_' + str(num_steps)][()].T
    t2 = f1['t2_' + str(num_steps)][()].T
    t3 = f1['t3_' + str(num_steps)][()].T
    t3a = f1['t3b_' + str(num_steps)][()].T
    f1.close()

    f1 = h5py.File('data/test_references/aq_ccsdt_mos.h5', 'r')
    CA = np.hstack((f1['cI'][()].T, f1['cA'][()].T))
    CB = np.hstack((f1['ci'][()].T, f1['ca'][()].T))
    f1.close()

    # permute AO indices to match pyscf order
    from tcc.utils import perm_matrix
    perm = [0, 1, 2, 4, 5, 3, 7, 8, 6, 9, 10, 11, 12]
    m = perm_matrix(perm)
    CA_perm = m.dot(CA)

    from tcc.cc_solvers import residual_diis_solver
    from tcc.cc_solvers import (step_solver, classic_solver,
                                residual_diis_solver)
    from tcc.rccsdt import RCCSDT
    from tcc.rccsd import RCCSD
    cc = RCCSDT(rhf, mo_coeff=CA_perm)

    converged, energy, amps = classic_solver(cc,
                                             conv_tol_energy=1e-10,
                                             conv_tol_res=1e-10,
                                             max_cycle=300)

    print('delta E: {}'.format(energy - -0.1311305308))
Ejemplo n.º 16
0
def test_cc_ri():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [['O', (0., 0., 0.)], ['H', (0., -0.757, 0.587)],
                ['H', (0., 0.757, 0.587)]]

    mol.basis = 'sto-3g'
    mol.build()
    rhf = scf.RHF(mol)
    rhf.scf()  # -76.0267656731

    rhf_ri = scf.density_fit(scf.RHF(mol))
    rhf_ri.scf()

    from tcc.cc_solvers import residual_diis_solver
    from tcc.cc_solvers import classic_solver
    from tcc.rccsd import RCCSD_DIR_RI, RCCSD
    cc1 = RCCSD_DIR_RI(rhf_ri)
    cc2 = RCCSD(rhf)

    converged1, energy2, _ = classic_solver(cc1, conv_tol_energy=-1)

    converged2, energy2, _ = classic_solver(cc2, conv_tol_energy=-1)
Ejemplo n.º 17
0
def calc_solutions_diff_r_eq_cpd():
    """
    Plot error of RCCSD-CPD vs rank for weak corellation
    """
    rankst = RANKS_T.copy()

    # Run RHF calculations
    rhf = hubbard_from_scf(scf.RHF, N, N, U, 'y')
    rhf.damp = -4.0
    rhf.scf()

    rhf_results = tuple([rhf.e_tot, rhf.mo_coeff, rhf.mo_energy])

    with open('calculated/{}-site/amps_and_scf_eq/rhf_results_u_{}.p'.format(N, U), 'wb') as fp:
        pickle.dump(rhf_results, fp)

    # Run reference calculation
    cc_ref = RCCSD_UNIT(rhf)
    _, energy_ref, amps_ref = root_solver(cc_ref, conv_tol=1e-10)

    cc_results = tuple([energy_ref, amps_ref])

    with open('calculated/{}-site/amps_and_scf_eq/cc_results_u_{}.p'.format(N, U), 'wb') as fp:
        pickle.dump(cc_results, fp)

    all_amps = []
    for idx, rank in enumerate(rankst):
        tim = time.process_time()
        cc = RCCSD_nCPD_LS_T_HUB(rhf, rankt={'t2': rank})
        converged, energy, amps = classic_solver(
            cc, lam=1.8, conv_tol_energy=1e-14,
            conv_tol_amps=1e-10, max_cycle=40000,
            verbose=logger.NOTE)
        if not converged:
            Warning(
                'Warning: N = {}, U = {} '
                'Rank = {} did not converge'.format(N, U, rank)
            )
        all_amps.append(tuple([energy, rank, amps]))
        elapsed = time.process_time() - tim
        print('Step {} out of {}, rank = {}, time: {}'.format(
            idx + 1, len(rankst), rank, elapsed
        ))

    with open('calculated/{}-site/amps_and_scf_eq/energy_rank_amps_u_{}.p'.format(N, U), 'wb') as fp:
        pickle.dump(all_amps, fp)
Ejemplo n.º 18
0
def test_cc():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]
    mol.basis = {
        'H': '3-21g',
        'O': '3-21g',
    }
    mol.build()
    rhf = scf.RHF(mol)
    rhf = scf.density_fit(scf.RHF(mol))
    rhf.scf()

    from tcc.rccsdt_ri import RCCSDT_RI
    from tcc.rccsdt_cpd import RCCSDT_nCPD_LS_T
    from tcc.rccsdt_cpd import RCCSDT_CPD_LS_T
    from tcc.cc_solvers import (classic_solver, step_solver)
    cc1 = RCCSDT_RI(rhf)
    cc2 = RCCSDT_nCPD_LS_T(rhf, rankt={'t2': 20, 't3': 40})
    cc3 = RCCSDT_CPD_LS_T(rhf, rankt={'t2': 20, 't3': 40})

    converged1, energy1, amps1 = classic_solver(cc1,
                                                conv_tol_energy=1e-9,
                                                conv_tol_res=1e-8,
                                                max_cycle=100)

    print('dE: {}'.format(energy1 - -1.304876e-01))

    import numpy as np
    np.seterr(all='raise')
    import warnings
    warnings.filterwarnings("error")

    converged2, energy2, amps2 = step_solver(cc2,
                                             conv_tol_energy=1e-8,
                                             max_cycle=100)

    converged3, energy3, amps3 = step_solver(cc3,
                                             conv_tol_energy=1e-8,
                                             max_cycle=100)

    print('dE: {}'.format(energy2 - -0.12621546190311517))
    print('E(CPD)-E(nCPD): {}'.format(energy3 - energy2))
Ejemplo n.º 19
0
    def test_rccsd_mul(self):
        from tcc.cc_solvers import classic_solver, residual_diis_solver
        from tcc.rccsd_mul import RCCSD_MUL

        cc = RCCSD_MUL(self.rhf)
        converged, energy, amps = classic_solver(cc,
                                                 conv_tol_amps=1e-8,
                                                 conv_tol_energy=1e-8)

        self.assertEqual(converged, True)
        self.assertEqual(np.allclose(energy, -0.049467456410677929, 1e-5),
                         True)
        cc._converged = False
        converged, energy1, _ = residual_diis_solver(cc,
                                                     amps=amps,
                                                     conv_tol_energy=1e-10)
        self.assertEqual(np.allclose(energy, -0.049467456410677929, 1e-5),
                         True)
Ejemplo n.º 20
0
def test_hubbard_iterations():
    from pyscf import gto
    from pyscf import scf
    from tcc.hubbard import hubbard_from_scf
    rhf = hubbard_from_scf(scf.RHF, 6, 6, 3, 'y')
    rhf.damp = -4.0
    rhf.scf()

    from scipy.io import loadmat
    ref = loadmat('reference_hub_rccsdthc.mat', matlab_compatible=True)
    mo_coeff = ref['orbA']
    mo_energy = ref['valsA'].flatten()

    from tcc.cc_solvers import classic_solver
    from tcc.rccsd_thc import RCCSD_THC_LS_T_HUB
    cc = RCCSD_THC_LS_T_HUB(rhf,
                            rankt=3,
                            mo_energy=mo_energy,
                            mo_coeff=mo_coeff)
    t1 = ref['t1']
    t2l = ref['t2s'][0][0]
    amps = cc.types.AMPLITUDES_TYPE(t1, *t2l)

    t1n = ref['t1n']
    t2ln = ref['t2sn'][0][0]
    ref_amps = cc.types.AMPLITUDES_TYPE(t1n, *t2ln)

    dt1 = ref['dt1']
    dt2l = ref['dt2s'][0][0]
    delta = cc.types.AMPLITUDES_TYPE(dt1, *dt2l)

    ham = cc.create_ham()
    res = cc.calc_residuals(ham, amps)
    rhs = cc.update_rhs(ham, amps, res)
    new_amps = cc.solve_amps(ham, amps, rhs)

    delta1 = cc.types.AMPLITUDES_TYPE(
        new_amps.t1 - amps.t1, new_amps.x1 - amps.x1, new_amps.t1 - amps.x2,
        new_amps.t1 - amps.x3, new_amps.t1 - amps.x4, new_amps.t1 - amps.x5)
    # cc = RCCSD_THC_LS_T_HUB(rhf, rankt=3)
    converged, energy, _ = classic_solver(cc, max_cycle=300, lam=3, amps=amps)
    print(converged, energy)
Ejemplo n.º 21
0
def test_cc():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]

    mol.basis = {
        'H': 'cc-pvdz',
        'O': 'cc-pvdz',
    }
    mol.build()
    rhf = scf.RHF(mol)
    rhf = scf.density_fit(scf.RHF(mol))
    rhf.scf()  # -76.0267656731

    from tcc.cc_solvers import classic_solver
    from tcc.rccsd_mul import RCCSD_MUL_RI
    cc = RCCSD_MUL_RI(rhf)
    converged, energy, _ = classic_solver(cc)
Ejemplo n.º 22
0
def test_cc_anti():  # pragma: nocover
    from pyscf import gto
    from pyscf import scf
    mol = gto.Mole()
    mol.unit = 'Angstrom'
    mol.atom = [[8, (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]
    mol.basis = '3-21g'
    mol.build()
    rhf = scf.RHF(mol)
    rhf.scf()

    from tcc.rccsdt import RCCSDT_UNIT_ANTI
    from tcc.cc_solvers import classic_solver
    cc = RCCSDT_UNIT_ANTI(rhf)

    converged, energy, amps = classic_solver(cc,
                                             conv_tol_energy=1e-10,
                                             conv_tol_res=1e-10,
                                             lam=3,
                                             max_cycle=100)

    h = cc.create_ham()
    res = cc.calc_residuals(h, amps)
    r3 = res.t3
    # Extract antisymmetric part only
    r3 = 1 / 6 * (+r3 - r3.transpose([1, 0, 2, 3, 4, 5]) + r3.transpose(
        [1, 2, 0, 3, 4, 5]) - r3.transpose([2, 1, 0, 3, 4, 5]) + r3.transpose(
            [2, 0, 1, 3, 4, 5]) - r3.transpose([0, 2, 1, 3, 4, 5]))
    r3 = 1 / 6 * (+r3 - r3.transpose([0, 1, 2, 4, 3, 5]) + r3.transpose(
        [0, 1, 2, 4, 5, 3]) - r3.transpose([0, 1, 2, 5, 4, 3]) + r3.transpose(
            [0, 1, 2, 5, 3, 4]) - r3.transpose([0, 1, 2, 3, 5, 4]))

    import numpy as np
    norms = res.map(np.linalg.norm)
    print('r1: {}, r2: {}, r3: {}, r3_antisym: {}'.format(
        norms.t1, norms.t2, norms.t3, np.linalg.norm(r3)))
    # The energy should be higher than in the correct RCCSDT
    # due to more restrictions on the symmetry of T3 than needed
    # r3 residual is not zero, but its antisymmetric part is
    print('dE: {}'.format(energy - -1.311811e-01))
Ejemplo n.º 23
0
def test_update_diis_solver():
    from tcc.hubbard import hubbard_from_scf
    from pyscf import scf
    N = 6
    U = 4
    USE_PBC = 'y'
    rhf = hubbard_from_scf(scf.RHF, N, N, U, USE_PBC)
    rhf.scf()  # -76.0267656731

    from tcc.rccsd import RCCSD_UNIT
    from tcc.rccsd_cpd import (RCCSD_nCPD_LS_T_HUB)

    cc1 = RCCSD_UNIT(rhf)
    cc2 = RCCSD_nCPD_LS_T_HUB(rhf, rankt={'t2': 30})

    from tcc.cc_solvers import (residual_diis_solver, update_diis_solver,
                                classic_solver)
    cc1._converged = False
    converged1, energy1, amps1 = residual_diis_solver(cc1,
                                                      conv_tol_energy=1e-8,
                                                      lam=3,
                                                      max_cycle=100)

    import pickle
    with open('test_amps.p', 'rb') as fp:
        ampsi = pickle.load(fp)

    cc2._converged = False
    converged2, energy2, amps2 = update_diis_solver(cc2,
                                                    conv_tol_energy=1e-8,
                                                    conv_tol_res=1e-8,
                                                    beta=0.666,
                                                    max_cycle=100,
                                                    amps=ampsi)

    cc2._converged = False
    converged2, energy2, amps2 = classic_solver(cc2,
                                                conv_tol_energy=1e-8,
                                                conv_tol_res=1e-8,
                                                lam=3,
                                                max_cycle=100)
Ejemplo n.º 24
0
def calc_t1_norm_vs_u_cpd():
    """
    Plot T1 norm of RCCSD-CPD for all corellation strengths
    """
    # Set up parameters of the script
    N = 10
    us = np.linspace(1, 10, num=10)
    lambdas = [
        3,
    ] * 6 + [
        4,
    ] * 3 + [
        4,
    ]
    rankst = np.array([5, 7, 8, 10, 12, 20]).astype('int')

    results = np.array(us)
    results_t1 = np.array(us)
    results_t2 = np.array(us)

    # Run all scfs here so we will have same starting points for CC
    run_scfs(N, us, 'calculated/{}-site/scfs_different_u_t1.p'.format(N))
    with open('calculated/{}-site/scfs_different_u_t1.p'.format(N),
              'rb') as fp:
        ref_scfs = pickle.load(fp)

    for idxr, rank in enumerate(rankst):
        t1_norms = []
        energies = []
        t2_norms = []
        # timb = time.process_time()
        for idxu, (u, curr_scf) in enumerate(zip(us, ref_scfs)):
            tim = time.process_time()
            rhf = hubbard_from_scf(scf.RHF, N, N, u, 'y')
            rhf.max_cycle = 1
            rhf.scf()
            e_scf, mo_coeff, mo_energy = curr_scf
            cc = RCCSD_CPD_LS_T_HUB(rhf,
                                    rankt=rank,
                                    mo_coeff=mo_coeff,
                                    mo_energy=mo_energy)
            converged = False
            if idxu == 0:
                converged, energy, amps = classic_solver(cc,
                                                         lam=lambdas[idxu],
                                                         conv_tol_energy=1e-8,
                                                         conv_tol_amps=1e-7,
                                                         max_cycle=20000,
                                                         verbose=logger.NOTE)
            else:
                converged, energy, amps = classic_solver(cc,
                                                         lam=lambdas[idxu],
                                                         conv_tol_energy=1e-8,
                                                         conv_tol_amps=1e-7,
                                                         max_cycle=30000,
                                                         verbose=logger.NOTE)
            if np.isnan(energy):
                Warning('Warning: N = {}, U = {} '
                        'Rank = {} did not converge'.format(N, u, rank))

            energies.append(energy + e_scf)
            if not np.isnan(energy):
                t1_norms.append(np.linalg.norm(amps.t1))
            else:
                t1_norms.append(np.nan)

            if not np.isnan(energy):
                tmp, _ = cpd_normalize(amps[1:])
                t2_norms.append(tmp[0])
            else:
                t2_norms.append(np.nan)

            elapsed = time.process_time() - tim
            print('Step {} out of {}, rank = {}, time: {}\n'.format(
                idxu + 1, len(us), rank, elapsed))

        results = np.column_stack((results, energies))
        results_t1 = np.column_stack((results_t1, t1_norms))
        results_t2 = np.column_stack((results_t2, t2_norms))
        # elapsedb = time.process_time() - timb
        # print('Batch {} out of {}, rank = {}, time: {}'.format(
        #  0 + 1, len(rankst), rank, elapsedb))

    # np.savetxt(
    #     'calculated/{}-site/t1_norm_vs_u_energies.txt'.format(N),
    #     results,
    #     header='U '+' '.join('R={}'.format(rr) for rr in rankst)
    # )
    # np.savetxt(
    #     'calculated/{}-site/t1_norm_vs_u.txt'.format(N),
    #     results_t1,
    #     header='U '+' '.join('R={}'.format(rr) for rr in rankst)
    # )
    np.savetxt('calculated/{}-site/lam_1_vs_u.txt'.format(N),
               results_t2,
               header='U ' + ' '.join('R={}'.format(rr) for rr in rankst))

    us, *t1_norms_l = np.loadtxt(
        'calculated/{}-site/t1_norm_vs_u.txt'.format(N), unpack=True)

    # Plot
    from matplotlib import pyplot as plt
    fig, ax = plt.subplots()
    plt.plot(us, t1_norms)
    plt.xlabel('$U$')
    plt.ylabel('$||T^{1}||$')
    plt.title('Energy behavior for different ranks')
    fig.show()
Ejemplo n.º 25
0
def calc_energy_vs_u_cpd():
    """
    Plot energy of RCCSD-CPD for all corellation strengths
    """
    # Set up parameters of the script
    us = U_VALUES.copy()
    lambdas = LAMBDAS.copy()
    rankst = RANKS_T.copy()

    results = np.array(us)

    print('Running CC-CPD')
    # Run all scfs here so we will have same starting points for CC
    run_scfs(N, us, 'calculated/{}-site/scfs_different_u.p'.format(N))
    with open('calculated/{}-site/scfs_different_u.p'.format(N), 'rb') as fp:
        ref_scfs = pickle.load(fp)

    for idxr, rank in enumerate(rankst):
        energies = []
        converged = False
        # timb = time.process_time()
        amps = None
        for idxu, (u, curr_scf) in enumerate(zip(us, ref_scfs)):
            tim = time.process_time()
            rhf = hubbard_from_scf(scf.RHF, N, N, u, USE_PBC)
            rhf.max_cycle = 1
            rhf.scf()
            e_scf, mo_coeff, mo_energy = curr_scf
            cc = RCCSD_CPD_LS_T_HUB(rhf,
                                    rankt={'t2': rank},
                                    mo_coeff=mo_coeff,
                                    mo_energy=mo_energy)
            if not converged:
                amps = None

            converged, energy, amps = classic_solver(cc,
                                                     lam=lambdas[idxr][idxu],
                                                     conv_tol_energy=1e-8,
                                                     conv_tol_amps=1e-7,
                                                     max_cycle=40000,
                                                     verbose=logger.NOTE)
            # converged, energy, amps = step_solver(
            #     cc, beta=0.7,  # (1 - 1. / lambdas[idxr][idxu]),
            #     conv_tol_energy=1e-8,
            #     conv_tol_amps=1e-7, max_cycle=20000,
            #     verbose=logger.NOTE)

            if np.isnan(energy):
                Warning('Warning: N = {}, U = {} '
                        'Rank = {} did not converge'.format(N, u, rank))

            energies.append(energy + e_scf)
            elapsed = time.process_time() - tim
            print('Step {} out of {}, rank = {}, time: {}\n'.format(
                idxu + 1, len(us), rank, elapsed))

        results = np.column_stack((results, energies))
        # elapsedb = time.process_time() - timb
        # print('Batch {} out of {}, rank = {}, time: {}'.format(
        #  0 + 1, len(rankst), rank, elapsedb))

    np.savetxt('calculated/{}-site/energy_vs_u.txt'.format(N),
               results,
               header='U ' + ' '.join('R={}'.format(rr) for rr in rankst))
    us, *energies_l = np.loadtxt(
        'calculated/{}-site/energy_vs_u.txt'.format(N), unpack=True)

    # Plot
    from matplotlib import pyplot as plt
    fig, ax = plt.subplots()
    plt.plot(us, energies)
    plt.xlabel('$U$')
    plt.ylabel('$E$, H')
    plt.title('Energy behavior for different ranks')
    fig.show()
Ejemplo n.º 26
0
def calc_err_vs_r_cpd():
    """
    Plot error of RCCSD-CPD vs rank for weak corellation
    """
    # Set up parameters of the script
    N = 14
    U = 2

    rankst = np.round(N**np.linspace(0.2, 1.8, num=10)).astype('int')

    # Run RHF calculations
    from pyscf import scf
    from tcc.hubbard import hubbard_from_scf
    rhf = hubbard_from_scf(scf.RHF, N, N, U, 'y')
    rhf.damp = -4.0
    rhf.scf()

    from tcc.cc_solvers import (classic_solver, root_solver)
    from tcc.rccsd import RCCSD_UNIT
    from tcc.rccsd_cpd import RCCSD_CPD_LS_T_HUB
    from tensorly.decomposition import parafac

    # Run reference calculation
    cc_ref = RCCSD_UNIT(rhf)
    _, energy_ref, amps_ref = root_solver(cc_ref, conv_tol=1e-10)

    energies = []
    deltas = []
    for idx, rank in enumerate(rankst):
        tim = time.process_time()
        cc = RCCSD_CPD_LS_T_HUB(rhf, rankt=rank)
        xs = parafac(
            amps_ref.t2, rank, tol=1e-14
        )
        amps_guess = cc.types.AMPLITUDES_TYPE(
            amps_ref.t1, *xs
        )
        converged, energy, amps = classic_solver(
            cc, lam=1.8, conv_tol_energy=1e-14,
            conv_tol_amps=1e-10, max_cycle=10000,
            amps=amps_guess, verbose=logger.NOTE)
        if not converged:
            Warning(
                'Warning: N = {}, U = {} '
                'Rank = {} did not converge'.format(N, U, rank)
            )
        energies.append(energy)
        deltas.append(energy - energy_ref)
        elapsed = time.process_time() - tim
        print('Step {} out of {}, rank = {}, time: {}'.format(
            idx + 1, len(rankst), rank, elapsed
        ))

    results = np.column_stack((rankst, energies, deltas))
    np.savetxt(
        'calculated/{}-site/err_vs_rank.txt'.format(N),
        results, header='Rank Energy Delta', fmt=('%i', '%e', '%e')
    )
    rankst, energies, deltas = np.loadtxt(
        'calculated/{}-site/err_vs_rank.txt'.format(N), unpack=True)

    # Plot
    from matplotlib import pyplot as plt
    plt.plot(np.log(rankst)/np.log(N), np.log10(np.abs(deltas)))
    plt.xlabel('log$_N(R)$')
    plt.ylabel('log($\Delta$)')
    plt.title('Error dependence on rank in weak correlation regime')
    plt.show()
Ejemplo n.º 27
0
def calc_energy_vs_d_cpd():
    """
    Plot energy of RCCSD-CPD for different distances in dissociation of N2
    """
    # Set up parameters of the script

    basis = 'cc-pvdz'
    dists = np.linspace(0.8, 2.7, num=15)
    lambdas = [
        3,
    ] * 6 + [
        5,
    ] * 6 + [
        6,
    ] * 3
    rankst = np.array([2, 4, 5, 6, 8]).astype('int')

    def make_mol(dist):
        from pyscf import gto
        mol = gto.Mole()
        mol.atom = [[7, (0., 0., 0.)], [7, (0., 0., dist)]]

        mol.basis = {'N': basis}
        mol.build()
        return mol

    mols = [make_mol(dist) for dist in dists]

    results = np.array(dists)

    # Run all scfs here so we will have same starting points for CC
    run_scfs(mols, 'calculated/{}/scfs_different_dist.p'.format(basis))
    with open('calculated/{}/scfs_different_dist.p'.format(basis), 'rb') as fp:
        ref_scfs = pickle.load(fp)

    for idxr, rank in enumerate(rankst):
        lambdas = [
            3,
        ] * 6 + [
            4,
        ] * 0 + [
            6,
        ] * 6 + [
            6,
        ] * 3

        energies = []
        converged = False
        # timb = time.process_time()
        for idxd, (dist, curr_scf) in enumerate(zip(dists, ref_scfs)):
            tim = time.process_time()
            rhf = scf.density_fit(scf.RHF(mols[idxd]))
            rhf.max_cycle = 1
            rhf.scf()
            e_scf, mo_coeff, mo_energy = curr_scf
            cc = RCCSD_CPD_LS_T(rhf,
                                rankt=rank,
                                mo_coeff=mo_coeff,
                                mo_energy=mo_energy)
            if not converged:
                amps = None

            converged, energy, amps = classic_solver(cc,
                                                     lam=lambdas[idxd],
                                                     conv_tol_energy=1e-8,
                                                     conv_tol_amps=1e-7,
                                                     max_cycle=30000,
                                                     verbose=logger.NOTE)

            if not converged:
                Warning('Warning: D = {} Rank = {}'
                        ' did not converge'.format(dist, rank))

            energies.append(energy + e_scf)
            elapsed = time.process_time() - tim
            print('Step {} out of {}, rank = {}, time: {}\n'.format(
                idxd + 1, len(dists), rank, elapsed))

        results = np.column_stack((results, energies))
        # elapsedb = time.process_time() - timb
        # print('Batch {} out of {}, rank = {}, time: {}'.format(
        #  0 + 1, len(rankst), rank, elapsedb))

    np.savetxt('calculated/{}/energy_vs_d.txt'.format(basis),
               results,
               header='Dist ' + ' '.join('R={}'.format(rr) for rr in rankst))
    us, *energies_l = np.loadtxt('calculated/{}/energy_vs_d.txt'.format(basis),
                                 unpack=True)

    # Plot
    from matplotlib import pyplot as plt
    fig, ax = plt.subplots()
    plt.plot(dists, energies, marker='o')
    plt.xlabel('$D, \AA$')
    plt.ylabel('$E$, H')
    plt.title('Energy behavior for different ranks')
    fig.show()
Ejemplo n.º 28
0
def calc_solutions_diff_u_cpd():
    """
    Run RCCSD-CPD for all corellation strengths
    """
    # Set up parameters of the script
    us = U_VALUES.copy()
    lambdas = LAMBDAS.copy()
    rankst = RANKS_T.copy()

    results = np.array(us)
    results_t1 = np.array(us)
    results_t2 = np.array(us)

    # Run all scfs here so we will have same starting points for CC
    run_scfs(N, us, 'calculated/{}-site/scfs_different_u_t1.p'.format(N))
    with open('calculated/{}-site/scfs_different_u_t1.p'.format(N),
              'rb') as fp:
        ref_scfs = pickle.load(fp)

    for idxr, rank in enumerate(rankst):
        t1_norms = []
        energies = []
        t2_norms = []
        # timb = time.process_time()
        solutions = []
        for idxu, (u, curr_scf) in enumerate(zip(us, ref_scfs)):
            tim = time.process_time()
            rhf = hubbard_from_scf(scf.RHF, N, N, u, 'y')
            rhf.max_cycle = 1
            rhf.scf()
            e_scf, mo_coeff, mo_energy = curr_scf
            cc = RCCSD_nCPD_LS_T_HUB(rhf,
                                     rankt={'t2': rank},
                                     mo_coeff=mo_coeff,
                                     mo_energy=mo_energy)
            converged = False
            if idxu == 0:
                converged, energy, amps = classic_solver(
                    cc,
                    lam=lambdas[idxr][idxu],
                    conv_tol_energy=1e-8,
                    conv_tol_amps=1e-7,
                    max_cycle=50000,
                    verbose=logger.NOTE)
            else:
                converged, energy, amps = classic_solver(
                    cc,
                    lam=lambdas[idxr][idxu],
                    conv_tol_energy=1e-8,
                    conv_tol_amps=1e-8,
                    max_cycle=60000,
                    verbose=logger.NOTE,
                    amps=amps)
            solutions.append((u, curr_scf, amps))
            if np.isnan(energy):
                Warning('Warning: N = {}, U = {} '
                        'Rank = {} did not converge'.format(N, u, rank))

            energies.append(energy + e_scf)
            norms = amps.map(np.linalg.norm)
            if not np.isnan(energy):
                t1_norms.append(norms.t1)
            else:
                t1_norms.append(np.nan)

            if not np.isnan(energy):
                t2_norms.append(amps.t2.xlam[0, 0])
            else:
                t2_norms.append(np.nan)

            elapsed = time.process_time() - tim
            print('Step {} out of {}, rank = {}, time: {}\n'.format(
                idxu + 1, len(us), rank, elapsed))

        results = np.column_stack((results, energies))
        results_t1 = np.column_stack((results_t1, t1_norms))
        results_t2 = np.column_stack((results_t2, t2_norms))
        with open('amps_and_scf_rank_{}.p'.format(rank), 'wb') as fp:
            pickle.dump(solutions, fp)