Ejemplo n.º 1
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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
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
Ejemplo n.º 5
0
def test_overlap_derivative(H2_ccecp_uhf, epsilon=1e-8):
    mol, mf = H2_ccecp_uhf
    mf = copy.copy(mf)

    wf0 = slater.Slater(mol, mf)
    mf.mo_coeff[0][:, 0] = np.mean(mf.mo_coeff[0][:, :2], axis=1)
    wf1, to_opt = wftools.generate_slater(mol, mf, optimize_orbitals=True)

    pgrad = pyq.gradient_generator(mol, wf1, to_opt)
    configs = pyq.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])
        assert np.all(error[k] < epsilon)
Ejemplo n.º 6
0
def test_transform_wf_change(H2_casci):
    mol, mf, mc = H2_casci
    mc = copy.copy(mc)
    mc.ci = mc.ci[0]
    wf, to_opt = pyq.generate_slater(mol,
                                     mf,
                                     mc=mc,
                                     optimize_determinants=True)
    pgrad = pyq.gradient_generator(mol, wf, to_opt)
    parameters = pgrad.transform.serialize_parameters(wf.parameters)
    deserialize = pgrad.transform.deserialize(wf, parameters)

    wf.parameters['det_coeff'] *= 100
    parameters100 = pgrad.transform.serialize_parameters(wf.parameters)
    print("reserialize100", parameters100)
    deserialize100 = pgrad.transform.deserialize(wf, parameters100)
    print(deserialize100['det_coeff'])
    print(deserialize['det_coeff'])
    assert abs(deserialize100['det_coeff'][0] -
               100 * deserialize['det_coeff'][0]) < 1e-10
Ejemplo n.º 7
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)