예제 #1
0
def test_constraints(H2_ccecp_casci_s0):
    mol, mf, mc = H2_ccecp_casci_s0

    wf, to_opt = pyq.generate_wf(mol, mf, mc=mc)

    old_parms = copy.deepcopy(wf.parameters)
    lt = LinearTransform(wf.parameters, to_opt)

    # Test serialize parameters
    x0 = lt.serialize_parameters(wf.parameters)
    x0 += np.random.normal(size=x0.shape)
    for k, it in lt.deserialize(wf, x0).items():
        assert wf.parameters[k].shape == it.shape
        wf.parameters[k] = it

    # to_opt is supposed to be false for both of these.
    assert wf.parameters["wf1det_coeff"][0] == old_parms["wf1det_coeff"][0]
    assert np.sum(wf.parameters["wf2bcoeff"][0] -
                  old_parms["wf2bcoeff"][0]) == 0
    # While this one is supposed to change.
    assert np.sum(wf.parameters["wf2bcoeff"][1] -
                  old_parms["wf2bcoeff"][1]) != 0

    # Test serialize gradients
    configs = pyq.initial_guess(mol, 10)
    wf.recompute(configs)
    pgrad = wf.pgradient()
    pgrad_serial = lt.serialize_gradients(pgrad)

    # Pgrad should be walkers, configs
    assert pgrad_serial.shape[1] == x0.shape[0]
예제 #2
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)
예제 #3
0
def run_optimization_best_practice_2states(**kwargs):
    """
    First optimize the ground state and then optimize the excited
    states while fixing the 
    """

    mol, mf, mc = H2_casci()
    import copy
    mf.output = None
    mol.output = None
    mc.output = None
    mc.stdout = None
    mol.stdout = None
    mc.stdout = None
    nstates = 2
    mcs = [copy.copy(mc) for i in range(nstates)]
    for i in range(nstates):
        mcs[i].ci = mc.ci[i]

    wfs = []
    to_opts = []
    for i in range(nstates):
        wf, to_opt = pyq.generate_wf(
            mol, mf, mc=mcs[i], slater_kws=dict(optimize_determinants=True))
        wfs.append(wf)
        to_opts.append(to_opt)
    configs = pyq.initial_guess(mol, 1000)

    pgrad1 = pyq.gradient_generator(mol, wfs[0], to_opt=to_opts[0])
    wfs[0], _ = pyq.line_minimization(wfs[0],
                                      configs,
                                      pgrad1,
                                      verbose=True,
                                      max_iterations=10)

    for k in to_opts[0]:
        to_opts[0][k] = np.zeros_like(to_opts[0][k])
    to_opts[0]['wf1det_coeff'][0] = True  #Bug workaround for linear transform
    for to_opt in to_opts[1:]:
        to_opt['wf1det_coeff'] = np.ones_like(to_opt['wf1det_coeff'])

    transforms = [
        pyqmc.accumulators.LinearTransform(wf.parameters, to_opt)
        for wf, to_opt in zip(wfs, to_opts)
    ]
    for wf in wfs[1:]:
        for k in wf.parameters.keys():
            if 'wf2' in k:
                wf.parameters[k] = wfs[0].parameters[k].copy()
    _, configs = pyq.vmc(wfs[0], configs)
    energy = pyq.EnergyAccumulator(mol)
    return optimize(wfs, configs, energy, transforms, **kwargs)
예제 #4
0
def test_transform(LiH_sto3g_rhf):
    """Tests that the shapes are ok"""
    mol, mf = LiH_sto3g_rhf
    wf, to_opt = pyq.generate_wf(mol, mf)
    transform = LinearTransform(wf.parameters)
    x = transform.serialize_parameters(wf.parameters)
    nconfig = 10
    configs = pyq.initial_guess(mol, nconfig)
    wf.recompute(configs)
    pgrad = wf.pgradient()
    gradtrans = transform.serialize_gradients(pgrad)
    assert gradtrans.shape[1] == len(x)
    assert gradtrans.shape[0] == nconfig
예제 #5
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)
예제 #6
0
def test_linemin(H2_ccecp_uhf):
    """Optimize a Slater-Jastrow wave function and check that it's better than Hartree-Fock"""
    mol, mf = H2_ccecp_uhf

    wf, to_opt = generate_wf(mol, mf)
    nconf = 100
    wf, dfgrad = line_minimization(
        wf, initial_guess(mol, nconf), gradient_generator(mol, wf, to_opt)
    )

    dfgrad = pd.DataFrame(dfgrad)
    mfen = mf.energy_tot()
    enfinal = dfgrad["energy"].values[-1]
    enfinal_err = dfgrad["energy_error"].values[-1]
    assert mfen > enfinal
예제 #7
0
def test_dmc_restarts(H_pbc_sto3g_krks, nconf=10):
    """For PBCs, check to make sure there are no
    errors on restart."""
    mol, mf = H_pbc_sto3g_krks
    nconf = 10
    fname = "test_dmc_restart_" + str(uuid.uuid4())

    configs = pyq.initial_guess(mol, nconf)
    wf, _ = pyq.generate_wf(mol, mf, jastrow_kws=dict(na=0, nb=0))
    enacc = pyq.EnergyAccumulator(mol)
    pyq.rundmc(wf,
               configs,
               nsteps=20,
               hdf_file=fname,
               accumulators={"energy": enacc})
    pyq.rundmc(wf,
               configs,
               nsteps=20,
               hdf_file=fname,
               accumulators={"energy": enacc})
    os.remove(fname)
예제 #8
0
def test():
    """ Ensure that DMC obtains the exact result for a hydrogen atom """
    from pyscf import gto, scf
    from pyqmc.dmc import limdrift
    import pandas as pd

    mol = gto.M(atom="H 0. 0. 0.", basis="sto-3g", unit="bohr", spin=1)
    mf = scf.UHF(mol).run()
    nconf = 1000
    configs = pyq.initial_guess(mol, nconf)
    wf, _ = pyq.generate_wf(mol, mf, jastrow_kws=dict(na=0, nb=0))
    enacc = pyq.EnergyAccumulator(mol)

    warmup = 200
    branchtime = 5
    dfdmc, configs_, weights_ = pyq.rundmc(
        wf,
        configs,
        nsteps=4000 + warmup * branchtime,
        branchtime=branchtime,
        accumulators={"energy": enacc},
        ekey=("energy", "total"),
        tstep=0.01,
        verbose=True,
    )

    dfdmc = pd.DataFrame(dfdmc)
    dfdmc.sort_values("step", inplace=True)

    dfprod = dfdmc[dfdmc.step >= warmup]

    rb_summary = reblock.reblock_summary(dfprod[["energytotal", "energyei"]],
                                         20,
                                         weights=dfprod["weight"])
    energy, err = [
        rb_summary[v]["energytotal"] for v in ("mean", "standard error")
    ]
    assert (np.abs(energy + 0.5) <
            5 * err), "energy not within {0} of -0.5: energy {1}".format(
                5 * err, np.mean(energy))
예제 #9
0
def test_complex_linemin(H2_ccecp_rhf, optfile="linemin.hdf5"):
    """Test linemin for the case of complex orbital coefficients.
    We check whether it completes successfully and whether the energy has decreased.
    """
    mol, mf = H2_ccecp_rhf
    mf = copy.copy(mf)
    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 = pyq.generate_wf(mol, mf, slater_kws=slater_kws)

    configs = pyq.initial_guess(mol, 100)
    acc = pyq.gradient_generator(mol, wf, to_opt)
    pyq.line_minimization(
        wf, configs, acc, verbose=True, hdf_file=optfile, max_iterations=5
    )
    assert os.path.isfile(optfile)
    with h5py.File(optfile, "r") as f:
        en = f["energy"][()]
    assert en[0] > en[-1]
    os.remove(optfile)