Example #1
0
def test():

    mol = gto.M(atom="Li 0. 0. 0.; Li 0. 0. 1.5",
                basis="sto-3g",
                unit="bohr",
                verbose=0)
    mf = scf.RHF(mol).run()

    # Lowdin orthogonalized AO basis.
    lowdin = lo.orth_ao(mol, "lowdin")

    # MOs in the Lowdin basis.
    mo = solve(lowdin, mf.mo_coeff)

    # make AO to localized orbital coefficients.
    mfobdm = mf.make_rdm1(mo, mf.mo_occ)

    ### Test OBDM calculation.
    nconf = 500
    nsteps = 400
    obdm_steps = 4
    warmup = 15
    wf = PySCFSlaterUHF(mol, mf)
    configs = initial_guess(mol, nconf)
    energy = EnergyAccumulator(mol)
    obdm = OBDMAccumulator(mol=mol, orb_coeff=lowdin, nsweeps=1)
    obdm_up = OBDMAccumulator(mol=mol, orb_coeff=lowdin, nsweeps=1, spin=0)
    obdm_down = OBDMAccumulator(mol=mol, orb_coeff=lowdin, nsweeps=1, spin=1)

    df, coords = vmc(
        wf,
        configs,
        nsteps=nsteps,
        accumulators={
            "energy": energy,
            "obdm": obdm,
            "obdm_up": obdm_up,
            "obdm_down": obdm_down,
        },
    )
    df = DataFrame(df)

    obdm_est = {}
    for k in ["obdm", "obdm_up", "obdm_down"]:
        avg_norm = np.array(df.loc[warmup:,
                                   k + "norm"].values.tolist()).mean(axis=0)
        avg_obdm = np.array(df.loc[warmup:,
                                   k + "value"].values.tolist()).mean(axis=0)
        obdm_est[k] = normalize_obdm(avg_obdm, avg_norm)

    print("Average OBDM(orb,orb)", obdm_est["obdm"].diagonal().round(3))
    print("mf obdm", mfobdm.diagonal().round(3))
    assert np.max(np.abs(obdm_est["obdm"] - mfobdm)) < 0.05
    print(obdm_est["obdm_up"].diagonal().round(3))
    print(obdm_est["obdm_down"].diagonal().round(3))
    assert np.mean(
        np.abs(obdm_est["obdm_up"] + obdm_est["obdm_down"] - mfobdm)) < 0.05
Example #2
0
def find_basis_evaluate(mfchk, hdf_opt, hdf_vmc, hdf_final):
    """Given a wave function in hdf_opt, compute the 1-RDM (stored in hdf_vmc) , generate a minimal atomic basis and compute the energy/OBDM/TBDM and store in hdf_final """
    from pyqmc.obdm import OBDMAccumulator
    from pyqmc.tbdm import TBDMAccumulator
    from pyqmc import EnergyAccumulator

    sys = pyqmc_from_hdf(mfchk)

    mol = sys["mol"]
    a = lo.orth_ao(mol, "lowdin")
    obdm_up = OBDMAccumulator(mol=mol, orb_coeff=a, spin=0)
    obdm_down = OBDMAccumulator(mol=mol, orb_coeff=a, spin=1)
    with h5py.File(hdf_opt, "r") as hdf_in:
        if f"wf" in hdf_in.keys():
            print("reading in wave function")
            grp = hdf_in[f"wf"]
            for k in grp.keys():
                sys["wf"].parameters[k] = np.array(grp[k])

    configs = pyqmc.initial_guess(sys["mol"], 1000)
    pyqmc.vmc(
        sys["wf"],
        configs,
        nsteps=500,
        hdf_file=hdf_vmc,
        accumulators={
            "obdm_up": obdm_up,
            "obdm_down": obdm_down
        },
    )

    with h5py.File(hdf_vmc, "r") as vmc_hdf:
        obdm_up = np.mean(np.array(vmc_hdf["obdm_upvalue"]), axis=0)
        obdm_down = np.mean(np.array(vmc_hdf["obdm_downvalue"]), axis=0)
    basis_up = gen_basis(mol, sys["mf"], obdm_up)
    basis_down = gen_basis(mol, sys["mf"], obdm_down)
    obdm_up_acc = OBDMAccumulator(mol=mol, orb_coeff=basis_up, spin=0)
    obdm_down_acc = OBDMAccumulator(mol=mol, orb_coeff=basis_down, spin=1)
    tbdm = TBDMAccumulator(mol, np.array([basis_up, basis_down]), spin=(0, 1))
    acc = {
        "energy": EnergyAccumulator(mol),
        "obdm_up": obdm_up_acc,
        "obdm_down": obdm_down_acc,
        "tbdm": tbdm,
    }

    configs = pyqmc.initial_guess(sys["mol"], 1000)
    pyqmc.vmc(sys["wf"],
              configs,
              nsteps=500,
              hdf_file=hdf_final,
              accumulators=acc)
Example #3
0
def test():

    mol = gto.M(atom="Li 0. 0. 0.; Li 0. 0. 1.5",
                basis="sto-3g",
                unit="bohr",
                verbose=0)
    mf = scf.RHF(mol).run()

    # Lowdin orthogonalized AO basis.
    lowdin = lo.orth_ao(mol, "lowdin")

    # MOs in the Lowdin basis.
    mo = solve(lowdin, mf.mo_coeff)

    # make AO to localized orbital coefficients.
    mfobdm = mf.make_rdm1(mo, mf.mo_occ)

    ### Test OBDM calculation.
    nconf = 500
    nsteps = 400
    warmup = 15
    wf = Slater(mol, mf)
    configs = initial_guess(mol, nconf)
    obdm_dict = dict(mol=mol, orb_coeff=lowdin, nsweeps=5, warmup=15)
    obdm = OBDMAccumulator(**obdm_dict)
    obdm_up = OBDMAccumulator(**obdm_dict, spin=0)
    obdm_down = OBDMAccumulator(**obdm_dict, spin=1)

    df, coords = vmc(
        wf,
        configs,
        nsteps=nsteps,
        accumulators={
            "obdm": obdm,
            "obdm_up": obdm_up,
            "obdm_down": obdm_down
        },
    )
    obdm_est = {}
    for k in ["obdm", "obdm_up", "obdm_down"]:
        avg_norm = np.mean(df[k + "norm"][warmup:], axis=0)
        avg_obdm = np.mean(df[k + "value"][warmup:], axis=0)
        obdm_est[k] = normalize_obdm(avg_obdm, avg_norm)

    assert np.mean(
        np.abs(obdm_est["obdm_up"] + obdm_est["obdm_down"] - mfobdm)) < 0.05
Example #4
0
def test_info_functions_mol(LiH_sto3g_rhf):
    mol, mf = LiH_sto3g_rhf
    wf, to_opt = pyq.generate_wf(mol, mf)
    accumulators = {
        "pgrad": pyq.gradient_generator(mol, wf, to_opt),
        "obdm": OBDMAccumulator(mol, orb_coeff=mf.mo_coeff),
        "tbdm_updown": TBDMAccumulator(mol, np.asarray([mf.mo_coeff] * 2), (0, 1)),
    }
    info_functions(mol, wf, accumulators)
Example #5
0
def test_pbc(li_cubic_ccecp):
    from pyqmc import supercell
    import scipy

    mol, mf = li_cubic_ccecp

    # S = np.ones((3, 3)) - np.eye(3)
    S = np.identity(3)
    mol = supercell.get_supercell(mol, S)
    kpts = supercell.get_supercell_kpts(mol)[:2]
    kdiffs = mf.kpts[np.newaxis] - kpts[:, np.newaxis]
    kinds = np.nonzero(np.linalg.norm(kdiffs, axis=-1) < 1e-12)[1]

    # Lowdin orthogonalized AO basis.
    # lowdin = lo.orth_ao(mol, "lowdin")
    loiao = lo.iao.iao(mol.original_cell, mf.mo_coeff, kpts=kpts)
    occs = [mf.mo_occ[k] for k in kinds]
    coefs = [mf.mo_coeff[k] for k in kinds]
    ovlp = mf.get_ovlp()[kinds]
    lowdin = [lo.vec_lowdin(l, o) for l, o in zip(loiao, ovlp)]
    lreps = [np.linalg.multi_dot([l.T, o, c]) for l, o, c in zip(lowdin, ovlp, coefs)]

    # make AO to localized orbital coefficients.
    mfobdm = [np.einsum("ij,j,kj->ik", l.conj(), o, l) for l, o in zip(lreps, occs)]

    ### Test OBDM calculation.
    nconf = 500
    nsteps = 100
    warmup = 6
    wf = Slater(mol, mf)
    configs = initial_guess(mol, nconf)
    obdm_dict = dict(mol=mol, orb_coeff=lowdin, kpts=kpts, nsweeps=4, warmup=10)
    obdm = OBDMAccumulator(**obdm_dict)

    df, coords = vmc(
        wf,
        configs,
        nsteps=nsteps,
        accumulators={"obdm": obdm},  # , "obdm_up": obdm_up, "obdm_down": obdm_down},
        verbose=True,
    )

    obdm_est = {}
    for k in ["obdm"]:  # , "obdm_up", "obdm_down"]:
        avg_norm = np.mean(df[k + "norm"][warmup:], axis=0)
        avg_obdm = np.mean(df[k + "value"][warmup:], axis=0)
        obdm_est[k] = normalize_obdm(avg_obdm, avg_norm)

    mfobdm = scipy.linalg.block_diag(*mfobdm)

    mae = np.mean(np.abs(obdm_est["obdm"] - mfobdm))
    assert mae < 0.05, f"mae {mae}"
Example #6
0
def test_info_functions_pbc(H_pbc_sto3g_krks):
    from pyqmc.supercell import get_supercell

    mol, mf = H_pbc_sto3g_krks
    kinds = [0, 1]
    dm_orbs = [mf.mo_coeff[i][:, :2] for i in kinds]
    wf, to_opt = pyq.generate_wf(mol, mf)
    accumulators = {
        "pgrad": pyq.gradient_generator(mol, wf, to_opt, ewald_gmax=10),
        "obdm": OBDMAccumulator(mol, dm_orbs, kpts=mf.kpts[kinds]),
        "Sq": SqAccumulator(mol.lattice_vectors()),
    }
    info_functions(mol, wf, accumulators)
Example #7
0
def test_info_functions_mol():
    from pyscf import gto, scf
    from pyqmc.tbdm import TBDMAccumulator

    mol = gto.Mole()
    mol.atom = """He 0.00 0.00 0.00 """
    mol.basis = "ccpvdz"
    mol.build()

    mf = scf.RHF(mol)
    ehf = mf.kernel()

    wf, to_opt = pyqmc.default_sj(mol, mf)
    accumulators = {
        "pgrad": pyqmc.gradient_generator(mol, wf, to_opt),
        "obdm": OBDMAccumulator(mol, orb_coeff=mf.mo_coeff),
        "tbdm_updown": TBDMAccumulator(mol, np.asarray([mf.mo_coeff] * 2),
                                       (0, 1)),
    }
    info_functions(mol, wf, accumulators)
Example #8
0
def test_info_functions_pbc():
    from pyscf.pbc import gto, scf
    from pyqmc.supercell import get_supercell

    mol = gto.Cell(atom="He 0.00 0.00 0.00", basis="ccpvdz", unit="B")
    mol.a = 5.61 * np.eye(3)
    mol.build()

    mf = scf.KRHF(mol, kpts=mol.make_kpts([2, 2, 2])).density_fit()
    ehf = mf.kernel()

    supercell = get_supercell(mol, 2 * np.eye(3))
    kinds = [0, 1]
    dm_orbs = [mf.mo_coeff[i][:, :2] for i in kinds]
    wf, to_opt = pyqmc.default_sj(mol, mf)
    accumulators = {
        "pgrad": pyqmc.gradient_generator(mol, wf, to_opt, ewald_gmax=10),
        "obdm": OBDMAccumulator(mol, dm_orbs, kpts=mf.kpts[kinds]),
        "Sq": pyqmc.accumulators.SqAccumulator(mol.lattice_vectors()),
    }
    info_functions(mol, wf, accumulators)
Example #9
0
def setuph2(r, obdm_steps=5):
    from pyscf import gto, scf, lo
    from pyqmc.accumulators import LinearTransform, EnergyAccumulator
    from pyqmc.obdm import OBDMAccumulator
    from pyqmc.cvmc import DescriptorFromOBDM, PGradDescriptor

    import itertools

    # ccECP from A. Annaberdiyev et al. Journal of Chemical Physics 149, 134108 (2018)
    basis = {
        "H":
        gto.basis.parse("""
    H S
23.843185 0.00411490
10.212443 0.01046440
4.374164 0.02801110
1.873529 0.07588620
0.802465 0.18210620
0.343709 0.34852140
0.147217 0.37823130
0.063055 0.11642410
""")
    }
    """
H S
0.040680 1.00000000
H S
0.139013 1.00000000
H P
0.166430 1.00000000
H P
0.740212 1.00000000
"""
    ecp = {
        "H":
        gto.basis.parse_ecp("""
    H nelec 0
H ul
1 21.24359508259891 1.00000000000000
3 21.24359508259891 21.24359508259891
2 21.77696655044365 -10.85192405303825
""")
    }

    mol = gto.M(atom=f"H 0. 0. 0.; H 0. 0. {r}",
                unit="bohr",
                basis=basis,
                ecp=ecp,
                verbose=5)
    mf = scf.RHF(mol).run()
    mo_occ = mf.mo_coeff[:, mf.mo_occ > 0]
    a = lo.iao.iao(mol, mo_occ)
    a = lo.vec_lowdin(a, mf.get_ovlp())

    obdm_up = OBDMAccumulator(mol=mol, orb_coeff=a, nstep=obdm_steps, spin=0)
    obdm_down = OBDMAccumulator(mol=mol, orb_coeff=a, nstep=obdm_steps, spin=1)

    wf = pyqmc.slater_jastrow(mol, mf)

    freeze = {}
    for k in wf.parameters:
        freeze[k] = np.zeros(wf.parameters[k].shape, dtype='bool')
    print(freeze.keys())
    print(wf.parameters['wf1mo_coeff_alpha'])
    #this freezing allows us to easily go between bonding and
    # AFM configurations.
    freeze['wf1mo_coeff_alpha'][0, 0] = True
    freeze['wf1mo_coeff_beta'][1, 0] = True

    descriptors = {
        "t": [[(1.0, (0, 1)), (1.0, (1, 0))], [(1.0, (0, 1)), (1.0, (1, 0))]],
        "trace": [[(1.0, (0, 0)), (1.0, (1, 1))], [(1.0, (0, 0)),
                                                   (1.0, (1, 1))]],
    }
    for i in [0, 1]:
        descriptors[f"nup{i}"] = [[(1.0, (i, i))], []]
        descriptors[f"ndown{i}"] = [[], [(1.0, (i, i))]]

    acc = PGradDescriptor(
        EnergyAccumulator(mol),
        LinearTransform(wf.parameters, freeze=freeze),
        [obdm_up, obdm_down],
        DescriptorFromOBDM(descriptors, norm=2.0),
    )

    return {
        "wf": wf,
        "acc": acc,
        "mol": mol,
        "mf": mf,
        "descriptors": descriptors
    }
Example #10
0
def test(atom="He", total_spin=0, total_charge=0, scf_basis="sto-3g"):
    mol = gto.M(
        atom="%s 0. 0. 0.; %s 0. 0. 1.5" % (atom, atom),
        basis=scf_basis,
        unit="bohr",
        verbose=4,
        spin=total_spin,
        charge=total_charge,
    )
    mf = scf.UHF(mol).run()
    # Intrinsic Atomic Orbitals
    iaos = make_separate_spin_iaos(
        mol, mf, np.array([i for i in range(mol.natm)]), iao_basis="minao"
    )
    # iaos=make_combined_spin_iaos(mol,mf,np.array([i for i in range(mol.natm)]),iao_basis='minao')
    # MOs in the IAO basis
    mo = reps_combined_spin_iaos(
        iaos,
        mf,
        np.einsum("i,j->ji", np.arange(mf.mo_coeff[0].shape[1]), np.array([1, 1])),
    )
    # Mean-field obdm in IAO basis
    mfobdm = mf.make_rdm1(mo, mf.mo_occ)
    # Mean-field tbdm in IAO basis
    mftbdm = singledet_tbdm(mf, mfobdm)

    ### Test TBDM calculation.
    # VMC params
    nconf = 500
    n_vmc_steps = 400
    vmc_tstep = 0.3
    vmc_warmup = 30
    # TBDM params
    tbdm_sweeps = 4
    tbdm_tstep = 0.5

    wf = PySCFSlater(mol, mf)  # Single-Slater (no jastrow) wf
    configs = initial_guess(mol, nconf)
    energy = EnergyAccumulator(mol)
    obdm_up = OBDMAccumulator(mol=mol, orb_coeff=iaos[0], nsweeps=tbdm_sweeps, spin=0)
    obdm_down = OBDMAccumulator(mol=mol, orb_coeff=iaos[1], nsweeps=tbdm_sweeps, spin=1)
    tbdm_upup = TBDMAccumulator(
        mol=mol, orb_coeff=iaos, nsweeps=tbdm_sweeps, tstep=tbdm_tstep, spin=(0, 0)
    )
    tbdm_updown = TBDMAccumulator(
        mol=mol, orb_coeff=iaos, nsweeps=tbdm_sweeps, tstep=tbdm_tstep, spin=(0, 1)
    )
    tbdm_downup = TBDMAccumulator(
        mol=mol, orb_coeff=iaos, nsweeps=tbdm_sweeps, tstep=tbdm_tstep, spin=(1, 0)
    )
    tbdm_downdown = TBDMAccumulator(
        mol=mol, orb_coeff=iaos, nsweeps=tbdm_sweeps, tstep=tbdm_tstep, spin=(1, 1)
    )

    print("VMC...")
    df, coords = vmc(
        wf,
        configs,
        nsteps=n_vmc_steps,
        tstep=vmc_tstep,
        accumulators={
            "energy": energy,
            "obdm_up": obdm_up,
            "obdm_down": obdm_down,
            "tbdm_upup": tbdm_upup,
            "tbdm_updown": tbdm_updown,
            "tbdm_downup": tbdm_downup,
            "tbdm_downdown": tbdm_downdown,
        },
        verbose=True,
    )

    # Compares obdm from QMC and MF
    obdm_est = {}
    for k in ["obdm_up", "obdm_down"]:
        avg_norm = np.mean(df[k + "norm"][vmc_warmup:], axis=0)
        avg_obdm = np.mean(df[k + "value"][vmc_warmup:], axis=0)
        obdm_est[k] = normalize_obdm(avg_obdm, avg_norm)
    qmcobdm = np.array([obdm_est["obdm_up"], obdm_est["obdm_down"]])
    print("\nComparing QMC and MF obdm:")
    for s in [0, 1]:
        # print('QMC obdm[%d]:\n'%s,qmcobdm[s])
        # print('MF obdm[%d]:\n'%s,mfobdm[s])
        print("diff[%d]:\n" % s, qmcobdm[s] - mfobdm[s])

    # Compares tbdm from QMC and MF
    avg_norm = {}
    avg_tbdm = {}
    tbdm_est = {}
    for t in ["tbdm_upup", "tbdm_updown", "tbdm_downup", "tbdm_downdown"]:
        for k in df.keys():
            if k.startswith(t + "norm_"):
                avg_norm[k.split("_")[-1]] = np.mean(df[k][vmc_warmup:], axis=0)
            if k.startswith(t + "value"):
                avg_tbdm[k.split("_")[-1]] = np.mean(df[k][vmc_warmup:], axis=0)
    for k in avg_tbdm:
        tbdm_est[k] = normalize_tbdm(
            avg_tbdm[k].reshape(2, 2, 2, 2), avg_norm["a"], avg_norm["b"]
        )
    qmctbdm = np.array(
        [
            [tbdm_est["upupvalue"], tbdm_est["updownvalue"]],
            [tbdm_est["downupvalue"], tbdm_est["downdownvalue"]],
        ]
    )
    print("\nComparing QMC and MF tbdm:")
    for sa, sb in [[0, 0], [0, 1], [1, 0], [1, 1]]:
        # print('QMC tbdm[%d,%d]:\n'%(sa,sb),qmctbdm[sa,sb])
        # print('MF tbdm[%d,%d]:\n'%(sa,sb),mftbdm[sa,sb])
        diff = qmctbdm[sa, sb] - mftbdm[sa, sb]
        print("diff[%d,%d]:\n" % (sa, sb), diff)
        assert np.max(np.abs(diff)) < 0.05
Example #11
0
def test_pbc():
    from pyscf.pbc import gto, scf
    from pyqmc import PySCFSlaterUHF, PySCFSlaterPBC
    from pyqmc import slaterpbc
    import scipy

    lvecs = (np.ones((3, 3)) - np.eye(3)) * 2.0
    mol = gto.M(
        atom="H 0. 0. -{0}; H 0. 0. {0}".format(0.7),
        basis="sto-3g",
        unit="bohr",
        verbose=0,
        a=lvecs,
    )
    mf = scf.KRHF(mol, kpts=mol.make_kpts((2, 2, 2)))
    mf = mf.run()

    S = np.ones((3, 3)) - 2 * np.eye(3)
    mol = slaterpbc.get_supercell(mol, S)
    kpts = slaterpbc.get_supercell_kpts(mol)[:2]
    kdiffs = mf.kpts[np.newaxis] - kpts[:, np.newaxis]
    kinds = np.nonzero(np.linalg.norm(kdiffs, axis=-1) < 1e-12)[1]

    # Lowdin orthogonalized AO basis.
    # lowdin = lo.orth_ao(mol, "lowdin")
    loiao = lo.iao.iao(mol.original_cell, mf.mo_coeff, kpts=kpts)
    occs = [mf.mo_occ[k] for k in kinds]
    coefs = [mf.mo_coeff[k] for k in kinds]
    ovlp = mf.get_ovlp()[kinds]
    lowdin = [lo.vec_lowdin(l, o) for l, o in zip(loiao, ovlp)]
    lreps = [np.linalg.multi_dot([l.T, o, c]) for l, o, c in zip(lowdin, ovlp, coefs)]

    # make AO to localized orbital coefficients.
    mfobdm = [np.einsum("ij,j,kj->ik", l.conj(), o, l) for l, o in zip(lreps, occs)]

    ### Test OBDM calculation.
    nconf = 800
    nsteps = 50
    warmup = 6
    wf = PySCFSlaterPBC(mol, mf)
    configs = initial_guess(mol, nconf)
    obdm_dict = dict(mol=mol, orb_coeff=lowdin, kpts=kpts, nsweeps=4, warmup=10)
    obdm = OBDMAccumulator(**obdm_dict)
    obdm_up = OBDMAccumulator(**obdm_dict, spin=0)
    obdm_down = OBDMAccumulator(**obdm_dict, spin=1)

    df, coords = vmc(
        wf,
        configs,
        nsteps=nsteps,
        accumulators={"obdm": obdm, "obdm_up": obdm_up, "obdm_down": obdm_down},
        verbose=True,
    )
    df = DataFrame(df)

    obdm_est = {}
    for k in ["obdm", "obdm_up", "obdm_down"]:
        avg_norm = np.array(df.loc[warmup:, k + "norm"].values.tolist()).mean(axis=0)
        avg_obdm = np.array(df.loc[warmup:, k + "value"].values.tolist()).mean(axis=0)
        obdm_est[k] = normalize_obdm(avg_obdm, avg_norm)

    print("Average OBDM(orb,orb)", obdm_est["obdm"].round(3))
    mfobdm = scipy.linalg.block_diag(*mfobdm)
    print("mf obdm", mfobdm.round(3))
    max_abs_err = np.max(np.abs(obdm_est["obdm"] - mfobdm))
    assert max_abs_err < 0.05, "max abs err {0}".format(max_abs_err)
    print(obdm_est["obdm_up"].diagonal().round(3))
    print(obdm_est["obdm_down"].diagonal().round(3))
    mae = np.mean(np.abs(obdm_est["obdm_up"] + obdm_est["obdm_down"] - mfobdm))
    maup = np.mean(np.abs(obdm_est["obdm_up"]))
    madn = np.mean(np.abs(obdm_est["obdm_down"]))
    mamf = np.mean(np.abs(mfobdm))
    assert mae < 0.05, "mae {0}\n maup {1}\n madn {2}\n mamf {3}".format(
        mae, maup, madn, mamf
    )