Example #1
0
def OPTIMIZE(
    dft_checkfile,
    output,
    anchors=None,
    nconfig=1000,
    ci_checkfile=None,
    start_from=None,
    S=None,
    client=None,
    npartitions=None,
    jastrow_kws=None,
    slater_kws=None,
    linemin_kws=None,
):
    if linemin_kws is None:
        linemin_kws = {}

    target_root = 0
    if ci_checkfile is None:
        mol, mf = pyqmc.recover_pyscf(dft_checkfile)
        mc = None
    else:
        mol, mf, mc = pyqmc.recover_pyscf(dft_checkfile,
                                          ci_checkfile=ci_checkfile)
        mc.ci = mc.ci[target_root]

    if S is not None:
        mol = pyqmc.get_supercell(mol, np.asarray(S))

    wf, to_opt = pyqmc.generate_wf(mol,
                                   mf,
                                   mc=mc,
                                   jastrow_kws=jastrow_kws,
                                   slater_kws=slater_kws)
    if start_from is not None:
        pyqmc.read_wf(wf, start_from)

    configs = pyqmc.initial_guess(mol, nconfig)
    acc = pyqmc.gradient_generator(mol, wf, to_opt)
    if anchors is None:
        pyqmc.line_minimization(wf,
                                configs,
                                acc,
                                verbose=True,
                                hdf_file=output,
                                client=client,
                                npartitions=npartitions,
                                **linemin_kws)
    else:
        wfs = [pyqmc.read_wf(copy.deepcopy(wf), a) for a in anchors]
        wfs.append(wf)
        pyqmc.optimize_orthogonal(
            wfs,
            configs,
            acc,
            # verbose=True,
            hdf_file=output,
            client=client,
            npartitions=npartitions,
            **linemin_kws)
Example #2
0
def optimize_excited(mc_anchors, mc_calc, nconfig = 1000, **kwargs):
    acc = pyqmc.gradient_generator(mc_calc['mol'], mc_calc['wf'], to_opt=mc_calc['to_opt'])
    wfs = [x['wf'] for x in mc_anchors]
    wfs.append(mc_calc['wf'])
    configs = pyqmc.initial_guess(mc_calc['mol'], nconfig)

    pyqmc.optimize_orthogonal.optimize_orthogonal(wfs,configs, acc, **kwargs)
Example #3
0
def OPTIMIZE(
    dft_checkfile,
    output,
    nconfig=1000,
    start_from=None,
    S=None,
    client=None,
    npartitions=None,
    jastrow_kws=None,
    slater_kws=None,
    linemin_kws=None,
):
    if linemin_kws is None:
        linemin_kws = {}
    mol, mf = pyqmc.recover_pyscf(dft_checkfile)
    if S is not None:
        mol = pyqmc.get_supercell(mol, np.asarray(S))

    wf, to_opt = pyqmc.generate_wf(mol,
                                   mf,
                                   jastrow_kws=jastrow_kws,
                                   slater_kws=slater_kws)
    if start_from is not None:
        pyqmc.read_wf(wf, start_from)

    configs = pyqmc.initial_guess(mol, nconfig)
    acc = pyqmc.gradient_generator(mol, wf, to_opt)
    pyqmc.line_minimization(wf,
                            configs,
                            acc,
                            verbose=True,
                            hdf_file=output,
                            client=client,
                            npartitions=npartitions,
                            **linemin_kws)
Example #4
0
def pyqmc_from_hdf(chkfile):
    """ Loads pyqmc objects from a pyscf checkfile """
    mol = lib.chkfile.load_mol(chkfile)
    mol.output = None
    mol.stdout = None

    mf = scf.RHF(mol)
    mf.__dict__.update(scf.chkfile.load(chkfile, "scf"))
    with h5py.File(chkfile, "r") as f:
        mc = mcscf.CASCI(mf,
                         ncas=int(f["mc/ncas"][...]),
                         nelecas=f["mc/nelecas"][...])
        mc.ci = f["mc/ci"][...]

    wf, to_opt, freeze = pyqmc.default_msj(mol, mf, mc)

    freeze["wf1det_coeff"][...] = False
    pgrad = pyqmc.gradient_generator(mol, wf, to_opt, freeze)

    return {
        "mol": mol,
        "mf": mf,
        "to_opt": to_opt,
        "freeze": freeze,
        "wf": wf,
        "pgrad": pgrad,
    }
Example #5
0
 def setup(self):
     self.mol = pyscf.gto.M(atom="O 0 0 0; H 0 -2.757 2.587; H 0 2.757 2.587", basis=f'ccecpccpvdz', ecp='ccecp')
     self.mf = pyscf.scf.RHF(self.mol).run()
     self.configs = pyqmc.initial_guess(self.mol, 500)
     self.slater, self.slater_to_opt =  pyqmc.default_slater(self.mol, self.mf, optimize_orbitals=True)
     self.jastrow, self.jastrow_to_opt =  pyqmc.default_jastrow(self.mol)
     self.pgrad_acc = pyqmc.gradient_generator(self.mol, self.slater, self.slater_to_opt)
     self.slater.recompute(self.configs)
     self.jastrow.recompute(self.configs)
Example #6
0
def test():
    """ Optimize a Helium atom's wave function and check that it's 
    better than Hartree-Fock"""

    mol = gto.M(atom="He 0. 0. 0.", basis="bfd_vdz", ecp="bfd", unit="bohr")
    mf = scf.RHF(mol).run()
    wf = slater_jastrow(mol, mf)
    nconf = 500
    wf, dfgrad, dfline = line_minimization(wf, initial_guess(mol, nconf),
                                           gradient_generator(mol, wf))
    dfgrad = pd.DataFrame(dfgrad)
    mfen = mf.energy_tot()
    enfinal = dfgrad["en"].values[-1]
    enfinal_err = dfgrad["en_err"].values[-1]
    assert mfen > enfinal
Example #7
0
def test():
    print("running scf", flush=True)
    mol = gto.M(atom="H 0. 0. 0.; H 0. 0. 1.6", basis="ccpvdz", unit="bohr")
    mf = scf.UHF(mol).run()
    mf.stdout = None

    print("setting up wfs", flush=True)
    wf0 = pyqmc.Slater(mol, mf)
    mf.mo_coeff[0][:, 0] = np.mean(mf.mo_coeff[0][:, :2], axis=1)
    wf1, to_opt = pyqmc.default_slater(mol, mf, optimize_orbitals=True)

    pgrad = pyqmc.gradient_generator(mol, wf1, to_opt)
    configs = pyqmc.initial_guess(mol, 2000)

    wf0.recompute(configs)
    wf1.recompute(configs)
    wfs = [wf0, wf1]

    print("warming up", flush=True)
    block_avg, configs = oo.sample_overlap_worker(wfs,
                                                  configs,
                                                  pgrad,
                                                  20,
                                                  tstep=1.5)

    print("computing gradients and normalization", flush=True)
    data = get_data(wfs, configs, pgrad)
    parameters = pgrad.transform.serialize_parameters(wfs[-1].parameters)
    N = compute_normalization(wfs, [parameters], pgrad.transform, configs)
    print(np.stack([data["N"], N]))

    print("computing numerical gradients", flush=True)
    error = {"N": [], "S": []}
    deltas = [1e-4, 1e-5, 1e-6]
    numgrad = numerical_gradient(wfs, configs, pgrad, deltas)
    for k, ng in numgrad.items():
        pgerr = data[k + "_derivative"].T[:, np.newaxis] - ng
        error[k] = pgerr

    print("computing errors", flush=True)
    for k, er in error.items():
        error[k] = np.amin(er, axis=1)
        print(k)
        print(error[k])
Example #8
0
 def optimize(self, nconfig=1000, **kwargs):
     configs = pyqmc.initial_guess(self.mol, nconfig)
     acc = pyqmc.gradient_generator(self.mol, self.wf, to_opt=self.to_opt)
     if self.client is None:
         pyqmc.line_minimization(self.wf, configs, acc, **kwargs)
     else:
         pyqmc.dasktools.line_minimization(
             self.wf,
             configs,
             acc,
             **kwargs,
             client=self.client,
             lmoptions={"npartitions": self.npartitions},
             vmcoptions={
                 "npartitions": self.npartitions,
                 'nblocks': 5,
                 'nsteps_per_block': 20
             },
         )
Example #9
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 #10
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 #11
0
def test():
    chkfile = "h2.hdf5"
    optfile = "linemin.hdf5"
    run_scf(chkfile)
    mol, mf = pyqmc.recover_pyscf(chkfile)
    noise = (np.random.random(mf.mo_coeff.shape) - 0.5) * 0.2
    mf.mo_coeff = mf.mo_coeff * 1j + noise

    slater_kws = {"optimize_orbitals": True}
    wf, to_opt = pyqmc.generate_wf(mol, mf, slater_kws=slater_kws)

    configs = pyqmc.initial_guess(mol, 100)
    acc = pyqmc.gradient_generator(mol, wf, to_opt)
    pyqmc.line_minimization(wf,
                            configs,
                            acc,
                            verbose=True,
                            hdf_file=optfile,
                            max_iterations=5)

    assert os.path.isfile(optfile)
    os.remove(chkfile)
    os.remove(optfile)
Example #12
0
    wf=pyqmc.slater_jastrow(mol,mf)

    return mol,mf,wf



if __name__=="__main__":
    cluster = LocalCluster(n_workers=ncore, threads_per_worker=1)
    client = Client(cluster)
    mol,mf,wf=generate_wfs()
    from pyqmc.mc import vmc
    from pyqmc.dasktools import distvmc,line_minimization
    from pyqmc.dmc import rundmc
    from pyqmc import EnergyAccumulator
    df,coords=distvmc(wf,pyqmc.initial_guess(mol,nconfig),client=client,nsteps_per=10,nsteps=10)
    line_minimization(wf,coords,pyqmc.gradient_generator(mol,wf,["wf2acoeff", "wf2bcoeff"]),client=client)
    dfdmc, configs, weights = rundmc(
        wf,
        coords,
        nsteps=5000,
        branchtime=5,
        accumulators={"energy": EnergyAccumulator(mol)},
        ekey=("energy", "total"),
        tstep=0.02,
        verbose=True,
        propagate=pyqmc.dasktools.distdmc_propagate,
        client=client,
    )

    dfdmc = pd.DataFrame(dfdmc).to_json("dmc.json")
Example #13
0
    return cell, kmf


if __name__ == "__main__":
    # Run SCF
    cell, kmf = run_scf(nk=2)

    # Set up wf and configs
    nconfig = 100
    S = np.eye(3) * 2  # 2x2x2 supercell
    supercell = get_supercell(cell, S)
    wf, to_opt = pyqmc.default_sj(supercell, kmf)
    configs = pyqmc.initial_guess(supercell, nconfig)

    # Initialize energy accumulator (and Ewald)
    pgrad = pyqmc.gradient_generator(supercell, wf, to_opt=to_opt)

    # Optimize jastrow
    wf, lm_df = pyqmc.line_minimization(wf,
                                        configs,
                                        pgrad,
                                        hdf_file="pbc_he_linemin.hdf",
                                        verbose=True)

    # Run VMC
    df, configs = pyqmc.vmc(
        wf,
        configs,
        nblocks=100,
        accumulators={"energy": pgrad.enacc},
        hdf_file="pbc_he_vmc.hdf",
Example #14
0
            basis="bfd_vtz",
            ecp="bfd")
mf = scf.RHF(mol).run()
# clean_pyscf_objects gets rid of the TextIO objects that can't
# be sent using parsl.
mol, mf = clean_pyscf_objects(mol, mf)

# It's better to load parsl after pyscf has run. Some of the
# executors have timeouts and will kill the job while pyscf is running!
parsl.load(config)
parsl.set_stream_logger(level=logging.WARNING)

# We make a Slater-Jastrow wave function and
# only optimize the Jastrow coefficients.
wf = pyqmc.slater_jastrow(mol, mf)
acc = pyqmc.gradient_generator(mol, wf, ["wf2acoeff", "wf2bcoeff"])

# Generate the initial configurations.
# Here we run VMC for a few steps with no accumulators to equilibrate the
# walkers.
configs = pyqmc.initial_guess(mol, nconf)
df, configs = distvmc(wf,
                      configs,
                      accumulators={},
                      nsteps=10,
                      npartitions=ncore)

# This uses a stochastic reconfiguration step to generate parameter changes along a line,
# then minimizes the energy along that line.
wf, dfgrad, dfline = line_minimization(
    wf,
Example #15
0
if __name__ == "__main__":
    import pyscf
    import pyqmc
    import pandas as pd
    import h5py
    import uuid
    import itertools

    mol = pyscf.gto.M(atom = "He 0. 0. 0.", basis='bfd_vdz', ecp='bfd', unit='bohr')

    mf = pyscf.scf.RHF(mol).run()

    for nconfig, steprange, npts in itertools.product([250, 500, 1000], [0.1, 0.2], [5, 10] ):
        nconfig = nconfig
        configs = pyqmc.initial_guess(mol, nconfig)
        wf = pyqmc.slater_jastrow(mol, mf)
        acc = pyqmc.gradient_generator(mol, wf, ['wf2acoeff','wf2bcoeff'])

        identity = str(uuid.uuid4())
        fname = f"../static/{identity}.hdf5"
        pyqmc.line_minimization(wf, configs, acc, hdf_file = fname, steprange = steprange, npts=npts)

        #These are not saved by line minimization, so we save them here.
        with h5py.File(fname) as f:
            f.attrs['uuid'] = identity
            f.attrs['nconfig'] = nconfig
Example #16
0
    mol = gto.M(
        atom="O 0 0 0; H 0 -2.757 2.587; H 0 2.757 2.587", basis="bfd_vtz", ecp="bfd"
    )
    mf = scf.RHF(mol).run()
    return mol, mf


if __name__ == "__main__":
    cluster = LocalCluster(n_workers=ncore, threads_per_worker=1)
    client = Client(cluster)
    mol, mf = run_scf()
    from pyqmc import vmc, line_minimization, rundmc

    wf, to_opt = pyqmc.default_sj(mol, mf)
    pgrad_acc = pyqmc.gradient_generator(mol, wf, to_opt)
    configs = pyqmc.initial_guess(mol, nconfig)
    line_minimization(
        wf,
        configs,
        pgrad_acc,
        hdf_file="h2o_opt.hdf",
        client=client,
        npartitions=ncore,
        verbose=True,
    )
    df, configs = vmc(
        wf,
        configs,
        hdf_file="h2o_vmc.hdf",
        accumulators={"energy": pgrad_acc.enacc},
Example #17
0
    from dask.distributed import Client, LocalCluster
    r = 1.1

    ncore = 2
    sys = setuph2(r)
    cluster = LocalCluster(n_workers=ncore, threads_per_worker=1)
    client = Client(cluster)

    # Set up calculation
    nconf = 800
    configs = pyqmc.initial_guess(sys["mol"], nconf)

    wf, dfgrad, dfline = line_minimization(
        sys["wf"],
        configs,
        pyqmc.gradient_generator(sys["mol"], sys["wf"]),
        client=client,
        maxiters=5,
    )

    forcing = {}
    obj = {}
    for k in sys["descriptors"]:
        forcing[k] = 0.0
        obj[k] = 0.0

    forcing["t"] = 0.5
    forcing["trace"] = 1.0
    obj["t"] = 0.0
    obj["trace"] = 2.0
Example #18
0
def linear(mc_calc,nconfig=1000,**kwargs):
    configs = pyqmc.initial_guess(mc_calc['mol'], nconfig)
    acc = pyqmc.gradient_generator(mc_calc['mol'], mc_calc['wf'], to_opt=mc_calc['to_opt'], freeze=mc_calc['freeze'])
    pyqmc.line_minimization(mc_calc['wf'], configs, acc,  **kwargs)