def build_system(request): mol = psi4.geometry(""" O H 1 1.00 H 1 1.00 2 103.1 """) memory = 50000 puream = request.param == "spherical" primary = psi4.core.BasisSet.build(mol, "ORBITAL", "cc-pVDZ", puream=puream) aux = psi4.core.BasisSet.build(mol, "ORBITAL", "cc-pVDZ-jkfit", puream=puream) nbf = primary.nbf() naux = aux.nbf() # construct spaces names = ['C1', 'C2', 'C3', 'C4', 'C5'] sizes = [16, 16, 20, 20, 30] spaces = {names[ind]: psi4.core.Matrix.from_array(np.random.rand(nbf, size)) for ind, size in enumerate(sizes)} space_pairs = [[0, 0], [0, 1], [1, 1], [2, 2], [3, 2], [3, 3], [4, 4]] # space vectors C_vectors = [[spaces[names[left]], spaces[names[right]]] for left, right in space_pairs] # DiskJK psi4.set_options({"SCF_TYPE": "DISK_DF"}) DiskJK = psi4.core.JK.build_JK(primary, aux) DiskJK.initialize() DiskJK.print_header() # symm_JK psi4.set_options({"SCF_TYPE": "MEM_DF"}) MemJK = psi4.core.JK.build_JK(primary, aux) MemJK.initialize() MemJK.print_header() # add C matrices for Cleft, Cright in C_vectors: DiskJK.C_left_add(Cleft) MemJK.C_left_add(Cleft) DiskJK.C_right_add(Cright) MemJK.C_right_add(Cright) # compute DiskJK.compute() MemJK.compute() # get integrals DiskJK_ints = [DiskJK.J(), DiskJK.K()] MemJK_ints = [MemJK.J(), MemJK.K()] return (DiskJK_ints, MemJK_ints)
def dft_bench_systems(): ang = np.array([ [ -1.551007, -0.114520, 0.000000], [ -1.934259, 0.762503, 0.000000], [ -0.599677, 0.040712, 0.000000]]) oldang = ang * 0.52917721067 / 0.52917720859 oldmass = [15.99491461956, 1.00782503207, 1.00782503207] h2o = psi4.core.Molecule.from_arrays(geom=oldang, elez=[8, 1, 1], units='Angstrom', mass=oldmass) h2o_plus = psi4.core.Molecule.from_arrays(geom=oldang, elez=[8, 1, 1], units='Angstrom', mass=oldmass, molecular_charge=1, molecular_multiplicity=2) h2o_dimer = psi4.geometry(""" 0 1 O -1.551007 -0.114520 0.000000 H -1.934259 0.762503 0.000000 H -0.599677 0.040712 0.000000 -- 0 1 O 1.350625 0.111469 0.000000 H 1.680398 -0.373741 -0.758561 H 1.680398 -0.373741 0.758561 no_reorient """) psi4.set_options({ 'dft_radial_points': 200, 'dft_spherical_points': 590, 'guess': 'sad', 'e_convergence': 9, 'd_convergence': 9, }) return {'h2o': h2o, 'h2o_plus': h2o_plus, 'h2o_dimer': h2o_dimer}
def restricted_orbitals(basis, labels, coords, charge=0, spin=0, niter=100, e_thresh=1e-12, d_thresh=1e-9, guess='gwh'): """restricted Hartree-Fock orbitals :param basis: basis set name :type basis: str :param labels: atomic symbols labeling the nuclei :type labels: tuple :param coords: nuclear coordinates in Bohr :type coords: numpy.ndarray :param charge: total molecular charge :type charge: int :param spin: number of unpaired electrons :type spin: int :param niter: maximum number of iterations :type niter: int :param e_thresh: energy convergence threshold :type e_thresh: float :param d_thresh: density convergence threshold :type d_thresh: float :param guess: hartree-fock starting guess :type guess: str :return: orbital coefficients and energies, along with the occupation count :rtype: (numpy.ndarray, numpy.ndarray, int) """ psi4.set_options({'e_convergence': e_thresh, 'd_convergence': d_thresh, 'maxiter': niter, 'guess': guess, 'reference': 'RHF'}) mol = psi4_molecule(labels=labels, coords=coords, charge=charge, spin=spin) wfn = psi4.core.Wavefunction.build(mol, basis) sf, _ = psi4.driver.dft_funcs.build_superfunctional("HF", False) hf = psi4.core.RHF(wfn, sf) hf.compute_energy() return numpy.array(hf.Ca()), numpy.array(hf.epsilon_a()), int(hf.nalpha())
def test_gpudfcc2(): """gpu_dfcc/tests/gpu_dfcc2""" #! aug-cc-pvdz (H2O) Test DF-CCSD(T) vs GPU-DF-CCSD(T) import psi4 H20 = psi4.geometry(""" O 0.000000000000 0.000000000000 -0.068516219310 H 0.000000000000 -0.790689573744 0.543701060724 H 0.000000000000 0.790689573744 0.543701060724 """) psi4.set_memory(32000000000) psi4.set_options({ 'cc_type': 'df', 'basis': 'aug-cc-pvdz', 'freeze_core': 'true', 'e_convergence': 1e-8, 'd_convergence': 1e-8, 'r_convergence': 1e-8, 'scf_type': 'df', 'maxiter': 30}) psi4.set_num_threads(2) en_dfcc = psi4.energy('ccsd(t)') en_gpu_dfcc = psi4.energy('gpu-df-ccsd(t)') assert psi4.compare_values(en_gpu_dfcc, en_dfcc, 8, "CCSD total energy")
def psi4_esp(method, basis, molecule): """ Computes QM electrostatic potential Parameters ---------- method : str QM method basis : str basis set molecule : psi4.Molecule instance Returns ------- np.array QM electrostatic potential. Note ----- Psi4 read grid information from grid.dat file """ import psi4 mol = psi4.geometry(molecule.create_psi4_string_from_molecule()) psi4.set_options({'basis': basis}) e, wfn = psi4.prop(method, properties=['GRID_ESP'], return_wfn=True) psi4.core.clean() return np.loadtxt('grid_esp.dat')
def test_uhf(): """ test for uhf using (H2O)^+ """ print("!!! %s" % os.path.dirname(__file__)) ao_ints, test_scf_param, e_ZZ_repulsion = scf.init(\ os.path.dirname(__file__) + "/test_uhf.yml") eps, C, D, F = scf.scf(ao_ints, test_scf_param, e_ZZ_repulsion) energy = scf.get_SCF_energy(ao_ints['H'], F, D, True) + e_ZZ_repulsion print("energy: %f" % energy) # psi4 setup import psi4 mol = psi4.geometry(""" 1 2 O H 1 1.1 H 1 1.1 2 104 """) mol.update_geometry() bas = psi4.core.BasisSet.build(mol, target=test_scf_param['basis']) mints = psi4.core.MintsHelper(bas) # DENSITY FITTED psi4.set_options({"scf_type": "pk", "reference": "uhf"}) psi4_energy = psi4.energy("SCF/cc-pVDZ", molecule = mol) print("psi4 energy: %f" % psi4_energy) assert(np.allclose(energy, psi4_energy) == True)
def test_mp2(): """ test for energies """ ao_ints, test_scf_param, e_ZZ_repulsion = scf.init(\ os.path.dirname(__file__) + "/test_mp2.yml") eps, C, D, F = scf.scf(ao_ints, test_scf_param, e_ZZ_repulsion) energy = scf.get_SCF_energy(ao_ints['H'], F, D, False) + e_ZZ_repulsion # psi4 setup import psi4 mol = psi4.geometry(""" O H 1 1.1 H 1 1.1 2 104 """) mol.update_geometry() bas = psi4.core.BasisSet.build(mol, target="cc-pVDZ") mints = psi4.core.MintsHelper(bas) # DF-MP2 psi4.set_options({"scf_type": "df"}) psi4.set_options({"MP2_type": "CONV"}) psi4_energy = psi4.energy("MP2/cc-pVDZ", molecule = mol) psi4_energy_MP2 = psi4.get_variable('SCS-MP2 TOTAL ENERGY') test_scf_param.update({"method": "MP2"}) test_scf_param.update({"is_fitted": "True"}) eps, C, D, F = scf.scf(ao_ints, test_scf_param, e_ZZ_repulsion) H = ao_ints['T'] + ao_ints['V'] energy = np.sum((F+H)*D) + e_ZZ_repulsion energy_corr = mp2.get_mp2_energy(\ eps, C, ao_ints['g4'], test_scf_param['nel_alpha']) assert(np.allclose(energy + energy_corr, psi4_energy_MP2) == True)
def test_cfour(): """cfour/sp-rhf-ccsd_t_""" #! single-point CCSD(T)/qz2p on water print(' <<< Translation of ZMAT to Psi4 format to Cfour >>>') psi4.geometry(""" O H 1 R H 1 R 2 A R=0.958 A=104.5 """) psi4.set_options({ 'cfour_CALC_level': 'CCSD(T)', 'cfour_BASIS': 'qz2p', 'cfour_SCF_CONV': 12, 'cfour_CC_CONV': 12, }) psi4.energy('cfour') assert psi4.compare_values(-76.062748460117, psi4.variable('scf total energy'), 6, 'SCF') assert psi4.compare_values(-76.332940127333, psi4.variable('mp2 total energy'), 6, 'MP2') assert psi4.compare_values(-76.338453951890, psi4.variable('ccsd total energy'), 6, 'CCSD') assert psi4.compare_values(-0.275705491773, psi4.variable('ccsd correlation energy'), 6, 'CCSD corl') assert psi4.compare_values(-76.345717549886, psi4.variable('ccsd(t) total energy'), 6, 'CCSD(T)') assert psi4.compare_values(-0.282969089769, psi4.variable('ccsd(t) correlation energy'), 6, 'CCSD(T) corl')
def test_rhf(): """ test for rhf """ ao_ints, test_scf_param, e_ZZ_repulsion = scf.init(\ os.path.dirname(__file__) + "/test_rhf.yml") eps, C, D, F = scf.scf(ao_ints, test_scf_param, e_ZZ_repulsion) energy = scf.get_SCF_energy(ao_ints['H'], F, D, False) + e_ZZ_repulsion # psi4 setup import psi4 mol = psi4.geometry(""" O H 1 1.1 H 1 1.1 2 104 """) mol.update_geometry() bas = psi4.core.BasisSet.build(mol, target="cc-pVDZ") mints = psi4.core.MintsHelper(bas) # DENSITY FITTED psi4.set_options({"scf_type": "df"}) psi4_energy = psi4.energy("SCF/cc-pVDZ", molecule = mol) assert(np.allclose(energy, psi4_energy) == True)
def test_gpu_dfcc(): """gpu_dfcc/tests/gpu_dfcc1""" #! cc-pvdz (H2O)2 Test DF-CCSD vs GPU-DF-CCSD import gpu_dfcc H20 = psi4.geometry(""" O 0.000000000000 0.000000000000 -0.068516219310 H 0.000000000000 -0.790689573744 0.543701060724 H 0.000000000000 0.790689573744 0.543701060724 """) psi4.set_memory(32000000000) psi4.set_options({ 'cc_timings': False, 'num_gpus': 1, 'cc_type': 'df', 'df_basis_cc': 'aug-cc-pvdz-ri', 'df_basis_scf': 'aug-cc-pvdz-jkfit', 'basis': 'aug-cc-pvdz', 'freeze_core': 'true', 'e_convergence': 1e-8, 'd_convergence': 1e-8, 'r_convergence': 1e-8, 'scf_type': 'df', 'maxiter': 30}) psi4.set_num_threads(2) en_dfcc = psi4.energy('ccsd', molecule=H20) en_gpu_dfcc = psi4.energy('gpu-df-ccsd', molecule=H20) assert psi4.compare_values(en_gpu_dfcc, en_dfcc, 8, "CCSD total energy")
def test_dftd3_dft_grad_lr3(): """modified VV10-less B97 functional gradient wB97X-V -> wB97X-D3BJ""" # stored data from finite differences FD_wb97x_d3 = psi4.core.Matrix.from_list([ [ 0.03637802044642, 0.06718963272193, 0.00000000000000], [ 0.04955519892514, -0.06340333481039, 0.00000000000000], [ -0.07009043821383, -0.00834477190196, 0.00000000000000], [ 0.02732425404378, -0.05883094637658, 0.00000000000000], [ -0.02158351760075, 0.03169471018350, 0.05342791683461], [ -0.02158351760075, 0.03169471018350, -0.05342791683461]]) psi4.geometry(""" 0 1 O -1.65542 -0.12330 0.00000 O 1.24621 0.10269 0.00000 H -0.70409 0.03193 0.00000 H -2.03867 0.75372 0.00000 H 1.57599 -0.38252 -0.75856 H 1.57599 -0.38252 0.75856 """) psi4.set_options({ 'scf_type': 'pk', 'basis': 'minix', 'dft_radial_points': 99, 'dft_spherical_points': 302, 'e_convergence': 8, }) analytic = psi4.gradient('wB97X-D3BJ', dertype=1) assert compare_matrices(analytic, FD_wb97x_d3, 5, "wB97X-D3BJ Analytic vs Store")
def test_psi4_cas(): """casscf-sp""" #! CASSCF/6-31G** energy point geom = psi4.geometry(""" O H 1 1.00 H 1 1.00 2 103.1 """) psi4.set_options({ "basis" : '6-31G**', "reference" : 'rhf', "scf_type" : 'pk', "mcscf_algorithm" : 'ah', "qc_module" : 'detci', "nat_orbs" : True}) cisd_energy, cisd_wfn = psi4.energy("CISD", return_wfn=True) assert psi4.compare_values(-76.2198474477531, cisd_energy, 6, 'CISD Energy') psi4.set_options({ "restricted_docc": [1, 0, 0, 0], "active": [3, 0, 1, 2]}) casscf_energy = psi4.energy('casscf', ref_wfn=cisd_wfn) assert psi4.compare_values(-76.073865006902, casscf_energy, 6, 'CASSCF Energy')
def test_restricted_RPA_triplet_c1(): "Build out the full CIS/TDA hamiltonian (A) col by col with the product engine" h2o = psi4.geometry(""" O H 1 0.96 H 1 0.96 2 104.5 symmetry c1 """) psi4.set_options({"scf_type": "pk", 'save_jk': True}) e, wfn = psi4.energy("hf/cc-pvdz", molecule=h2o, return_wfn=True) A_ref, B_ref = build_RHF_AB_C1_triplet(wfn) ni, na, _, _ = A_ref.shape nia = ni * na A_ref = A_ref.reshape((nia, nia)) B_ref = B_ref.reshape((nia, nia)) P_ref = A_ref + B_ref M_ref = A_ref - B_ref # Build engine eng = TDRSCFEngine(wfn, ptype='rpa', triplet=True) # our "guess"" vectors ID = [psi4.core.Matrix.from_array(v.reshape((ni, na))) for v in tuple(np.eye(nia).T)] Px, Mx = eng.compute_products(ID)[:-1] P_test = np.column_stack([x.to_array().flatten() for x in Px]) assert compare_arrays(P_ref, P_test, 8, "RHF (A+B)x C1 products") M_test = np.column_stack([x.to_array().flatten() for x in Mx]) assert compare_arrays(M_ref, M_test, 8, "RHF (A-B)x C1 products")
def test_unrestricted_RPA_C1(): ch2 = psi4.geometry(""" 0 3 c h 1 1.0 h 1 1.0 2 125.0 symmetry c1 """) psi4.set_options({"scf_type": "pk", 'reference': 'UHF', 'save_jk': True}) e, wfn = psi4.energy("hf/cc-pvdz", molecule=ch2, return_wfn=True) A_ref, B_ref = build_UHF_AB_C1(wfn) nI, nA, _, _ = A_ref['IAJB'].shape nIA = nI * nA ni, na, _, _ = A_ref['iajb'].shape nia = ni * na P_ref = {k: A_ref[k] + B_ref[k] for k in A_ref.keys()} M_ref = {k: A_ref[k] - B_ref[k] for k in A_ref.keys()} eng = TDUSCFEngine(wfn, ptype='rpa') X_jb = [psi4.core.Matrix.from_array(v.reshape((ni, na))) for v in tuple(np.eye(nia).T)] zero_jb = [psi4.core.Matrix(ni, na) for x in range(nIA)] X_JB = [psi4.core.Matrix.from_array(v.reshape((nI, nA))) for v in tuple(np.eye(nIA).T)] zero_JB = [psi4.core.Matrix(nI, nA) for x in range(nia)] # Guess Identity: # X_I0 X_0I = X_I0 X_0I # [ I{nOV x nOV} | 0{nOV x nov}] = [ X{KC,JB} | 0{KC, jb}] # [ 0{nov x nOV} | I{nov x nov}] [ 0{kc,JB} | X{kc, jb}] # Products: # [ A+/-B{IA, KC} A+/-B{IA, kc}] [ I{KC, JB} | 0{KC,jb}] = [A+/-B x X_I0] = [ (A+/-B)_IAJB, (A+/-B)_iaJB] # [ A+/-B{ia, KC} A+/-B{ia, kc}] [ O{kc, JB} | X{kc,jb}] [A+/-B x X_0I] = [ (A+/-B)_IAjb, (A+/-B)_iajb] X_I0 = [[x, zero] for x, zero in zip(X_JB, zero_jb)] X_0I = [[zero, x] for zero, x in zip(zero_JB, X_jb)] Px_I0, Mx_I0 = eng.compute_products(X_I0)[:-1] Px_0I, Mx_0I = eng.compute_products(X_0I)[:-1] P_IAJB_test = np.column_stack([x[0].to_array().flatten() for x in Px_I0]) assert compare_arrays(P_ref['IAJB'].reshape(nIA, nIA), P_IAJB_test, 8, "A_IAJB") M_IAJB_test = np.column_stack([x[0].to_array().flatten() for x in Mx_I0]) assert compare_arrays(M_ref['IAJB'].reshape(nIA, nIA), M_IAJB_test, 8, "A_IAJB") P_iaJB_test = np.column_stack([x[1].to_array().flatten() for x in Px_I0]) assert compare_arrays(P_ref['iaJB'].reshape(nia, nIA), P_iaJB_test, 8, "P_iaJB") M_iaJB_test = np.column_stack([x[1].to_array().flatten() for x in Mx_I0]) assert compare_arrays(M_ref['iaJB'].reshape(nia, nIA), M_iaJB_test, 8, "M_iaJB") P_IAjb_test = np.column_stack([x[0].to_array().flatten() for x in Px_0I]) assert compare_arrays(P_ref['IAjb'].reshape(nIA, nia), P_IAjb_test, 8, "P_IAjb") M_IAjb_test = np.column_stack([x[0].to_array().flatten() for x in Mx_0I]) assert compare_arrays(M_ref['IAjb'].reshape(nIA, nia), M_IAjb_test, 8, "M_IAjb") P_iajb_test = np.column_stack([x[1].to_array().flatten() for x in Px_0I]) assert compare_arrays(P_ref['iajb'].reshape(nia, nia), P_iajb_test, 8, "P_iajb") M_iajb_test = np.column_stack([x[1].to_array().flatten() for x in Mx_0I]) assert compare_arrays(M_ref['iajb'].reshape(nia, nia), M_iajb_test, 8, "M_iajb")
def disabled_test_forte(): """aci-10: Perform aci on benzyne""" import forte refscf = -229.20378006852584 refaci = -229.359450812283 refacipt2 = -229.360444943286 mbenzyne = psi4.geometry(""" 0 1 C 0.0000000000 -2.5451795941 0.0000000000 C 0.0000000000 2.5451795941 0.0000000000 C -2.2828001669 -1.3508352528 0.0000000000 C 2.2828001669 -1.3508352528 0.0000000000 C 2.2828001669 1.3508352528 0.0000000000 C -2.2828001669 1.3508352528 0.0000000000 H -4.0782187459 -2.3208602146 0.0000000000 H 4.0782187459 -2.3208602146 0.0000000000 H 4.0782187459 2.3208602146 0.0000000000 H -4.0782187459 2.3208602146 0.0000000000 units bohr """) psi4.set_options({ 'basis': 'DZ', 'df_basis_mp2': 'cc-pvdz-ri', 'reference': 'uhf', 'scf_type': 'pk', 'd_convergence': 10, 'e_convergence': 12, 'guess': 'gwh', }) psi4.set_module_options("FORTE", { 'root_sym': 0, 'frozen_docc': [2,1,0,0,0,0,2,1], 'restricted_docc': [3,2,0,0,0,0,2,3], 'active': [1,0,1,2,1,2,1,0], 'multiplicity': 1, 'aci_nroot': 1, 'job_type': 'aci', 'sigma': 0.001, 'aci_select_type': 'aimed_energy', 'aci_spin_projection': 1, 'aci_enforce_spin_complete': True, 'aci_add_aimed_degenerate': False, 'aci_project_out_spin_contaminants': False, 'diag_algorithm': 'full', 'aci_quiet_mode': True, }) scf = psi4.energy('scf') assert psi4.compare_values(refscf, scf,10,"SCF Energy") psi4.energy('forte') assert psi4.compare_values(refaci, psi4.variable("ACI ENERGY"),10,"ACI energy") assert psi4.compare_values(refacipt2, psi4.variable("ACI+PT2 ENERGY"),8,"ACI+PT2 energy")
def test_dft_bench_interaction(func, expected, basis, dft_bench_systems, request): """functionals interaction energies vs. Q-Chem & Orca""" if func.lower() in psi4.driver.procedures['energy']: mols = dft_bench_systems psi4.set_options({'basis': basis}) psi4_ie = psi4.energy(func, molecule=mols['h2o_dimer'], bsse_type='nocp') assert compare_values(expected, psi4_ie, 4, request.node.name) else: pytest.skip("{0:s} not in Psi4.".format(func))
def test_libefp(): """libefp/qchem-qmefp-sp""" #! EFP on mixed QM (water) and EFP (water + 2 * ammonia) system. #! An EFP-only calc performed first to test vales against q-chem. qmefp = psi4.geometry(""" # QM fragment 0 1 units bohr O1 0.000000000000 0.000000000000 0.224348285559 H2 -1.423528800232 0.000000000000 -0.897393142237 H3 1.423528800232 0.000000000000 -0.897393142237 # EFP as EFP fragments -- efp h2o -4.014110144291 2.316749370493 -1.801514729931 -2.902133 1.734999 -1.953647 -- efp NH3,1.972094713645,,3.599497221584 , 5.447701074734 -1.105309 2.033306 -1.488582 -- efp NH3 -7.876296399270 -1.854372164887 -2.414804197762 2.526442 1.658262 -2.742084 """) # <<< EFP calc >>> psi4.set_options({ 'basis': '6-31g*', 'scf_type': 'pk', 'guess': 'core', 'df_scf_guess': False}) psi4.energy('efp') assert psi4.compare_values( 9.1793879214, qmefp.nuclear_repulsion_energy(), 6, 'QM NRE') assert psi4.compare_values(-0.0004901368, psi4.variable('efp elst energy'), 6, 'EFP-EFP Elst') # from q-chem assert psi4.compare_values(-0.0003168768, psi4.variable('efp ind energy'), 6, 'EFP-EFP Indc') assert psi4.compare_values(-0.0021985285, psi4.variable('efp disp energy'), 6, 'EFP-EFP Disp') # from q-chem assert psi4.compare_values( 0.0056859871, psi4.variable('efp exch energy'), 6, 'EFP-EFP Exch') # from q-chem assert psi4.compare_values( 0.0026804450, psi4.variable('efp total energy'), 6, 'EFP-EFP Totl') assert psi4.compare_values( 0.0026804450, psi4.variable('current energy'), 6, 'Current') psi4.core.print_variables() psi4.core.clean() psi4.core.clean_variables() # <<< QM + EFP calc >>> psi4.set_options({ 'e_convergence': 12, 'd_convergence': 12}) psi4.energy('scf') assert psi4.compare_values( 9.1793879214, qmefp.nuclear_repulsion_energy(), 6, 'QM NRE') assert psi4.compare_values( 0.2622598847, psi4.variable('efp total energy') - psi4.variable('efp ind energy'), 6, 'EFP corr to SCF') # from q-chem assert psi4.compare_values(-0.0117694790, psi4.variable('efp ind energy'), 6, 'QM-EFP Indc') # from q-chem assert psi4.compare_values(-0.0021985285, psi4.variable('efp disp energy'), 6, 'EFP-EFP Disp') # from q-chem assert psi4.compare_values( 0.0056859871, psi4.variable('efp exch energy'), 6, 'EFP-EFP Exch') # from q-chem assert psi4.compare_values( 0.2504904057, psi4.variable('efp total energy'), 6, 'EFP-EFP Totl') # from q-chem assert psi4.compare_values(-76.0139362744, psi4.variable('scf total energy'), 6, 'SCF') # from q-chem psi4.core.print_variables()
def test_dft_bench_ionization(func, expected, basis, dft_bench_systems, request): """functionals ionization energies vs. Q-Chem""" if func.lower() in psi4.driver.procedures['energy']: mols = dft_bench_systems psi4.set_options({'basis': basis, 'reference': 'uks'}) cation = psi4.energy(func, molecule=mols['h2o_plus']) psi4.set_options({'reference': 'rks'}) neutral = psi4.energy(func, molecule=mols['h2o']) assert compare_values(expected, cation - neutral, 4, request.node.name) else: pytest.skip("{0:s} not in Psi4.".format(func))
def psiSCF(self): psi4.core.set_output_file("output.dat",False) psi4.set_options({'basis': self.options['DEFAULT']['basis'], 'scf_type': 'pk', 'reference': 'rhf', 'puream': 0, 'print': 0 }) return psi4.energy('scf')
def test_psi4_sapt(): """sapt1""" #! SAPT0 cc-pVDZ computation of the ethene-ethyne interaction energy, using the cc-pVDZ-JKFIT RI basis for SCF #! and cc-pVDZ-RI for SAPT. Monomer geometries are specified using Cartesian coordinates. Eref = [ 85.189064196429101, -0.00359915058, 0.00362911158, -0.00083137117, -0.00150542374, -0.00230683391 ] ethene_ethyne = psi4.geometry(""" 0 1 C 0.000000 -0.667578 -2.124659 C 0.000000 0.667578 -2.124659 H 0.923621 -1.232253 -2.126185 H -0.923621 -1.232253 -2.126185 H -0.923621 1.232253 -2.126185 H 0.923621 1.232253 -2.126185 -- 0 1 C 0.000000 0.000000 2.900503 C 0.000000 0.000000 1.693240 H 0.000000 0.000000 0.627352 H 0.000000 0.000000 3.963929 units angstrom """) # this molecule will crash test if molecule passing broken barrier = psi4.geometry(""" 0 1 He """) psi4.set_options({ "basis": "cc-pvdz", "guess": "sad", "scf_type": "df", "sad_print": 2, "d_convergence": 11, "puream": True, "print": 1}) psi4.energy('sapt0', molecule=ethene_ethyne) Eelst = psi4.get_variable("SAPT ELST ENERGY") Eexch = psi4.get_variable("SAPT EXCH ENERGY") Eind = psi4.get_variable("SAPT IND ENERGY") Edisp = psi4.get_variable("SAPT DISP ENERGY") ET = psi4.get_variable("SAPT0 TOTAL ENERGY") assert psi4.compare_values(Eref[0], ethene_ethyne.nuclear_repulsion_energy(), 9, "Nuclear Repulsion Energy") assert psi4.compare_values(Eref[1], Eelst, 6, "SAPT0 Eelst") assert psi4.compare_values(Eref[2], Eexch, 6, "SAPT0 Eexch") assert psi4.compare_values(Eref[3], Eind, 6, "SAPT0 Eind") assert psi4.compare_values(Eref[4], Edisp, 6, "SAPT0 Edisp") assert psi4.compare_values(Eref[5], ET, 6, "SAPT0 Etotal")
def _build_wfn(ref, func, basis, nosym): if ref.startswith('RHF'): mol = tddft_systems['RHF'] else: mol = tddft_systems['UHF'] psi4.set_options({'reference': 'UHF'}) if nosym: mol.reset_point_group('c1') psi4.set_options({'scf_type': 'pk', 'e_convergence': 8, 'd_convergence': 8, 'save_jk': True}) e, wfn = psi4.energy("{}/{}".format(func, basis), return_wfn=True, molecule=mol) return wfn
def test_gdma(): """gdma1""" #! Water RHF/cc-pVTZ distributed multipole analysis ref_energy = -76.0571685433842219 ref_dma_mat = psi4.core.Matrix(3, 9) ref_dma_mat.name = 'Reference DMA values' ref_dma_arr = [ [ -0.43406697290168, -0.18762673939633, 0.00000000000000, 0.00000000000000, 0.03206686487531, 0.00000000000000, -0.00000000000000, -0.53123477172696, 0.00000000000000 ], [ 0.21703348903257, -0.06422316619952, 0.00000000000000, -0.11648289410022, 0.01844320206227, 0.00000000000000, 0.07409226544133, -0.07115302332866, 0.00000000000000 ], [ 0.21703348903257, -0.06422316619952, 0.00000000000000, 0.11648289410022, 0.01844320206227, 0.00000000000000, -0.07409226544133, -0.07115302332866, 0.00000000000000 ] ] for i in range(3): for j in range(9): ref_dma_mat.set(i, j, ref_dma_arr[i][j]) ref_tot_mat = psi4.core.Matrix(1, 9) ref_tot_mat.name = "Reference total values" ref_tot_arr = [ 0.00000000516346, -0.79665315928128, 0.00000000000000, 0.00000000000000, 0.10813259329390, 0.00000000000000, 0.00000000000000, -2.01989585894142, 0.00000000000000 ] for i in range(9): ref_tot_mat.set(0, i, ref_tot_arr[i]) # noreorient/nocom are not needed, but are used here to guarantee that the # GDMA origin placement defined below is at the O atom. water = psi4.geometry(""" O 0.000000 0.000000 0.117176 H -0.000000 -0.756950 -0.468706 H -0.000000 0.756950 -0.468706 noreorient nocom """) psi4.set_options({"scf_type": "pk", "basis": "cc-pvtz", "d_convergence": 10, "gdma_switch": 0, "gdma_radius": [ "H", 0.65 ], "gdma_limit": 2, "gdma_origin": [ 0.000000, 0.000000, 0.117176 ]}) energy, wfn = psi4.energy('scf', return_wfn=True) psi4.gdma(wfn) dmavals = psi4.core.variable("DMA DISTRIBUTED MULTIPOLES") totvals = psi4.core.variable("DMA TOTAL MULTIPOLES") assert psi4.compare_values(ref_energy, energy, 8, "SCF Energy") assert psi4.compare_matrices(dmavals, ref_dma_mat, 6, "DMA Distributed Multipoles") assert psi4.compare_matrices(totvals, ref_tot_mat, 6, "DMA Total Multipoles")
def test_v2rdm_casscf(): """v2rdm_casscf/tests/v2rdm1""" #! cc-pvdz N2 (6,6) active space Test DQG print(' N2 / cc-pVDZ / DQG(6,6), scf_type = CD / 1e-12, rNN = 0.5 A') import v2rdm_casscf n2 = psi4.geometry(""" 0 1 n n 1 r """) interloper = psi4.geometry(""" 0 1 O H 1 1.0 H 1 1.0 2 90.0 """) psi4.set_options({ 'basis': 'cc-pvdz', 'scf_type': 'cd', 'cholesky_tolerance': 1e-12, 'd_convergence': 1e-10, 'maxiter': 500, 'restricted_docc': [ 2, 0, 0, 0, 0, 2, 0, 0 ], 'active': [ 1, 0, 1, 1, 0, 1, 1, 1 ], }) ##psi4.set_module_options('v2rdm_casscf', { psi4.set_options({ # 'positivity': 'dqg', 'r_convergence': 1e-5, 'e_convergence': 1e-6, 'maxiter': 20000, # #'orbopt_frequency': 1000, # #'mu_update_frequency': 1000, }) psi4.activate(n2) n2.r = 0.5 refscf = -103.04337420425350 refv2rdm = -103.086205379481 psi4.energy('v2rdm-casscf', molecule=n2) assert psi4.compare_values(refscf, psi4.get_variable("SCF TOTAL ENERGY"), 8, "SCF total energy") assert psi4.compare_values(refv2rdm, psi4.get_variable("CURRENT ENERGY"), 5, "v2RDM-CASSCF total energy")
def test_psi4_basic(): """tu1-h2o-energy""" #! Sample HF/cc-pVDZ H2O computation h2o = psi4.geometry(""" O H 1 0.96 H 1 0.96 2 104.5 """) psi4.set_options({'basis': "cc-pVDZ"}) psi4.energy('scf') assert psi4.compare_values(-76.0266327341067125, psi4.get_variable('SCF TOTAL ENERGY'), 6, 'SCF energy')
def test_mp2_module(inp, clsd_open_pmols, request): tnm = request.node.name subject = clsd_open_pmols[inp['subject']] ref_block = _ref_module[inp['options']['scf_type']][inp['options']['reference']] ref_ref = ref_block['HF TOTAL ENERGY'] ref_block = ref_block[inp['options']['freeze_core']][inp['options']['mp2_type']] ref_corl = ref_block['MP2 CORRELATION ENERGY'] ref_tot = ref_block['MP2 TOTAL ENERGY'] psi4.set_options({ 'basis': 'cc-pvdz', 'guess': 'sad', 'e_convergence': 8, 'd_convergence': 7, }) psi4.set_options(inp['options']) if inp['driver'] == 'energy': ene, wfn = psi4.energy('mp2', molecule=subject, return_wfn=True) elif inp['driver'] == 'gradient': grad, wfn = psi4.gradient('mp2', molecule=subject, return_wfn=True) ref_tot_grad = ref_block['MP2 TOTAL GRADIENT'] for obj in [psi4.core, wfn]: for pv in ['HF TOTAL ENERGY', 'SCF TOTAL ENERGY', 'CURRENT REFERENCE ENERGY']: assert compare_values(ref_ref, obj.variable(pv), 6, tnm + ' ' + pv) for pv in [ 'MP2 CORRELATION ENERGY', 'CURRENT CORRELATION ENERGY', ]: assert compare_values(ref_corl, obj.variable(pv), 6, tnm + ' ' + pv) for pv in [ 'MP2 TOTAL ENERGY', 'CURRENT ENERGY', ]: assert compare_values(ref_tot, obj.variable(pv), 6, tnm + ' ' + pv) assert compare_values(ref_tot, wfn.energy(), 6, tnm + ' wfn') if inp['driver'] == 'energy': assert compare_values(ref_tot, ene, 6, tnm + ' return') elif inp['driver'] == 'gradient': assert compare_matrices(ref_tot_grad, wfn.gradient(), 6, tnm + ' grad wfn') assert compare_matrices(ref_tot_grad, grad, 6, tnm + ' grad return')
def test_opt(): """ We pick the physicist's water molecule in a relatively large basis set (aug-cc-pVDZ), whose uhf and rhf solutions are the same. And we test that energies of the following four cases are identical: RHF + DIIS RHF + ODA UHF + DIIS UHF + ODA Note for DIIS, we in addition require the convergence is achieved in 30 iterations. """ # get integrals from psi4 ao_ints, scf_params, e_ZZ_repul = \ scf.init(os.path.dirname(__file__) + '/test_opt.yml') # RHF, DIIS scf_params['max_iter'] = 30 eps, C, D, F = scf.scf(ao_ints, scf_params, e_ZZ_repul) E_rhf_diis = scf.get_SCF_energy(ao_ints['H'], F, D, False) + e_ZZ_repul # RHF, ODA scf_params['max_iter'] = 300 scf_params['opt'] = "oda" eps, C, D, F = scf.scf(ao_ints, scf_params, e_ZZ_repul) E_rhf_oda = scf.get_SCF_energy(ao_ints['H'], F, D, False) + e_ZZ_repul # UHF, DIIS scf_params['max_iter'] = 30 scf_params['opt'] = "diis" scf_params['unrestricted'] = True eps, C, D, F = scf.scf(ao_ints, scf_params, e_ZZ_repul) E_uhf_diis = scf.get_SCF_energy(ao_ints['H'], F, D, True) + e_ZZ_repul # UHF, ODA scf_params['max_iter'] = 300 scf_params['opt'] = "oda" eps, C, D, F = scf.scf(ao_ints, scf_params, e_ZZ_repul) E_uhf_oda = scf.get_SCF_energy(ao_ints['H'], F, D, True) + e_ZZ_repul # RHF, psi4 import psi4 mol = psi4.geometry(scf_params['geometry']) mol.update_geometry() ctrl_string = "SCF/" + scf_params['basis'] psi4.set_options({"scf_type": "pk"}) psi4_E_rhf = psi4.energy(ctrl_string, molecule = mol) # check assert(np.allclose(E_rhf_diis, E_rhf_oda) == True) assert(np.allclose(E_rhf_diis, E_uhf_diis) == True) assert(np.allclose(E_rhf_diis, E_uhf_oda) == True) assert(np.allclose(E_rhf_diis, psi4_E_rhf) == True)
def psiMP2(self,options): psi4.core.set_output_file("output.dat",False) psi4.set_options({'basis': options['DEFAULT']['basis'], 'scf_type': 'pk', 'reference': 'uhf', 'e_convergence': 12, 'df_basis_mp2' : self.dfBasisName, 'puream': 0, 'print': 0 }) if not self.df: psi4.set_options( {'mp2_type': 'conv'} ) return psi4.energy('mp2')
def test_RU_TDA_C1(): h2o = psi4.geometry("""0 1 O 0.000000 0.000000 0.135446 H -0.000000 0.866812 -0.541782 H -0.000000 -0.866812 -0.541782 symmetry c1 no_reorient no_com """) psi4.set_options({"scf_type": "pk", 'save_jk': True}) e, wfn = psi4.energy("hf/sto-3g", molecule=h2o, return_wfn=True) A_ref, _ = build_UHF_AB_C1(wfn) ni, na, _, _ = A_ref['IAJB'].shape nia = ni * na A_sing_ref = A_ref['IAJB'] + A_ref['IAjb'] A_sing_ref = A_sing_ref.reshape(nia, nia) A_trip_ref = A_ref['IAJB'] - A_ref['IAjb'] A_trip_ref = A_trip_ref.reshape(nia, nia) sing_vals, _ = np.linalg.eigh(A_sing_ref) trip_vals, _ = np.linalg.eigh(A_trip_ref) trip_eng = TDRSCFEngine(wfn, ptype='tda', triplet=True) sing_eng = TDRSCFEngine(wfn, ptype='tda', triplet=False) ID = [psi4.core.Matrix.from_array(v.reshape((ni, na))) for v in tuple(np.eye(nia).T)] psi4.core.print_out("\nA sing:\n" + str(A_sing_ref) + "\n\n") psi4.core.print_out("\nA trip:\n" + str(A_trip_ref) + "\n\n") A_trip_test = np.column_stack([x.to_array().flatten() for x in trip_eng.compute_products(ID)[0]]) assert compare_arrays(A_trip_ref, A_trip_test, 8, "Triplet Ax C1 products") A_sing_test = np.column_stack([x.to_array().flatten() for x in sing_eng.compute_products(ID)[0]]) assert compare_arrays(A_sing_ref, A_sing_test, 8, "Singlet Ax C1 products") sing_vals_2, _ = np.linalg.eigh(A_sing_test) trip_vals_2, _ = np.linalg.eigh(A_trip_test) psi4.core.print_out("\n\n SINGLET EIGENVALUES\n") for x, y in zip(sing_vals, sing_vals_2): psi4.core.print_out("{:10.6f} {:10.6f}\n".format(x, y)) # assert compare_values(x, y, 4, "Singlet ROOT") psi4.core.print_out("\n\n Triplet EIGENVALUES\n") for x, y in zip(trip_vals, trip_vals_2): psi4.core.print_out("{:10.6f} {:10.6f}\n".format(x, y)) # assert compare_values(x, y, 4, "Triplet Root") for x, y in zip(sing_vals, sing_vals_2): assert compare_values(x, y, 4, "Singlet ROOT") for x, y in zip(trip_vals, trip_vals_2): assert compare_values(x, y, 4, "Triplet Root")
def test_chemps2(): """chemps2/scf-n2""" #! dmrg-scf on N2 N2 = psi4.geometry(""" N 0.0000 0.0000 0.0000 N 0.0000 0.0000 2.1180 units au """) psi4.set_options({ 'basis': 'cc-pVDZ', 'reference': 'rhf', 'e_convergence': 1e-12, 'd_convergence': 1e-12, 'dmrg_irrep': 0, 'dmrg_multiplicity': 1, 'restricted_docc': [ 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 ], 'active': [ 2 , 0 , 1 , 1 , 0 , 2 , 1 , 1 ], 'dmrg_sweep_states': [ 500, 1000, 1000 ], 'dmrg_sweep_energy_conv': [ 1e-10, 1e-10, 1e-10 ], 'dmrg_sweep_dvdson_rtol': [ 1e-4, 1e-6, 1e-8 ], 'dmrg_sweep_max_sweeps': [ 5, 5, 10 ], 'dmrg_sweep_noise_prefac': [ 0.05, 0.05, 0.0 ], 'dmrg_print_corr': True, 'dmrg_mps_write': False, 'dmrg_unitary_write': True, 'dmrg_diis': True, 'dmrg_scf_diis_thr': 1e-2, 'dmrg_diis_write': True, 'dmrg_excitation': 0, # Ground state 'dmrg_scf_state_avg': False, 'dmrg_scf_active_space': 'NO', # INPUT; NO; LOC 'dmrg_local_init': False, }) psi4.energy("dmrg-scf") ref_energy = -109.1035023353 assert psi4.compare_values(ref_energy, psi4.variable("CURRENT ENERGY"), 6, "DMRG Energy")
def test_dkh(): """dkh/molpro-2order""" Ne = psi4.geometry(""" 0 1 Ne """) psi4.set_options({ 'reference': 'rhf', 'basis': 'cc-pvtz-dk', 'relativistic': 'dkh', 'dkh_order': 2, 'print': 2, 'scf_type': 'pk'}) e = psi4.energy('scf') assert psi4.compare_values(-128.66891610, e, 6, '2nd order vs Molpro')
np.set_printoptions(precision=5, linewidth=200, suppress=True) import psi4 psi4.core.set_memory(int(2e9), False) psi4.core.set_output_file('output.dat', False) numpy_memory = 2 mol = psi4.geometry(""" O H 1 1.1 H 1 1.1 2 104 symmetry c1 """) psi4.set_options({'basis': 'cc-pVDZ'}) # For numpy compare_psi4 = True # Compute CCSD ccsd = helper_CCSD(mol, memory=2) ccsd.compute_energy() CCSDcorr_E = ccsd.ccsd_corr_e CCSD_E = ccsd.ccsd_e print('\nFinal CCSD correlation energy: % 16.10f' % CCSDcorr_E) print('Total CCSD energy: % 16.10f' % CCSD_E) # Triples correction required o^3v^3 storage due the noddy algorithm
def test_dftd3(): """dftd3/energy""" #! Exercises the various DFT-D corrections, both through python directly and through c++ ref_d2 = [-0.00390110, -0.00165271, -0.00058118] ref_d3zero = [-0.00285088, -0.00084340, -0.00031923] ref_d3bj = [-0.00784595, -0.00394347, -0.00226683] ref_pbe_d2 = [-0.00278650, -0.00118051, -0.00041513] ref_pbe_d3zero = [-0.00175474, -0.00045421, -0.00016839] ref_pbe_d3bj = [-0.00475937, -0.00235265, -0.00131239] eneyne = psi4.geometry(""" C 0.000000 -0.667578 -2.124659 C 0.000000 0.667578 -2.124659 H 0.923621 -1.232253 -2.126185 H -0.923621 -1.232253 -2.126185 H -0.923621 1.232253 -2.126185 H 0.923621 1.232253 -2.126185 -- C 0.000000 0.000000 2.900503 C 0.000000 0.000000 1.693240 H 0.000000 0.000000 0.627352 H 0.000000 0.000000 3.963929 """) psi4.print_stdout(' -D correction from Py-side') eneyne.update_geometry() E, G = eneyne.run_dftd3('b3lyp', 'd2gr') assert psi4.compare_values(ref_d2[0], E, 7, 'Ethene-Ethyne -D2') mA = eneyne.extract_subsets(1) E, G = mA.run_dftd3('b3lyp', 'd2gr') assert psi4.compare_values(ref_d2[1], E, 7, 'Ethene -D2') mB = eneyne.extract_subsets(2) E, G = mB.run_dftd3('b3lyp', 'd2gr') assert psi4.compare_values(ref_d2[2], E, 7, 'Ethyne -D2') #mBcp = eneyne.extract_subsets(2,1) #E, G = mBcp.run_dftd3('b3lyp', 'd2gr') #compare_values(ref_d2[2], E, 7, 'Ethyne(CP) -D2') E, G = eneyne.run_dftd3('b3lyp', 'd3zero') assert psi4.compare_values(ref_d3zero[0], E, 7, 'Ethene-Ethyne -D3 (zero)') mA = eneyne.extract_subsets(1) E, G = mA.run_dftd3('b3lyp', 'd3zero') assert psi4.compare_values(ref_d3zero[1], E, 7, 'Ethene -D3 (zero)') mB = eneyne.extract_subsets(2) E, G = mB.run_dftd3('b3lyp', 'd3zero') assert psi4.compare_values(ref_d3zero[2], E, 7, 'Ethyne -D3 (zero)') E, G = eneyne.run_dftd3('b3lyp', 'd3bj') assert psi4.compare_values(ref_d3bj[0], E, 7, 'Ethene-Ethyne -D3 (bj)') mA = eneyne.extract_subsets(1) E, G = mA.run_dftd3('b3lyp', 'd3bj') assert psi4.compare_values(ref_d3bj[1], E, 7, 'Ethene -D3 (bj)') mB = eneyne.extract_subsets(2) E, G = mB.run_dftd3('b3lyp', 'd3bj') assert psi4.compare_values(ref_d3bj[2], E, 7, 'Ethyne -D3 (bj)') E, G = eneyne.run_dftd3('b3lyp', 'd3') assert psi4.compare_values(ref_d3zero[0], E, 7, 'Ethene-Ethyne -D3 (alias)') E, G = eneyne.run_dftd3('b3lyp', 'd') assert psi4.compare_values(ref_d2[0], E, 7, 'Ethene-Ethyne -D (alias)') E, G = eneyne.run_dftd3('b3lyp', 'd2') assert psi4.compare_values(ref_d2[0], E, 7, 'Ethene-Ethyne -D2 (alias)') psi4.set_options({'basis': 'sto-3g', 'scf_type': 'df', 'dft_radial_points': 50, # use really bad grid for speed since all we want is the -D value 'dft_spherical_points': 110, #'scf print': 3, # will print dftd3 program output to psi4 output file }) psi4.print_stdout(' -D correction from C-side') psi4.activate(mA) #psi4.energy('b3lyp-d2p4') #assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling psi4 Disp class)') #psi4.energy('b3lyp-d2gr') #assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling dftd3 -old)') #psi4.energy('b3lyp-d3zero') #assert psi4.compare_values(ref_d3zero[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -zero)') psi4.energy('b3lyp-d3bj') assert psi4.compare_values(ref_d3bj[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -bj)') psi4.energy('b3lyp-d2') assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (alias)') #psi4.energy('b3lyp-d3') #assert psi4.compare_values(ref_d3zero[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (alias)') #psi4.energy('b3lyp-d') #assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D (alias)') psi4.energy('wb97x-d') assert psi4.compare_values(-0.000834247063, psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene wb97x-d (chg)') psi4.print_stdout(' non-default -D correction from C-side') psi4.activate(mB) #psi4.set_options({'dft_dispersion_parameters': [0.75]}) #psi4.energy('b3lyp-d2p4') #assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling psi4 Disp class)') #psi4.set_options({'dft_dispersion_parameters': [0.75, 20.0]}) #psi4.energy('b3lyp-d2gr') #assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling dftd3 -old)') #psi4.set_options({'dft_dispersion_parameters': [1.0, 0.722, 1.217, 14.0]}) #psi4.energy('b3lyp-d3zero') #assert psi4.compare_values(ref_pbe_d3zero[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -zero)') psi4.set_options({'dft_dispersion_parameters': [1.000, 0.7875, 0.4289, 4.4407]}) psi4.energy('b3lyp-d3bj') assert psi4.compare_values(ref_pbe_d3bj[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -bj)') psi4.set_options({'dft_dispersion_parameters': [0.75]}) psi4.energy('b3lyp-d2') assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (alias)') psi4.set_options({'dft_dispersion_parameters': [1.0, 0.722, 1.217, 14.0]}) psi4.energy('b3lyp-d3') assert psi4.compare_values(ref_pbe_d3zero[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (alias)') psi4.set_options({'dft_dispersion_parameters': [0.75]}) psi4.energy('b3lyp-d') assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D (alias)') psi4.activate(mA) psi4.set_options({'dft_dispersion_parameters': [1.0]}) psi4.energy('wb97x-d') assert psi4.compare_values(-0.000834247063, psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene wb97x-d (chg)') psi4.print_stdout(' non-default -D correction from Py-side') eneyne.update_geometry() eneyne.run_dftd3('b3lyp', 'd2gr', {'s6': 0.75}) assert psi4.compare_values(ref_pbe_d2[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D2') mA = eneyne.extract_subsets(1) mA.run_dftd3('b3lyp', 'd2gr', {'s6': 0.75}) assert psi4.compare_values(ref_pbe_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2') mB = eneyne.extract_subsets(2) mB.run_dftd3('b3lyp', 'd2gr', {'s6': 0.75}) assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethyne -D2') eneyne.run_dftd3('b3lyp', 'd3zero', {'s6': 1.0, 's8': 0.722, 'sr6': 1.217, 'alpha6': 14.0}) assert psi4.compare_values(ref_pbe_d3zero[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D3 (zero)') mA = eneyne.extract_subsets(1) mA.run_dftd3('b3lyp', 'd3zero', {'s6': 1.0, 's8': 0.722, 'sr6': 1.217, 'alpha6': 14.0}) assert psi4.compare_values(ref_pbe_d3zero[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (zero)') mB = eneyne.extract_subsets(2) mB.run_dftd3('b3lyp', 'd3zero', {'s6': 1.0, 's8': 0.722, 'sr6': 1.217, 'alpha6': 14.0}) assert psi4.compare_values(ref_pbe_d3zero[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethyne -D3 (zero)') eneyne.run_dftd3('b3lyp', 'd3bj', {'s6': 1.000, 's8': 0.7875, 'a1': 0.4289, 'a2': 4.4407}) assert psi4.compare_values(ref_pbe_d3bj[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D3 (bj)') mA = eneyne.extract_subsets(1) mA.run_dftd3('b3lyp', 'd3bj', {'s6': 1.000, 's8': 0.7875, 'a1': 0.4289, 'a2': 4.4407}) assert psi4.compare_values(ref_pbe_d3bj[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (bj)') mB = eneyne.extract_subsets(2) mB.run_dftd3('b3lyp', 'd3bj', {'s6': 1.000, 's8': 0.7875, 'a1': 0.4289, 'a2': 4.4407}) assert psi4.compare_values(ref_pbe_d3bj[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethyne -D3 (bj)') eneyne.run_dftd3('b3lyp', 'd3', {'s6': 1.0, 's8': 0.722, 'sr6': 1.217, 'alpha6': 14.0}) assert psi4.compare_values(ref_pbe_d3zero[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D3 (alias)') eneyne.run_dftd3('b3lyp', 'd', {'s6': 0.75}) assert psi4.compare_values(ref_pbe_d2[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D (alias)') eneyne.run_dftd3('b3lyp', 'd2', {'s6': 0.75}) assert psi4.compare_values(ref_pbe_d2[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D2 (alias)')
def test_psi4_scfproperty(): """scf-property""" #! UFH and B3LYP cc-pVQZ properties for the CH2 molecule. with open('grid.dat', 'w') as handle: handle.write("""\ 0.0 0.0 0.0 1.1 1.3 1.4 """) ch2 = psi4.geometry(""" 0 3 c h 1 b1 h 1 b1 2 a1 b1 = 1.0 a1 = 125.0 """) # Get a reasonable guess, to save some iterations psi4.set_options({ "scf_type": "pk", "basis": "6-31G**", "e_convergence": 8, "docc": [2, 0, 0, 1], "socc": [1, 0, 1, 0], "reference": "uhf" }) ch2.update_geometry() assert psi4.compare_values(6.648418918908746, ch2.nuclear_repulsion_energy(), 9, "Nuclear repulsion energy") props = [ 'DIPOLE', 'QUADRUPOLE', 'MULLIKEN_CHARGES', 'LOWDIN_CHARGES', 'WIBERG_LOWDIN_INDICES', 'MAYER_INDICES', 'MAYER_INDICES', 'MO_EXTENTS', 'GRID_FIELD', 'GRID_ESP', 'ESP_AT_NUCLEI', 'MULTIPOLE(5)', 'NO_OCCUPATIONS' ] psi4.property('scf', properties=props) assert psi4.compare_values(psi4.get_variable("CURRENT ENERGY"), -38.91591819679808, 6, "SCF energy") assert psi4.compare_values(psi4.get_variable('SCF DIPOLE X'), 0.000000000000, 4, "SCF DIPOLE X") assert psi4.compare_values(psi4.get_variable('SCF DIPOLE Y'), 0.000000000000, 4, "SCF DIPOLE Y") assert psi4.compare_values(psi4.get_variable('SCF DIPOLE Z'), 0.572697798348, 4, "SCF DIPOLE Z") assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE XX'), -7.664066833060, 4, "SCF QUADRUPOLE XX") assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE YY'), -6.097755074075, 4, "SCF QUADRUPOLE YY") assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE ZZ'), -7.074596012050, 4, "SCF QUADRUPOLE ZZ") assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE XY'), 0.000000000000, 4, "SCF QUADRUPOLE XY") assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE XZ'), 0.000000000000, 4, "SCF QUADRUPOLE XZ") assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE YZ'), 0.000000000000, 4, "SCF QUADRUPOLE YZ") psi4.property('B3LYP', properties=props) assert psi4.compare_values(psi4.get_variable('CURRENT ENERGY'), -39.14134740550916, 6, "B3LYP energy") assert psi4.compare_values(psi4.get_variable('B3LYP DIPOLE X'), 0.000000000000, 4, "B3LYP DIPOLE X") assert psi4.compare_values(psi4.get_variable('B3LYP DIPOLE Y'), -0.000000000000, 4, "B3LYP DIPOLE Y") assert psi4.compare_values(psi4.get_variable('B3LYP DIPOLE Z'), 0.641741521158, 4, "B3LYP DIPOLE Z") assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE XX'), -7.616483183211, 4, "B3LYP QUADRUPOLE XX") assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE YY'), -6.005896804551, 4, "B3LYP QUADRUPOLE YY") assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE ZZ'), -7.021817489904, 4, "B3LYP QUADRUPOLE ZZ") assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE XY'), 0.000000000000, 4, "B3LYP QUADRUPOLE XY") assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE XZ'), 0.000000000000, 4, "B3LYP QUADRUPOLE XZ") assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE YZ'), -0.000000000000, 4, "B3LYP QUADRUPOLE YZ")
# Memory for Psi4 in GB psi4.core.set_memory(int(5e8), False) psi4.core.set_output_file("output.dat", False) # Memory for numpy in GB numpy_memory = 2 mol = psi4.geometry(""" O H 1 1.1 H 1 1.1 2 104 symmetry c1 """) psi4.set_options({'basis': 'cc-pvdz', 'scf_type': 'pk', 'e_convergence': 1e-8}) # Set defaults maxiter = 40 E_conv = 1.0E-6 D_conv = 1.0E-3 # Integral generation from Psi4's MintsHelper wfn = psi4.core.Wavefunction.build(mol, psi4.core.get_global_option('BASIS')) t = time.time() mints = psi4.core.MintsHelper(wfn.basisset()) S = np.asarray(mints.ao_overlap()) # Get nbf and ndocc for closed shell molecules nbf = S.shape[0] ndocc = wfn.nalpha()
import psi4 psi4.set_output_file("output.dat", False) geom = psi4.geometry(""" C """) psi4.set_options({"SCF_TYPE": "DF", "BASIS": "cc-pVDZ"}) scf_e, scf_wfn = psi4.energy('SCF', return_wfn=True) psi4.compare_values(-37.5959861862713893, scf_e, 6, 'SCF DF Energy') psi4.core.set_local_option("SCF", "SCF_TYPE", "PK") psi4.compare_values(-37.5959861862713893, scf_e, 6, 'SCF PK Energy')
#!/usr/bin/python3 """ Test for reproducing results from Steven & Fink, CPL 139, pp.: 15-22 (1987) Usage: [basis] [xyz.psi] """ import psi4, gefp, sys psi4.set_options({ "scf_type": "direct", "guess": "auto", "df_scf_guess": True, "e_convergence": 1e-10, "d_convergence": 1e-10, "basis": sys.argv[1], "puream": False, "print": 1, }) psi4.set_output_file("test.log", False) mol = gefp.core.utilities.psi_molecule_from_file(sys.argv[2]) gefp.math.matrix.move_atom_rotate_molecule(mol, [-30., -83., 43.1]) e_hf, wfn = psi4.energy('scf', molecule=mol, return_wfn=True) sol = gefp.density.rvs.RVS(wfn) sol.run_dimer(conver=1e-8) psi4.core.print_out(str(sol))
def test_sparse_ci(): import math import psi4 import forte import itertools import numpy as np import pytest from forte import forte_options ref_fci = -1.101150330132956 psi4.core.clean() # need to clean the options otherwise this job will interfere forte.clean_options() psi4.geometry(""" H H 1 1.0 """) psi4.set_options({'basis': 'sto-3g'}) E_scf, wfn = psi4.energy('scf', return_wfn=True) na = wfn.nalpha() nb = wfn.nbeta() nirrep = wfn.nirrep() wfn_symmetry = 0 forte.startup() forte.banner() psi4_options = psi4.core.get_options() psi4_options.set_current_module('FORTE') forte_options.get_options_from_psi4(psi4_options) # Setup forte and prepare the active space integral class nmopi = wfn.nmopi() point_group = wfn.molecule().point_group().symbol() mo_space_info = forte.make_mo_space_info(nmopi, point_group, forte_options) ints = forte.make_ints_from_psi4(wfn, forte_options, mo_space_info) as_ints = forte.make_active_space_ints(mo_space_info, ints, 'ACTIVE', ['RESTRICTED_DOCC']) as_ints.print() print('\n\n => Sparse FCI Test <=') print(' Number of irreps: {}'.format(nirrep)) nmo = wfn.nmo() nmopi = [wfn.nmopi()[h] for h in range(nirrep)] nmopi_str = [str(wfn.nmopi()[h]) for h in range(nirrep)] mo_sym = [] for h in range(nirrep): for i in range(nmopi[h]): mo_sym.append(h) print(' Number of orbitals per irreps: [{}]'.format(','.join(nmopi_str))) print(' Symmetry of the MOs: ', mo_sym) hf_reference = forte.Determinant() hf_reference.create_alfa_bit(0) hf_reference.create_beta_bit(0) print(' Hartree-Fock determinant: {}'.format(hf_reference.str(2))) # Compute the HF energy hf_energy = as_ints.nuclear_repulsion_energy() + as_ints.slater_rules( hf_reference, hf_reference) print(' Nuclear repulsion energy: {}'.format( as_ints.nuclear_repulsion_energy())) print(' Reference energy: {}'.format(hf_energy)) # Build a list of determinants orblist = [i for i in range(nmo)] dets = [] for astr in itertools.combinations(orblist, na): for bstr in itertools.combinations(orblist, nb): sym = 0 d = forte.Determinant() for a in astr: d.create_alfa_bit(a) sym = sym ^ mo_sym[a] for b in bstr: d.create_beta_bit(b) sym = sym ^ mo_sym[b] if (sym == wfn_symmetry): dets.append(d) print(' Determinant {} has symmetry {}'.format( d.str(nmo), sym)) # Build the Hamiltonian matrix using 'slater_rules' nfci = len(dets) H = np.ndarray((nfci, nfci)) for I in range(nfci): # off-diagonal terms for J in range(I + 1, nfci): HIJ = as_ints.slater_rules(dets[I], dets[J]) H[I][J] = H[J][I] = HIJ # diagonal term H[I][I] = as_ints.nuclear_repulsion_energy() + as_ints.slater_rules( dets[I], dets[I]) # Find the lowest eigenvalue efci = np.linalg.eigh(H)[0][0] print('\n FCI Energy: {}\n'.format(efci)) assert efci == pytest.approx(ref_fci, 1.0e-9) # Clean up forte (necessary) forte.cleanup()
# Memory for numpy in GB numpy_memory = 2 # Triplet O2 mol = psi4.geometry(""" 0 3 O O 1 1.2 symmetry c1 """) psi4.set_options({ 'guess': 'core', 'basis': 'aug-cc-pvdz', 'scf_type': 'pk', 'e_convergence': 1e-8, 'reference': 'rohf' }) wfn = psi4.core.Wavefunction.build(mol, psi4.core.get_global_option('BASIS')) # Set occupations nocc = wfn.nalpha() ndocc = wfn.nbeta() nsocc = nocc - ndocc # Set defaults maxiter = 10 max_micro = 4 micro_print = True
C 0.69705 -1.20732 0.00000 C -0.69705 -1.20732 0.00000 C -1.39410 0.00000 0.00000 C -0.69705 1.20732 0.00000 C 0.69705 1.20732 0.00000 H 2.47618 0.00000 0.00000 H 1.23809 -2.14444 0.00000 H -1.23809 -2.14444 0.00000 H -2.47618 0.00000 0.00000 H -1.23809 2.14444 0.00000 H 1.23809 2.14444 0.00000 symmetry c1 """) # Basis used in mp2 density fitting psi4.set_options({'basis': 'aug-cc-pVDZ', 'df_basis_scf': 'aug-cc-pvdz-ri'}) check_energy = False print('\nStarting RHF...') t = time.time() RHF_E, wfn = psi4.energy('SCF', return_wfn=True) print('...RHF finished in %.3f seconds: %16.10f' % (time.time() - t, RHF_E)) # Grab data from Wavfunction clas ndocc = wfn.nalpha() nbf = wfn.nso() nvirt = nbf - ndocc # Split eigenvectors and eigenvalues into o and v eps_occ = np.asarray(wfn.epsilon_a_subset("AO", "ACTIVE_OCC"))
def sf_cas(new_charge, new_multiplicity, ref_mol, conf_space="", add_opts={}, return_ci_wfn=False, return_rohf_wfn=False, return_rohf_e=False, read_rohf_wfn=False, wfn_rohf_in=None, write_rohf_wfn="", write_ci_vects=False, localize=False, frozen_docc=0, frozen_uocc=0): """ A method to run a RAS-nSF-IP/EA calculation. This runs a RAS-nSF-IP/EA calculation using Psi4's DETCI module. The number of spin-flips and IP/EA is determined based on setting the ``new_charge`` and ``new_multiplicity`` of the desired target state. Additional excitations are included by setting the ``conf_space`` keyword; excitations through the CISDT level are currently supported. Parameters ---------- new_charge : int Target charge of the molecule. new_multiplicity : int Target multiplicity of the molecule. ref_mol : psi4.core.Molecule Molecule to run the calculation on. conf_space : str ("") Option for including additional excitations outside of the CAS space. Defaults to CAS-nSF-IP/EA. Valid options include: * ``""`` CAS-nSF-IP/EA * ``"h"`` RAS(h)-nSF-IP/EA * ``"p"`` RAS(p)-nSF-IP/EA * ``"1x"`` RAS(h,p)-nSF-IP/EA * ``"S"`` RAS(S)-nSF-IP/EA * ``"SD"`` RAS(SD)-nSF-IP/EA * ``"SDT"`` RAS(SDT)-nSF-IP/EA add_opts : dict ({}) Additional options to pass into Psi4. return_ci_wfn : bool (False) Whether to return the CI wavefunction object. return_rohf_wfn : bool (False) Whether to return the ROHF wavefunction object. return_rohf_e : bool (False) Whether to return the ROHF energy. read_rohf_wfn : bool (False) Whether to read a Psi4 ROHF wavefunction. rohf_wfn_in : psi4.core.Wavefunction The Psi4 ROHF reference wavefunction (pre-computed). write_rohf_wfn : str ("") Name of file (.npz) to write localize : bool (False) Perform BOYS localization on the RAS 2 space before DETCI call? Can help with visualization and analysis of orbitals. Returns ------- e_ci : double The SF-CAS([conf_space]) energy. return_ci_wfn : psi4.core.Wavefunction (optional) The SF-CAS([conf_space]) wavefunction. return_rohf_e : double (optional) The ROHF energy. return_rohf_wfn : psi4.core.Wavefunction (optional) The ROHF wavefunction. """ # printing initial information about the calculation print("SF-CAS(%s) CALCULATION" % conf_space) # default options for Psi4 opts = { 'scf_type': 'pk', 'basis': 'cc-pvdz', 'reference': 'rohf', 'mixed': False, 'maxiter': 1000, 'ci_maxiter': 50 } opts.update(add_opts) # add additional options from user # run ROHF calculation on reference state or read it in psi4.core.clean() # cleanup in case Psi4 has been run before psi4.set_options(opts) mol = ref_mol.clone() # clone molecule so original isn't modified # read in ROHF guess wavefunction if provided if (read_rohf_wfn): # set up options and run psi4.set_options(opts) print("USING ROHF FROM REFERENCE...\tCHARGE %i\tMULT %i" % (ref_mol.molecular_charge(), ref_mol.multiplicity())) wfn_rohf = wfn_rohf_in e_rohf = wfn_rohf.energy() # else, run ROHF on reference state else: print("RUNNING REFERENCE...\tCHARGE %i\tMULT %i" % (ref_mol.molecular_charge(), ref_mol.multiplicity())) e_rohf, wfn_rohf = psi4.energy('scf', molecule=mol, return_wfn=True, options=opts) print("SCF (%i %i): %6.12f" % (mol.molecular_charge(), mol.multiplicity(), e_rohf)) # change charge and multiplicity to new target values print("DOING SPIN-FLIP: CHARGE %i, MULTIPLICITY %i" % (new_charge, new_multiplicity)) # saving npz file of wavefunction if (write_rohf_wfn != ""): wfn_rohf.to_file(write_rohf_wfn) # update molecular charge and multiplicity mol.set_molecular_charge(new_charge) mol.set_multiplicity(new_multiplicity) # set up reference wfn to pass into detci # save orbital values from reference calculation doccpi = wfn_rohf.doccpi()[0] soccpi = wfn_rohf.soccpi()[0] nmo = wfn_rohf.nmo() # calculate soccpi and doccpi new_soccpi = mol.multiplicity() - 1 del_electrons = ref_mol.molecular_charge() - mol.molecular_charge() n_total = wfn_rohf.nalpha() + wfn_rohf.nbeta() + del_electrons # set orbital occupations wfn_rohf.force_soccpi(psi4.core.Dimension([new_soccpi])) wfn_rohf.force_doccpi( psi4.core.Dimension([(int)((n_total - new_soccpi) / 2)])) # if we need to localize... if (localize): C = psi4.core.Matrix.to_array(wfn_rohf.Ca(), copy=True) ras1_C = C[:, :doccpi] ras2_C = C[:, doccpi:doccpi + soccpi] ras3_C = C[:, doccpi + soccpi:] loc = psi4.core.Localizer.build('BOYS', wfn_rohf.basisset(), psi4.core.Matrix.from_array(ras2_C)) loc.localize() ras2_localized = psi4.core.Matrix.to_array(loc.L, copy=True) localized_orbs = np.column_stack((ras1_C, ras2_localized, ras3_C)) new_Ca = psi4.core.Matrix.from_array(localized_orbs, name="Ca") new_Cb = psi4.core.Matrix.from_array(localized_orbs, name="Cb") wfn_rohf.Ca().copy(new_Ca) wfn_rohf.Cb().copy(new_Cb) # set active space and docc space based on configuration space input # Regular CAS configuration space # includes only active space configurations if (conf_space == ""): opts.update({'frozen_docc': [doccpi]}) opts.update({'ras1': [0]}) opts.update({'ras2': [soccpi]}) opts.update({'ras3': [0]}) opts.update({'ras4': [0]}) # just (h) excitations elif (conf_space == "h"): opts.update({'ex_level': 0}) opts.update({'val_ex_level': 1}) opts.update({'ras3_max': 0}) opts.update({'frozen_docc': [frozen_docc]}) opts.update({'ras1': [doccpi - frozen_docc]}) opts.update({'ras2': [soccpi]}) opts.update({'ras3': [0]}) opts.update({'ras4': [0]}) # just (p) excitations elif (conf_space == "p"): opts.update({'ex_level': 0}) opts.update({'val_ex_level': 0}) opts.update({'ras3_max': 1}) opts.update({'frozen_docc': [doccpi]}) opts.update({'ras1': [0]}) opts.update({'ras2': [soccpi]}) opts.update({'ras3': [nmo - soccpi - doccpi - frozen_uocc]}) opts.update({'frozen_uocc': [frozen_uocc]}) opts.update({'ras4': [0]}) # 1x configuration space # includes (h, p) excitations elif (conf_space == "1x"): opts.update({'frozen_docc': [0]}) opts.update({'ex_level': 0}) opts.update({'val_ex_level': 1}) opts.update({'ras3_max': 1}) opts.update({'frozen_docc': [frozen_docc]}) opts.update({'ras1': [doccpi - frozen_docc]}) opts.update({'ras2': [soccpi]}) opts.update({'ras3': [nmo - soccpi - doccpi - frozen_uocc]}) opts.update({'frozen_uocc': [frozen_uocc]}) opts.update({'ras4': [0]}) # S configuration space # includes (h, p, hp) excitations elif (conf_space == "S" or conf_space == "xcis"): opts.update({'frozen_docc': [0]}) opts.update({'ex_level': 1}) opts.update({'frozen_docc': [frozen_docc]}) opts.update({'ras1': [doccpi - frozen_docc]}) opts.update({'ras2': [soccpi]}) opts.update({'ras3': [nmo - soccpi - doccpi - frozen_uocc]}) opts.update({'frozen_uocc': [frozen_uocc]}) opts.update({'ras4': [0]}) elif (conf_space == "SD"): opts.update({'frozen_docc': [0]}) opts.update({'ex_level': 2}) opts.update({'frozen_docc': [frozen_docc]}) opts.update({'ras1': [doccpi - frozen_docc]}) opts.update({'ras2': [soccpi]}) opts.update({'ras3': [nmo - soccpi - doccpi - frozen_uocc]}) opts.update({'frozen_uocc': [frozen_uocc]}) opts.update({'ras4': [0]}) elif (conf_space == "SDT"): opts.update({'frozen_docc': [0]}) opts.update({'ex_level': 3}) opts.update({'frozen_docc': [frozen_docc]}) opts.update({'ras1': [doccpi - frozen_docc]}) opts.update({'ras2': [soccpi]}) opts.update({'ras3': [nmo - soccpi - doccpi - frozen_uocc]}) opts.update({'frozen_uocc': [frozen_uocc]}) opts.update({'ras4': [0]}) # Other configuration spaces aren't supported yet else: print("Configuration space %s not supported. Exiting..." % conf_space) exit() # run cas print("RUNNING CAS...\t\tCHARGE %i\tMULT %i" % (mol.molecular_charge(), mol.multiplicity())) psi4.set_options(opts) e_cas, wfn_cas = psi4.energy('detci', ref_wfn=wfn_rohf, return_wfn=True, molecule=mol) print("CAS (%i %i): %6.12f" % (mol.molecular_charge(), mol.multiplicity(), e_cas)) # obtain eigenvectors if needed # partly based on Daniel Smith's answer on Psi4 forums if (write_ci_vects): wfn_cas_2 = psi4.core.CIWavefunction(wfn_rohf) n_roots = add_opts['NUM_ROOTS'] C = np.zeros((wfn_cas_2.ndet(), n_roots)) print(C.shape) for i in range(n_roots): dvec = wfn_cas_2.new_civector(i + 1, 53, True, True) dvec.set_nvec(i + 1) dvec.init_io_files(True) dvec.read(i, 0) C[:, i] = np.array(dvec) np.savetxt('ci_vect.txt', C) psi4.core.print_variables() # printing Psi4 variables psi4.core.clean_options() # more cleanup # return output specified by the user if ((not return_ci_wfn) and (not return_rohf_wfn) and (not return_rohf_e)): return e_cas else: out = (e_cas, ) if (return_ci_wfn): out = out + (wfn_cas, ) if (return_rohf_wfn): out = out + (wfn_rohf, ) if (return_rohf_e): out = out + (e_rohf, ) return out
# examples/api/05_casscf-doublet-guess.py """Example of a CASSCF computation on singlet methylene starting from doublet ROHF orbitals (from psi4)""" import psi4 import forte psi4.geometry(""" 1 2 C H 1 1.085 H 1 1.085 2 135.5 """) psi4.set_options({ 'basis': 'DZ', 'scf_type': 'pk', 'e_convergence': 12, 'reference': 'rohf' }) e, wfn = psi4.energy('scf', return_wfn=True) psi4.set_options({ 'forte__job_type': 'mcscf_two_step', 'forte__charge': 0, # <-- to override charge = +1 assumed from geometry 'forte__multiplicity': 1, # <-- to override multiplicity = 2 assumed from geometry 'forte__ms': 0, # <-- to override ms = 1/2 assumed from geometry 'forte__active_space_solver': 'fci', 'forte__restricted_docc': [1, 0, 0, 0], 'forte__active': [3, 0, 2, 2], })
def runner_asserter(inp, subject, method, basis, tnm): qc_module_in = "-".join(["psi4", inp["keywords"].get("qc_module", "") ]).strip("-") # returns "psi4"|"psi4-<module>" driver = inp["driver"] reference = inp["keywords"]["reference"] fcae = {"true": "fc", "false": "ae"}[inp["keywords"]["freeze_core"]] if qc_module_in == "psi4-detci" and basis != "cc-pvdz": pytest.skip(f"basis {basis} too big for {qc_module_in}") # <<< Reference Values >>> # ? precedence on next two scf_type = inp.get("corl_type", inp["keywords"].get( "scf_type", "df")) # hard-code of read_options.cc SCF_TYPE mp2_type = inp.get("corl_type", inp["keywords"].get( "mp2_type", "df")) # hard-code of read_options.cc MP2_TYPE if method in ["mp2.5", "mp3"]: mp_type = inp.get("corl_type", inp["keywords"].get( "mp_type", "df")) # hard-code of proc.py run_dfocc MP_TYPE else: mp_type = inp.get("corl_type", inp["keywords"].get( "mp_type", "conv")) # hard-code of read_options.cc MP_TYPE cc_type = inp.get("corl_type", inp["keywords"].get( "cc_type", "conv")) # hard-code of read_options.cc CC_TYPE corl_natural_values = { "hf": "df", # dummy to assure df/cd/conv scf_type refs available "mp2": mp2_type, "mp2.5": mp_type, "mp3": mp_type, "lccd": cc_type, "lccsd": cc_type, "ccsd": cc_type, "ccsd(t)": cc_type, "olccd": cc_type, } corl_type = corl_natural_values[method] natural_ref = {"conv": "pk", "df": "df", "cd": "cd"} scf_type = inp["keywords"].get("scf_type", natural_ref[corl_type]) natural_values = { "pk": "pk", "direct": "pk", "df": "df", "mem_df": "df", "disk_df": "df", "cd": "cd" } scf_type = natural_values[scf_type] atol = 1.0e-6 if driver == "hessian": atol = 2.0e-6 # todo implement more elaborate e/g/h atol like at qcdb & qcng: https://github.com/qcdb/qcdb/blob/master/qcdb/tests/standard_suite_runner.py#L144-L152 chash = answer_hash( system=subject.name(), basis=basis, fcae=fcae, scf_type=scf_type, reference=reference, corl_type=corl_type, ) # check all calcs against conventional reference to looser tolerance atol_conv = 3.0e-4 # for df-ccsd. mp2 ok with 1.e-4 chash_conv = answer_hash( system=subject.name(), basis=basis, fcae=fcae, reference=reference, corl_type="conv", scf_type="pk", ) ref_block_conv = std_suite[chash_conv] # <<< Prepare Calculation and Call API >>> driver_call = { "energy": psi4.energy, "gradient": psi4.gradient, "hessian": psi4.hessian } psi4.set_options({ # reference generation conv crit # "guess": "sad", # "e_convergence": 10, # "d_convergence": 9, # "r_convergence": 9, # "pcg_convergence": 9, # runtime conv crit "points": 5, "fd_project": False, }) extra_kwargs = inp["keywords"].pop("function_kwargs", {}) psi4.set_options(inp["keywords"]) if "error" in inp: errtype, errmsg = inp["error"] with pytest.raises(errtype) as e: driver_call[driver](inp["call"], molecule=subject, **extra_kwargs) assert errmsg in str(e.value), f"({errmsg}) not in ({e.value})" return ret, wfn = driver_call[driver](inp["call"], molecule=subject, return_wfn=True, **extra_kwargs) qc_module_out = "psi4-" + ("occ" if wfn.module() == "dfocc" else wfn.module()) # returns "psi4-<module>" # <<< Comparison Tests >>> if qc_module_in != "psi4": assert qc_module_out == qc_module_in, f"QC_MODULE used ({qc_module_in}) != requested ({qc_module_out})" ref_block = std_suite[chash] # qcvars contractual_args = [ qc_module_in, driver, reference, method, corl_type, fcae, ] asserter_args = [ [psi4.core, wfn], ref_block, atol, ref_block_conv, atol_conv, tnm, ] def qcvar_assertions(): print("BLOCK", chash, contractual_args) if method == "hf": _asserter(asserter_args, contractual_args, contractual_hf) elif method == "mp2": _asserter(asserter_args, contractual_args, contractual_mp2) elif method == "mp2.5": _asserter(asserter_args, contractual_args, contractual_mp2) _asserter(asserter_args, contractual_args, contractual_mp3) _asserter(asserter_args, contractual_args, contractual_mp2p5) elif method == "mp3": _asserter(asserter_args, contractual_args, contractual_mp2) _asserter(asserter_args, contractual_args, contractual_mp2p5) _asserter(asserter_args, contractual_args, contractual_mp3) elif method == "lccd": _asserter(asserter_args, contractual_args, contractual_mp2) _asserter(asserter_args, contractual_args, contractual_lccd) elif method == "lccsd": _asserter(asserter_args, contractual_args, contractual_mp2) _asserter(asserter_args, contractual_args, contractual_lccsd) elif method == "ccsd": _asserter(asserter_args, contractual_args, contractual_mp2) _asserter(asserter_args, contractual_args, contractual_ccsd) elif method == "ccsd(t)": _asserter(asserter_args, contractual_args, contractual_mp2) _asserter(asserter_args, contractual_args, contractual_ccsd) _asserter(asserter_args, contractual_args, contractual_ccsd_prt_pr) elif method == "olccd": _asserter(asserter_args, contractual_args, contractual_mp2) _asserter(asserter_args, contractual_args, contractual_olccd) if "wrong" in inp: errmsg, reason = inp["wrong"] with pytest.raises(AssertionError) as e: qcvar_assertions() # print("WRONG", errmsg, reason, str(e.value), "ENDW") assert errmsg in str(e.value) pytest.xfail(reason) qcvar_assertions() # aliases _asserter(asserter_args, contractual_args, contractual_current) # returns tf, errmsg = compare_values( ref_block[f"{method.upper()} TOTAL ENERGY"], wfn.energy(), tnm + " wfn", atol=atol, return_message=True, quiet=True, ) assert compare_values(ref_block[f"{method.upper()} TOTAL ENERGY"], wfn.energy(), tnm + " wfn", atol=atol), errmsg if driver == "energy": assert compare_values(ref_block[f"{method.upper()} TOTAL ENERGY"], ret, tnm + " return") elif driver == "gradient": assert compare_values(ref_block[f"{method.upper()} TOTAL GRADIENT"], wfn.gradient().np, tnm + " grad wfn", atol=atol) assert compare_values(ref_block[f"{method.upper()} TOTAL GRADIENT"], ret.np, tnm + " grad return", atol=atol) elif driver == "hessian": tf, errmsg = compare_values( ref_block[f"{method.upper()} TOTAL HESSIAN"], wfn.hessian().np, tnm + " hess wfn", atol=atol, return_message=True, quiet=True) assert compare_values(ref_block[f"{method.upper()} TOTAL HESSIAN"], wfn.hessian().np, tnm + " hess wfn", atol=atol), errmsg assert compare_values(ref_block[f"{method.upper()} TOTAL HESSIAN"], wfn.hessian().np, tnm + " hess wfn", atol=atol) assert compare_values(ref_block[f"{method.upper()} TOTAL GRADIENT"], wfn.gradient().np, tnm + " grad wfn", atol=atol) assert compare_values(ref_block[f"{method.upper()} TOTAL HESSIAN"], ret.np, tnm + " hess return", atol=atol) # generics # yapf: disable assert compare(ref_block["N BASIS FUNCTIONS"], wfn.nso(), tnm + " nbasis wfn"), f"nbasis {wfn.nso()} != {ref_block['N BASIS FUNCTIONS']}" assert compare(ref_block["N MOLECULAR ORBITALS"], wfn.nmo(), tnm + " nmo wfn"), f"nmo {wfn.nmo()} != {ref_block['N MOLECULAR ORBITALS']}" assert compare(ref_block["N ALPHA ELECTRONS"], wfn.nalpha(), tnm + " nalpha wfn"), f"nalpha {wfn.nalpha()} != {ref_block['N ALPHA ELECTRONS']}" assert compare(ref_block["N BETA ELECTRONS"], wfn.nbeta(), tnm + " nbeta wfn"), f"nbeta {wfn.nbeta()} != {ref_block['N BETA ELECTRONS']}"
# psi4.core.set_memory(int(2e9), False) psi4.core.set_output_file('output.dat', False) # Memory for numpy in GB numpy_memory = 2 mol = psi4.geometry(""" O H 1 1.1 H 1 1.1 2 104 symmetry c1 """) psi4.set_options({'basis': 'sto-3g', 'scf_type': 'pk', 'e_convergence': 1e-8, 'd_convergence': 1e-8}) print('\nStarting SCF and integral build...') t = time.time() # First compute SCF energy using Psi4 scf_e, wfn = psi4.energy('SCF', return_wfn=True) # Grab data from wavfunction class C = wfn.Ca() ndocc = wfn.doccpi()[0] nmo = wfn.nmo() nvirt = nmo - ndocc nDet_S = ndocc * nvirt * 2
self.T3onT2 = self.T3onT2 + np.einsum('ijab -> jiba', self.T3onT2) ## Contribution of disconnected T3*T1 terms to T2 equations via relax_t3t1ont2 function. self.relax_t3t1ont2() print('T3') printtensor(self.T3) if __name__ == '__main__': mol = psi4.geometry(""" 0 1 O H 1 0.96 H 1 0.96 2 104.5 symmetry c1""") mol.update_geometry() psi4.set_options({ 'basis': 'sto-3g', 'scf_type': 'pk', 'FCI': True, 'reference': 'rhf' }) E, wfn = psi4.energy('detci', return_wfn=True) CASCCSD(wfn) print(E)
import psi4 psi4.set_output_file("output.dat", False) # Benzene mol = psi4.geometry(""" 0 1 O H 1 1.1 H 1 1.1 2 104 symmetry c1 """) psi4.set_options({ "basis": "aug-cc-pVDZ", "scf_type": "df", "e_convergence": 1e-8 }) # Set tolerances maxiter = 12 E_conv = 1.0E-6 D_conv = 1.0E-5 # Integral generation from Psi4's MintsHelper wfn = psi4.core.Wavefunction.build(mol, psi4.core.get_global_option("BASIS")) mints = psi4.core.MintsHelper(wfn.basisset()) S = mints.ao_overlap() # Get nbf and ndocc for closed shell molecules nbf = wfn.nso()
S 1 1.00 0.1831920 1.0000000 **** C 0 S 3 1.00 172.2560000 0.0617669 25.9109000 0.3587940 5.5333500 0.7007130 SP 2 1.00 3.6649800 -0.3958970 0.2364600 0.7705450 1.2158400 0.8606190 SP 1 1.00 0.1958570 1.0000000 1.0000000 **** [DZ] spherical **** H 0 S 3 1.00 19.2406000 0.0328280 2.8992000 0.2312080 0.6534000 0.8172380 S 1 1.00 0.1776000 1.0000000 **** """) psi4.set_options({'d_convergence': 11, 'e_convergence': 11, 'scf_type': 'pk'}) scfenergy = psi4.energy('scf')
def test_geometric_hessian_rhf_outside_solver_psi4numpy(): psi4.core.set_output_file("output.dat", False) mol = psi4.geometry( """ O H 1 1.1 H 1 1.1 2 104 symmetry c1 """ ) psi4.core.set_active_molecule(mol) options = { "BASIS": "STO-3G", "SCF_TYPE": "PK", "E_CONVERGENCE": 1e-10, "D_CONVERGENCE": 1e-10, } psi4.set_options(options) _, wfn = psi4.energy("SCF", return_wfn=True) # Assuming C1 symmetry occ = wfn.doccpi()[0] nmo = wfn.nmo() vir = nmo - occ C = wfn.Ca_subset("AO", "ALL") npC = np.asarray(C) mints = psi4.core.MintsHelper(wfn.basisset()) H_ao = np.asarray(mints.ao_kinetic()) + np.asarray(mints.ao_potential()) # Update H, transform to MO basis H = np.einsum("uj,vi,uv", npC, npC, H_ao) # Integral generation from Psi4's MintsHelper MO = np.asarray(mints.mo_eri(C, C, C, C)) # Physicist notation MO = MO.swapaxes(1, 2) F = H + 2.0 * np.einsum("pmqm->pq", MO[:, :occ, :, :occ]) F -= np.einsum("pmmq->pq", MO[:, :occ, :occ, :]) # Uncomment every `np.save` call to regenerate reference data. # np.save(os.path.join(datadir, 'F.npy'), F) F_ref = np.load(os.path.join(datadir, "F.npy")) np.testing.assert_allclose(F, F_ref, rtol=0, atol=1.0e-10) natoms = mol.natom() cart = ["_X", "_Y", "_Z"] oei_dict = {"S": "OVERLAP", "T": "KINETIC", "V": "POTENTIAL"} deriv1_mat = {} deriv1 = {} # 1st Derivative of OEIs for atom in range(natoms): for key in oei_dict: deriv1_mat[key + str(atom)] = mints.mo_oei_deriv1(oei_dict[key], atom, C, C) for p in range(3): map_key = key + str(atom) + cart[p] deriv1[map_key] = np.asarray(deriv1_mat[key + str(atom)][p]) # np.save(os.path.join(datadir, f'{map_key}.npy'), deriv1[map_key]) deriv1_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose(deriv1[map_key], deriv1_ref, rtol=0, atol=1.0e-10) # 1st Derivative of TEIs for atom in range(natoms): string = "TEI" + str(atom) deriv1_mat[string] = mints.mo_tei_deriv1(atom, C, C, C, C) for p in range(3): map_key = string + cart[p] deriv1[map_key] = np.asarray(deriv1_mat[string][p]) # np.save(os.path.join(datadir, f'{map_key}.npy'), deriv1[map_key]) deriv1_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose(deriv1[map_key], deriv1_ref, rtol=0, atol=1.0e-10) Hes = {} deriv2_mat = {} deriv2 = {} Hes["S"] = np.zeros((3 * natoms, 3 * natoms)) Hes["V"] = np.zeros((3 * natoms, 3 * natoms)) Hes["T"] = np.zeros((3 * natoms, 3 * natoms)) Hes["N"] = np.zeros((3 * natoms, 3 * natoms)) Hes["J"] = np.zeros((3 * natoms, 3 * natoms)) Hes["K"] = np.zeros((3 * natoms, 3 * natoms)) Hes["R"] = np.zeros((3 * natoms, 3 * natoms)) Hessian = np.zeros((3 * natoms, 3 * natoms)) Hes["N"] = np.asarray(mol.nuclear_repulsion_energy_deriv2()) psi4.core.print_out("\n\n") Mat = psi4.core.Matrix.from_array(Hes["N"]) Mat.name = "NUCLEAR HESSIAN" Mat.print_out() # 2nd Derivative of OEIs for atom1 in range(natoms): for atom2 in range(atom1 + 1): for key in oei_dict: string = key + str(atom1) + str(atom2) deriv2_mat[string] = mints.mo_oei_deriv2(oei_dict[key], atom1, atom2, C, C) pq = 0 for p in range(3): for q in range(3): map_key = string + cart[p] + cart[q] deriv2[map_key] = np.asarray(deriv2_mat[string][pq]) # np.save(os.path.join(datadir, f'{map_key}.npy'), deriv2[map_key]) deriv2_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose( deriv2[map_key], deriv2_ref, rtol=0, atol=1.0e-10 ) pq = pq + 1 row = 3 * atom1 + p col = 3 * atom2 + q if key == "S": Hes[key][row][col] = -2.0 * np.einsum( "ii,ii->", F[:occ, :occ], deriv2[map_key][:occ, :occ] ) else: Hes[key][row][col] = 2.0 * np.einsum( "ii->", deriv2[map_key][:occ, :occ] ) Hes[key][col][row] = Hes[key][row][col] Hes[key][col][row] = Hes[key][row][col] # np.save(os.path.join(datadir, f'Hes_{map_key}.npy'), Hes[key]) Hes_ref = np.load(os.path.join(datadir, f"Hes_{map_key}.npy")) np.testing.assert_allclose(Hes[key], Hes_ref, rtol=0, atol=1.0e-10) for key in Hes: Mat = psi4.core.Matrix.from_array(Hes[key]) if key in oei_dict: Mat.name = oei_dict[key] + " HESSIAN" Mat.print_out() psi4.core.print_out("\n") # 2nd Derivative of TEIs for atom1 in range(natoms): for atom2 in range(atom1 + 1): string = "TEI" + str(atom1) + str(atom2) deriv2_mat[string] = mints.mo_tei_deriv2(atom1, atom2, C, C, C, C) pq = 0 for p in range(3): for q in range(3): map_key = string + cart[p] + cart[q] deriv2[map_key] = np.asarray(deriv2_mat[string][pq]) # np.save(os.path.join(datadir, f'{map_key}.npy'), deriv2[map_key]) deriv2_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose(deriv2[map_key], deriv2_ref, rtol=0, atol=1.0e-10) pq = pq + 1 row = 3 * atom1 + p col = 3 * atom2 + q Hes["J"][row][col] = 2.0 * np.einsum( "iijj->", deriv2[map_key][:occ, :occ, :occ, :occ] ) Hes["K"][row][col] = -1.0 * np.einsum( "ijij->", deriv2[map_key][:occ, :occ, :occ, :occ] ) Hes["J"][col][row] = Hes["J"][row][col] Hes["K"][col][row] = Hes["K"][row][col] for map_key in ("J", "K"): # np.save(os.path.join(datadir, f'Hes_{map_key}.npy'), Hes[map_key]) Hes_ref = np.load(os.path.join(datadir, f"Hes_{map_key}.npy")) np.testing.assert_allclose(Hes[map_key], Hes_ref, rtol=0, atol=1.0e-10) JMat = psi4.core.Matrix.from_array(Hes["J"]) KMat = psi4.core.Matrix.from_array(Hes["K"]) JMat.name = " COULOMB HESSIAN" KMat.name = " EXCHANGE HESSIAN" JMat.print_out() KMat.print_out() # Solve the CPHF equations here, G_aibj Ubj^x = Bai^x (Einstein summation), # where G is the electronic hessian, # G_aibj = delta_ij * delta_ab * epsilon_ij * epsilon_ab + 4 <ij|ab> - <ij|ba> - <ia|jb>, # where epsilon_ij = epsilon_i - epsilon_j, (epsilon -> orbital energies), # x refers to the perturbation, Ubj^x are the corresponsing CPHF coefficients # and Bai^x = Sai^x * epsilon_ii - Fai^x + Smn^x * (2<am|in> - <am|ni>), # where, S^x = del(S)/del(x), F^x = del(F)/del(x). I_occ = np.diag(np.ones(occ)) I_vir = np.diag(np.ones(vir)) epsilon = np.asarray(wfn.epsilon_a()) eps_diag = epsilon[occ:].reshape(-1, 1) - epsilon[:occ] # Build the electronic hessian G G = 4 * MO[:occ, :occ, occ:, occ:] G -= MO[:occ, :occ, occ:, occ:].swapaxes(2, 3) G -= MO[:occ, occ:, :occ, occ:].swapaxes(1, 2) G = G.swapaxes(1, 2) G += np.einsum("ai,ij,ab->iajb", eps_diag, I_occ, I_vir) # np.save(os.path.join(datadir, 'G.npy'), G) G_ref = np.load(os.path.join(datadir, "G.npy")) np.testing.assert_allclose(G, G_ref, rtol=0, atol=1.0e-10) # Inverse of G Ginv = np.linalg.inv(G.reshape(occ * vir, -1)) Ginv = Ginv.reshape(occ, vir, occ, vir) B = {} F_grad = {} U = {} # Build Fpq^x now for atom in range(natoms): for p in range(3): key = str(atom) + cart[p] F_grad[key] = deriv1["T" + key] F_grad[key] += deriv1["V" + key] F_grad[key] += 2.0 * np.einsum("pqmm->pq", deriv1["TEI" + key][:, :, :occ, :occ]) F_grad[key] -= 1.0 * np.einsum("pmmq->pq", deriv1["TEI" + key][:, :occ, :occ, :]) # np.save(os.path.join(datadir, f'F_grad_{key}.npy'), F_grad[key]) F_grad_ref = np.load(os.path.join(datadir, f"F_grad_{key}.npy")) np.testing.assert_allclose(F_grad[key], F_grad_ref, rtol=0, atol=1.0e-10) psi4.core.print_out("\n\n CPHF Coefficients:\n") # Build Bai^x now for atom in range(natoms): for p in range(3): key = str(atom) + cart[p] B[key] = np.einsum("ai,ii->ai", deriv1["S" + key][occ:, :occ], F[:occ, :occ]) B[key] -= F_grad[key][occ:, :occ] B[key] += 2.0 * np.einsum( "amin,mn->ai", MO[occ:, :occ, :occ, :occ], deriv1["S" + key][:occ, :occ] ) B[key] += -1.0 * np.einsum( "amni,mn->ai", MO[occ:, :occ, :occ, :occ], deriv1["S" + key][:occ, :occ] ) print(f"B[{key}]") print(B[key]) # np.save(os.path.join(datadir, f'B_{key}.npy'), B[key]) B_ref = np.load(os.path.join(datadir, f"B_{key}.npy")) np.testing.assert_allclose(B[key], B_ref, rtol=0, atol=1.0e-10) # Compute U^x now: U_ai^x = G^(-1)_aibj * B_bj^x U[key] = np.einsum("iajb,bj->ai", Ginv, B[key]) psi4.core.print_out("\n") UMat = psi4.core.Matrix.from_array(U[key]) UMat.name = key UMat.print_out() # np.save(os.path.join(datadir, f'U_{key}.npy'), U[key]) U_ref = np.load(os.path.join(datadir, f"U_{key}.npy")) np.testing.assert_allclose(U[key], U_ref, rtol=0, atol=1.0e-10) # Build the response Hessian for atom1 in range(natoms): for atom2 in range(atom1 + 1): for p in range(3): for q in range(3): key1 = str(atom1) + cart[p] key2 = str(atom2) + cart[q] key1S = "S" + key1 key2S = "S" + key2 r = 3 * atom1 + p c = 3 * atom2 + q Hes["R"][r][c] = -2.0 * np.einsum( "ij,ij->", deriv1[key1S][:occ, :occ], F_grad[key2][:occ, :occ] ) Hes["R"][r][c] -= 2.0 * np.einsum( "ij,ij->", deriv1[key2S][:occ, :occ], F_grad[key1][:occ, :occ] ) Hes["R"][r][c] += 4.0 * np.einsum( "ii,mi,mi->", F[:occ, :occ], deriv1[key2S][:occ, :occ], deriv1[key1S][:occ, :occ], ) Hes["R"][r][c] += 4.0 * np.einsum( "ij,mn,imjn->", deriv1[key1S][:occ, :occ], deriv1[key2S][:occ, :occ], MO[:occ, :occ, :occ, :occ], ) Hes["R"][r][c] -= 2.0 * np.einsum( "ij,mn,imnj->", deriv1[key1S][:occ, :occ], deriv1[key2S][:occ, :occ], MO[:occ, :occ, :occ, :occ], ) Hes["R"][r][c] -= 4.0 * np.einsum("ai,ai->", U[key2], B[key1]) Hes["R"][c][r] = Hes["R"][r][c] # np.save(os.path.join(datadir, 'Hes_R.npy'), Hes["R"]) Hes_ref = np.load(os.path.join(datadir, "Hes_R.npy")) np.testing.assert_allclose(Hes["R"], Hes_ref, rtol=0, atol=1.0e-10) Mat = psi4.core.Matrix.from_array(Hes["R"]) Mat.name = " RESPONSE HESSIAN" Mat.print_out() for key in Hes: Hessian += Hes[key] # print('deriv1_mat') # print(deriv1_mat.keys()) # print('deriv1') # print(deriv1.keys()) # print('deriv2_mat') # print(deriv2_mat.keys()) # print('deriv2') # print(deriv2.keys()) # print('B') # print(B.keys()) # print('F_grad') # print(F_grad.keys()) # print('U') # print(U.keys()) # print('Hes') # print(Hes.keys()) Mat = psi4.core.Matrix.from_array(Hessian) Mat.name = " TOTAL HESSIAN" Mat.print_out() # pylint: disable=bad-whitespace H_psi4 = psi4.core.Matrix.from_list( [ [ 7.613952269164418751e-02, 0.000000000000000000e00, 0.000000000000000000e00, -3.806976134297335168e-02, 0.000000000000000000e00, 0.000000000000000000e00, -3.806976134297410108e-02, 0.000000000000000000e00, 0.000000000000000000e00, ], [ 0.000000000000000000e00, 4.829053723748517601e-01, 0.000000000000000000e00, 0.000000000000000000e00, -2.414526861845633920e-01, 1.589001558536450587e-01, 0.000000000000000000e00, -2.414526861845646133e-01, -1.589001558536444758e-01, ], [ 0.000000000000000000e00, 0.000000000000000000e00, 4.373449597848400039e-01, 0.000000000000000000e00, 7.344233774055003439e-02, -2.186724798895446076e-01, 0.000000000000000000e00, -7.344233774054893804e-02, -2.186724798895475219e-01, ], [ -3.806976134297335168e-02, 0.000000000000000000e00, 0.000000000000000000e00, 4.537741758645107149e-02, 0.000000000000000000e00, 0.000000000000000000e00, -7.307656243475501093e-03, 0.000000000000000000e00, 0.000000000000000000e00, ], [ 0.000000000000000000e00, -2.414526861845633920e-01, 7.344233774055003439e-02, 0.000000000000000000e00, 2.578650065921952450e-01, -1.161712467970963669e-01, 0.000000000000000000e00, -1.641232040762596878e-02, 4.272890905654690846e-02, ], [ 0.000000000000000000e00, 1.589001558536450587e-01, -2.186724798895446076e-01, 0.000000000000000000e00, -1.161712467970963669e-01, 1.977519807685419462e-01, 0.000000000000000000e00, -4.272890905654720684e-02, 2.092049912100946499e-02, ], [ -3.806976134297410108e-02, 0.000000000000000000e00, 0.000000000000000000e00, -7.307656243475501093e-03, 0.000000000000000000e00, 0.000000000000000000e00, 4.537741758645268131e-02, 0.000000000000000000e00, 0.000000000000000000e00, ], [ 0.000000000000000000e00, -2.414526861845646133e-01, -7.344233774054893804e-02, 0.000000000000000000e00, -1.641232040762596878e-02, -4.272890905654720684e-02, 0.000000000000000000e00, 2.578650065921969103e-01, 1.161712467970957008e-01, ], [ 0.000000000000000000e00, -1.589001558536444758e-01, -2.186724798895475219e-01, 0.000000000000000000e00, 4.272890905654690846e-02, 2.092049912100946499e-02, 0.000000000000000000e00, 1.161712467970957008e-01, 1.977519807685442221e-01, ], ] ) H_python_mat = psi4.core.Matrix.from_array(Hessian) psi4.compare_matrices(H_psi4, H_python_mat, 10, "RHF-HESSIAN-TEST") # TEST
def test_erd(): """erd/scf5""" psi4.set_options({'integral_package': 'ERD'}) _test_scf5()
# O 0.0000000000 0.0000000000 2.3054658725 # H 1.7822044879 0.0000000000 -1.0289558751 # H -1.7822044879 0.0000000000 -1.0289558751 # C 0.0000000000 0.0000000000 0.0000000000 # symmetry c1 # """) mol = psi4.geometry(""" O 0.000000000000 -0.143225816552 0.000000000000 H 1.638036840407 1.136548822547 -0.000000000000 H -1.638036840407 1.136548822547 -0.000000000000 units bohr symmetry c1 """) psi4.set_options({"SAVE_JK": True, 'scf_type': 'pk', 'd_convergence': 10}) e, wfn = psi4.energy("HF/sto-3g", return_wfn=True) prod = AB_product_factory(wfn) F_ako = prod.mFa.to_array() C = prod.mCa.to_array() Fmo = (C.T).dot(F_ao).dot(C) F_ij = Fmo[prod.o, prod.o] F_ab = Fmo[prod.v, prod.v] print("F_ij: ", " x ".join(str(x) for x in F_ij.shape)) print("") print("F_ab: ", " x ".join(str(x) for x in F_ab.shape)) Iiajb = prod.mints.mo_eri(prod.mCa_occ, prod.mCa_virt, prod.mCa_occ, prod.mCa_virt).to_array() Iabji = prod.mints.mo_eri(prod.mCa_virt, prod.mCa_virt, prod.mCa_occ, prod.mCa_occ).to_array() A = np.einsum("ab,ij->iajb", F_ab, np.eye(prod.nocc)) A -= np.einsum("ij,ab->iajb", F_ij, np.eye(prod.nvir))
def test_chk(datadir): # run cc psi4.set_memory('600MB') psi4.core.set_output_file('output.dat', False) psi4.set_options({'basis': 'cc-pVDZ', 'scf_type': 'pk', 'mp2_type': 'conv', 'freeze_core': 'false', 'e_convergence': 1e-8, 'd_convergence': 1e-8, 'r_convergence': 1e-8, 'diis': 8}) mol = psi4.geometry(moldict["H2"]) # pull ref wfn, psi4 is picky about strings rhf_dir = str(datadir.join(f"ref_wfn.npy")) rhf_wfn = psi4.core.Wavefunction.from_file(rhf_dir) e_conv = 1e-8 r_conv = 1e-8 cc = pycc.ccwfn(rhf_wfn) ecc = cc.solve_cc(e_conv, r_conv) hbar = pycc.cchbar(cc) cclambda = pycc.cclambda(cc, hbar) lecc = cclambda.solve_lambda(e_conv, r_conv) ccdensity = pycc.ccdensity(cc, cclambda) # narrow Gaussian pulse F_str = 0.001 sigma = 0.01 center = 0.05 V = gaussian_laser(F_str, 0, sigma, center=center) # RTCC setup h = 0.1 tf = 10 rtcc = pycc.rtcc(cc,cclambda,ccdensity,V,magnetic=True,kick='z') # pull chk files for 0-5.1au chk_file = datadir.join(f"chk_5.pk") with open(chk_file,'rb') as cf: chk = pk.load(cf) # propagate to 10au ODE = rk2(h) y0 = chk['y'] ti = chk['time'] ofile = datadir.join(f"output.pk") tfile = datadir.join(f"t_out.pk") ret, ret_t = rtcc.propagate(ODE, y0, tf, ti=ti, ref=False, chk=True, tchk=1, ofile=ofile, tfile=tfile, k=2) # reference is "full" propagation (0-10au) refp_file = datadir.join(f"output_full.pk") with open(refp_file,'rb') as pf: ref_p = pk.load(pf) reft_file = datadir.join(f"t_out_full.pk") with open(reft_file,'rb') as ampf: ref_t = pk.load(ampf) # check properties pchk = ['ecc','mu_x','mu_y','mu_z','m_x','m_y','m_z'] for k in ref_p.keys(): for p in pchk: assert np.allclose(ret[k][p],ref_p[k][p]) # check amplitudes tchk = ['t1','t2','l1','l2'] for k in ref_t.keys(): for t in tchk: assert np.allclose(ret_t[k][t],ref_t[k][t])
H 45.508000 40.786000 39.175000 H 43.151000 37.062000 37.180000 H 40.929000 35.954000 37.704000 H 39.378000 37.062000 39.158000 H 40.246000 38.878000 40.859000 symmetry c1 no_com noreorient """) nroots = 3 psi4.set_options({ "basis": "6-31G*", "freeze_core": "true", "roots_per_irrep": [nroots], "pe": "true", "ints_tolerance": 2.5e-11, "puream": "true", }) psi4.set_module_options("pe", { "potfile": "nilered_in_blg_1000WAT.pot", "maxiter": 200 }) psi4.set_module_options("ccenergy", {"cachelevel": 0}) psi4.set_module_options("cclambda", {"r_convergence": 1e-3, "cachelevel": 0}) psi4.set_module_options("cceom", { "cachelevel": 0, "r_convergence": 1e-3,
def test_rtcc_water_cc_pvdz(): """H2O cc-pVDZ""" psi4.set_memory('2 GiB') psi4.core.set_output_file('output.dat', False) psi4.set_options({ 'basis': 'cc-pVDZ', 'scf_type': 'pk', 'mp2_type': 'conv', 'freeze_core': 'false', 'e_convergence': 1e-13, 'd_convergence': 1e-13, 'r_convergence': 1e-13, 'diis': 1 }) mol = psi4.geometry(moldict["H2O"]) rhf_e, rhf_wfn = psi4.energy('SCF', return_wfn=True) e_conv = 1e-13 r_conv = 1e-13 cc = pycc.ccwfn(rhf_wfn) ecc = cc.solve_cc(e_conv, r_conv) hbar = pycc.cchbar(cc) cclambda = pycc.cclambda(cc, hbar) lecc = cclambda.solve_lambda(e_conv, r_conv) ccdensity = pycc.ccdensity(cc, cclambda) # Gaussian pulse (a.u.) F_str = 0.01 omega = 0 sigma = 0.01 center = 0.05 V = gaussian_laser(F_str, omega, sigma, center) # RT-CC Setup t0 = 0 tf = 1 h = 0.01 t = t0 rtcc = pycc.rtcc(cc, cclambda, ccdensity, V) y0 = rtcc.collect_amps(cc.t1, cc.t2, cclambda.l1, cclambda.l2).astype('complex128') y = y0 # Setting for the adaptive integrator maxiter = 10 yconv = 1e-7 ODE = ck(maxiter, yconv) t1, t2, l1, l2 = rtcc.extract_amps(y0) mu0_x, mu0_y, mu0_z = rtcc.dipole(t1, t2, l1, l2) ecc0 = rtcc.lagrangian(t0, t1, t2, l1, l2) # For saving data at each time step. """ dip_x = [] dip_y = [] dip_z = [] time_points = [] dip_x.append(mu0_x) dip_y.append(mu0_y) dip_z.append(mu0_z) time_points.append(t) """ while t < tf: (y, h_old, h) = ODE(rtcc.f, t, y, h) t += h_old t1, t2, l1, l2 = rtcc.extract_amps(y) mu_x, mu_y, mu_z = rtcc.dipole(t1, t2, l1, l2) ecc = rtcc.lagrangian(t, t1, t2, l1, l2) """ dip_x.append(mu_x) dip_y.append(mu_y) dip_z.append(mu_z) time_points.append(t) """ print(mu_z) mu_z_ref = -0.34894577 assert (abs(mu_z_ref - mu_z.real) < 1e-3)
def test_simint(): """simint/scf5""" psi4.set_options({'integral_package': 'simint'}) _test_scf5()
def test_geometric_hessian_rhf_right_hand_side(): mol = molecules.molecule_physicists_water_sto3g() mol.reset_point_group("c1") mol.update_geometry() psi4.core.set_active_molecule(mol) options = { "BASIS": "STO-3G", "SCF_TYPE": "PK", "E_CONVERGENCE": 1e-10, "D_CONVERGENCE": 1e-10, } psi4.set_options(options) _, wfn = psi4.energy("hf", return_wfn=True) occupations = occupations_from_psi4wfn(wfn) nocc, nvir, _, _ = occupations norb = nocc + nvir o = slice(0, nocc) v = slice(nocc, norb) C = wfn.Ca_subset("AO", "ALL") npC = np.asarray(C) mints = psi4.core.MintsHelper(wfn) T = np.asarray(mints.ao_kinetic()) V = np.asarray(mints.ao_potential()) H_ao = T + V H = np.einsum("up,vq,uv->pq", npC, npC, H_ao) MO = np.asarray(mints.mo_eri(C, C, C, C)) F = H + 2.0 * np.einsum("pqii->pq", MO[:, :, o, o]) F -= np.einsum("piqi->pq", MO[:, o, :, o]) F_ref = np.load(os.path.join(datadir, "F.npy")) np.testing.assert_allclose(F, F_ref, rtol=0, atol=1.0e-10) natoms = mol.natom() cart = ["_X", "_Y", "_Z"] oei_dict = {"S": "OVERLAP", "T": "KINETIC", "V": "POTENTIAL"} deriv1 = dict() # 1st Derivative of OEIs for atom in range(natoms): for key in oei_dict: deriv1_mat = mints.mo_oei_deriv1(oei_dict[key], atom, C, C) for p in range(3): map_key = key + str(atom) + cart[p] deriv1[map_key] = np.asarray(deriv1_mat[p]) deriv1_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose(deriv1[map_key], deriv1_ref, rtol=0, atol=1.0e-10) # 1st Derivative of TEIs for atom in range(natoms): string = "TEI" + str(atom) deriv1_mat = mints.mo_tei_deriv1(atom, C, C, C, C) for p in range(3): map_key = string + cart[p] deriv1[map_key] = np.asarray(deriv1_mat[p]) deriv1_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose(deriv1[map_key], deriv1_ref, rtol=0, atol=1.0e-10) # B_ia^x = S_ia^x * epsilon_ii - F_ia^x + S_mn^x * [2(ia|mn) - (in|ma)] F_grad = dict() B = dict() # Build F_pq^x now for atom in range(natoms): for p in range(3): key = str(atom) + cart[p] F_grad[key] = deriv1["T" + key] F_grad[key] += deriv1["V" + key] F_grad[key] += 2.0 * np.einsum("pqmm->pq", deriv1["TEI" + key][:, :, o, o]) F_grad[key] -= 1.0 * np.einsum("pmmq->pq", deriv1["TEI" + key][:, o, o, :]) F_grad_ref = np.load(os.path.join(datadir, f"F_grad_{key}.npy")) np.testing.assert_allclose(F_grad[key], F_grad_ref, rtol=0, atol=1.0e-10) # Build B_ia^x now for atom in range(natoms): for p in range(3): key = str(atom) + cart[p] B[key] = np.einsum("ia,ii->ia", deriv1["S" + key][o, v], F[o, o]) B[key] -= F_grad[key][o, v] B[key] += 2.0 * np.einsum("iamn,mn->ia", MO[o, v, o, o], deriv1["S" + key][o, o]) B[key] += -1.0 * np.einsum("inma,mn->ia", MO[o, o, o, v], deriv1["S" + key][o, o]) B_ref = np.load(os.path.join(datadir, f"B_{key}.npy")) np.testing.assert_allclose(B[key], B_ref.T, rtol=0, atol=1.0e-10) from pyresponse.integrals import _form_rhs_geometric B_func = _form_rhs_geometric(npC, occupations, natoms, MO, mints) assert B_func.keys() == B.keys() for k in B_func: np.testing.assert_allclose(B_func[k], B[k], rtol=0, atol=1.0e-12) return B_func
#! that symmetry of the Molecule observes the basis assignment to atoms. # cc-pvdz aug-cc-pvdz # BASIS H 5/ 5 C 14/15 H +4/ 4 C +9/10 # RIFIT H 14/15 C 56/66 H +9/10 C +16/20 # JKFIT H 23/25 C 70/81 H +9/10 C +16/20 mymol = psi4.geometry(""" C 0.0 0.0 0.0 O 1.4 0.0 0.0 H_r -0.5 -0.7 0.0 H_l -0.5 0.7 0.0 """) psi4.set_options({'basis': 'cc-pvdz'}) print('[1] <<< uniform cc-pVDZ >>>') wert = psi4.core.BasisSet.build(mymol, 'BASIS', psi4.core.get_global_option('BASIS')) psi4.compare_strings('CC-PVDZ', psi4.core.get_global_option('BASIS'), 'name') #TEST psi4.compare_integers(38, wert.nbf(), 'nbf()') #TEST psi4.compare_integers(40, wert.nao(), 'nao()') #TEST psi4.compare_strings('c2v', mymol.schoenflies_symbol(), 'symm') #TEST psi4.compare_strings('CC-PVDZ', wert.name(), 'callby') #TEST psi4.compare_strings('CC-PVDZ', wert.blend(), 'blend') #TEST mymol.print_out() print('[2] <<< RIFIT (default) >>>') wert = psi4.core.BasisSet.build(mymol, 'DF_BASIS_MP2', '', 'RIFIT', psi4.core.get_global_option('BASIS')) psi4.compare_integers(140, wert.nbf(), 'nbf()') #TEST
def test_atomic_polar_tensor_rhf(): mol = molecules.molecule_physicists_water_sto3g() mol.reset_point_group("c1") mol.update_geometry() psi4.core.set_active_molecule(mol) options = { "BASIS": "STO-3G", "SCF_TYPE": "PK", "E_CONVERGENCE": 1e-10, "D_CONVERGENCE": 1e-10, } psi4.set_options(options) _, wfn = psi4.energy("hf", return_wfn=True) mints = psi4.core.MintsHelper(wfn) C = mocoeffs_from_psi4wfn(wfn) E = moenergies_from_psi4wfn(wfn) occupations = occupations_from_psi4wfn(wfn) nocc, nvir, _, _ = occupations norb = nocc + nvir # electric perturbation part ao2mo = AO2MO(C, occupations, I=np.asarray(mints.ao_eri())) ao2mo.perform_rhf_full() solver = ExactInv(C, E, occupations) solver.tei_mo = ao2mo.tei_mo solver.tei_mo_type = AO2MOTransformationType.full driver = CPHF(solver) operator_diplen = Operator( label="dipole", is_imaginary=False, is_spin_dependent=False, triplet=False ) # integrals_diplen_ao = self.pyscfmol.intor('cint1e_r_sph', comp=3) M = np.stack([np.asarray(Mc) for Mc in mints.ao_dipole()]) operator_diplen.ao_integrals = M driver.add_operator(operator_diplen) # geometric perturbation part operator_geometric = Operator( label="nuclear", is_imaginary=False, is_spin_dependent=False, triplet=False ) operator_geometric.form_rhs_geometric(C, occupations, mol.natom(), solver.tei_mo[0], mints) print(operator_geometric.label) print(operator_geometric.mo_integrals_ai_alph) print(operator_diplen.label) print(operator_diplen.mo_integrals_ai_alph) # hack for dim check in solver operator_geometric.ao_integrals = np.zeros((3 * mol.natom(), M.shape[1], M.shape[2])) # bypass driver's call to form_rhs driver.solver.operators.append(operator_geometric) driver.run( hamiltonian=Hamiltonian.RPA, spin=Spin.singlet, program=Program.Psi4, program_obj=wfn, ) print(driver.results[0]) print(driver.results[0].T) print(driver.results[0] - driver.results[0].T) print(operator_geometric.rspvecs_alph[0]) # Nuclear contribution to dipole gradient # Electronic contributions to static part of dipole gradient # Reorthonormalization part of dipole gradient # Static contribution to dipole gradient # Relaxation part of dipole gradient # Total dipole gradient - TRAROT print("Nuclear contribution to dipole gradient") natom = mol.natom() Z = np.asarray([mol.Z(i) for i in range(natom)]) nuclear_contrib = np.concatenate([np.diag(Z.take(3 * [i])) for i in range(natom)]) print(nuclear_contrib) return locals()
def test_unrestricted_RPA_C1(): ch2 = psi4.geometry(""" 0 3 c h 1 1.0 h 1 1.0 2 125.0 symmetry c1 """) psi4.set_options({"scf_type": "pk", 'reference': 'UHF', 'save_jk': True}) e, wfn = psi4.energy("hf/cc-pvdz", molecule=ch2, return_wfn=True) A_ref, B_ref = build_UHF_AB_C1(wfn) nI, nA, _, _ = A_ref['IAJB'].shape nIA = nI * nA ni, na, _, _ = A_ref['iajb'].shape nia = ni * na P_ref = {k: A_ref[k] + B_ref[k] for k in A_ref.keys()} M_ref = {k: A_ref[k] - B_ref[k] for k in A_ref.keys()} eng = TDUSCFEngine(wfn, ptype='rpa') X_jb = [ psi4.core.Matrix.from_array(v.reshape((ni, na))) for v in tuple(np.eye(nia).T) ] zero_jb = [psi4.core.Matrix(ni, na) for x in range(nIA)] X_JB = [ psi4.core.Matrix.from_array(v.reshape((nI, nA))) for v in tuple(np.eye(nIA).T) ] zero_JB = [psi4.core.Matrix(nI, nA) for x in range(nia)] # Guess Identity: # X_I0 X_0I = X_I0 X_0I # [ I{nOV x nOV} | 0{nOV x nov}] = [ X{KC,JB} | 0{KC, jb}] # [ 0{nov x nOV} | I{nov x nov}] [ 0{kc,JB} | X{kc, jb}] # Products: # [ A+/-B{IA, KC} A+/-B{IA, kc}] [ I{KC, JB} | 0{KC,jb}] = [A+/-B x X_I0] = [ (A+/-B)_IAJB, (A+/-B)_iaJB] # [ A+/-B{ia, KC} A+/-B{ia, kc}] [ O{kc, JB} | X{kc,jb}] [A+/-B x X_0I] = [ (A+/-B)_IAjb, (A+/-B)_iajb] X_I0 = [[x, zero] for x, zero in zip(X_JB, zero_jb)] X_0I = [[zero, x] for zero, x in zip(zero_JB, X_jb)] Px_I0, Mx_I0 = eng.compute_products(X_I0)[:-1] Px_0I, Mx_0I = eng.compute_products(X_0I)[:-1] P_IAJB_test = np.column_stack([x[0].to_array().flatten() for x in Px_I0]) assert compare_arrays(P_ref['IAJB'].reshape(nIA, nIA), P_IAJB_test, 8, "A_IAJB") M_IAJB_test = np.column_stack([x[0].to_array().flatten() for x in Mx_I0]) assert compare_arrays(M_ref['IAJB'].reshape(nIA, nIA), M_IAJB_test, 8, "A_IAJB") P_iaJB_test = np.column_stack([x[1].to_array().flatten() for x in Px_I0]) assert compare_arrays(P_ref['iaJB'].reshape(nia, nIA), P_iaJB_test, 8, "P_iaJB") M_iaJB_test = np.column_stack([x[1].to_array().flatten() for x in Mx_I0]) assert compare_arrays(M_ref['iaJB'].reshape(nia, nIA), M_iaJB_test, 8, "M_iaJB") P_IAjb_test = np.column_stack([x[0].to_array().flatten() for x in Px_0I]) assert compare_arrays(P_ref['IAjb'].reshape(nIA, nia), P_IAjb_test, 8, "P_IAjb") M_IAjb_test = np.column_stack([x[0].to_array().flatten() for x in Mx_0I]) assert compare_arrays(M_ref['IAjb'].reshape(nIA, nia), M_IAjb_test, 8, "M_IAjb") P_iajb_test = np.column_stack([x[1].to_array().flatten() for x in Px_0I]) assert compare_arrays(P_ref['iajb'].reshape(nia, nia), P_iajb_test, 8, "P_iajb") M_iajb_test = np.column_stack([x[1].to_array().flatten() for x in Mx_0I]) assert compare_arrays(M_ref['iajb'].reshape(nia, nia), M_iajb_test, 8, "M_iajb")
def test_geometric_hessian_rhf_outside_solver_chemists(): psi4.core.set_output_file("output2.dat", False) mol = molecules.molecule_physicists_water_sto3g() mol.reset_point_group("c1") mol.update_geometry() psi4.core.set_active_molecule(mol) options = { "BASIS": "STO-3G", "SCF_TYPE": "PK", "E_CONVERGENCE": 1e-10, "D_CONVERGENCE": 1e-10, } psi4.set_options(options) _, wfn = psi4.energy("hf", return_wfn=True) norb = wfn.nmo() nocc = wfn.nalpha() nvir = norb - nocc o = slice(0, nocc) v = slice(nocc, norb) C = wfn.Ca_subset("AO", "ALL") npC = np.asarray(C) mints = psi4.core.MintsHelper(wfn) T = np.asarray(mints.ao_kinetic()) V = np.asarray(mints.ao_potential()) H_ao = T + V H = np.einsum("up,vq,uv->pq", npC, npC, H_ao) MO = np.asarray(mints.mo_eri(C, C, C, C)) F = H + 2.0 * np.einsum("pqii->pq", MO[:, :, o, o]) F -= np.einsum("piqi->pq", MO[:, o, :, o]) F_ref = np.load(os.path.join(datadir, "F.npy")) np.testing.assert_allclose(F, F_ref, rtol=0, atol=1.0e-10) natoms = mol.natom() cart = ["_X", "_Y", "_Z"] oei_dict = {"S": "OVERLAP", "T": "KINETIC", "V": "POTENTIAL"} deriv1_mat = {} deriv1 = {} # 1st Derivative of OEIs for atom in range(natoms): for key in oei_dict: deriv1_mat[key + str(atom)] = mints.mo_oei_deriv1(oei_dict[key], atom, C, C) for p in range(3): map_key = key + str(atom) + cart[p] deriv1[map_key] = np.asarray(deriv1_mat[key + str(atom)][p]) deriv1_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose(deriv1[map_key], deriv1_ref, rtol=0, atol=1.0e-10) # 1st Derivative of TEIs for atom in range(natoms): string = "TEI" + str(atom) deriv1_mat[string] = mints.mo_tei_deriv1(atom, C, C, C, C) for p in range(3): map_key = string + cart[p] deriv1[map_key] = np.asarray(deriv1_mat[string][p]) deriv1_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose(deriv1[map_key], deriv1_ref, rtol=0, atol=1.0e-10) Hes = {} deriv2_mat = {} deriv2 = {} Hes["S"] = np.zeros((3 * natoms, 3 * natoms)) Hes["V"] = np.zeros((3 * natoms, 3 * natoms)) Hes["T"] = np.zeros((3 * natoms, 3 * natoms)) Hes["N"] = np.zeros((3 * natoms, 3 * natoms)) Hes["J"] = np.zeros((3 * natoms, 3 * natoms)) Hes["K"] = np.zeros((3 * natoms, 3 * natoms)) Hes["R"] = np.zeros((3 * natoms, 3 * natoms)) Hessian = np.zeros((3 * natoms, 3 * natoms)) Hes["N"] = np.asarray(mol.nuclear_repulsion_energy_deriv2()) psi4.core.print_out("\n\n") Mat = psi4.core.Matrix.from_array(Hes["N"]) Mat.name = "NUCLEAR HESSIAN" Mat.print_out() # 2nd Derivative of OEIs for atom1 in range(natoms): for atom2 in range(atom1 + 1): for key in oei_dict: string = key + str(atom1) + str(atom2) deriv2_mat[string] = mints.mo_oei_deriv2(oei_dict[key], atom1, atom2, C, C) pq = 0 for p in range(3): for q in range(3): map_key = string + cart[p] + cart[q] deriv2[map_key] = np.asarray(deriv2_mat[string][pq]) deriv2_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose( deriv2[map_key], deriv2_ref, rtol=0, atol=1.0e-10 ) pq = pq + 1 row = 3 * atom1 + p col = 3 * atom2 + q if key == "S": Hes[key][row][col] = -2.0 * np.einsum( "ii,ii->", F[o, o], deriv2[map_key][o, o] ) else: Hes[key][row][col] = 2.0 * np.einsum("ii->", deriv2[map_key][o, o]) Hes[key][col][row] = Hes[key][row][col] Hes[key][col][row] = Hes[key][row][col] Hes_ref = np.load(os.path.join(datadir, f"Hes_{map_key}.npy")) np.testing.assert_allclose(Hes[key], Hes_ref, rtol=0, atol=1.0e-10) for key in Hes: Mat = psi4.core.Matrix.from_array(Hes[key]) if key in oei_dict: Mat.name = oei_dict[key] + " HESSIAN" Mat.print_out() psi4.core.print_out("\n") # 2nd Derivative of TEIs for atom1 in range(natoms): for atom2 in range(atom1 + 1): string = "TEI" + str(atom1) + str(atom2) deriv2_mat[string] = mints.mo_tei_deriv2(atom1, atom2, C, C, C, C) pq = 0 for p in range(3): for q in range(3): map_key = string + cart[p] + cart[q] deriv2[map_key] = np.asarray(deriv2_mat[string][pq]) deriv2_ref = np.load(os.path.join(datadir, f"{map_key}.npy")) np.testing.assert_allclose(deriv2[map_key], deriv2_ref, rtol=0, atol=1.0e-10) pq = pq + 1 row = 3 * atom1 + p col = 3 * atom2 + q Hes["J"][row][col] = 2.0 * np.einsum("iijj->", deriv2[map_key][o, o, o, o]) Hes["K"][row][col] = -1.0 * np.einsum("ijij->", deriv2[map_key][o, o, o, o]) Hes["J"][col][row] = Hes["J"][row][col] Hes["K"][col][row] = Hes["K"][row][col] for map_key in ("J", "K"): Hes_ref = np.load(os.path.join(datadir, f"Hes_{map_key}.npy")) np.testing.assert_allclose(Hes[map_key], Hes_ref, rtol=0, atol=1.0e-10) JMat = psi4.core.Matrix.from_array(Hes["J"]) KMat = psi4.core.Matrix.from_array(Hes["K"]) JMat.name = " COULOMB HESSIAN" KMat.name = " EXCHANGE HESSIAN" JMat.print_out() KMat.print_out() # Solve the CPHF equations here, G_iajb U_jb^x = B_ia^x (Einstein summation), # where G is the electronic hessian, # G_iajb = delta_ij * delta_ab * epsilon_ij * epsilon_ab + 4(ia|jb) - (ij|ab) - (ib|ja), # where epsilon_ij = epsilon_i - epsilon_j, (epsilon -> orbital energies), # x refers to the perturbation, U_jb^x are the corresponsing CPHF coefficients # and B_ia^x = S_ia^x * epsilon_ii - F_ia^x + S_mn^x * [2(ia|mn) - (in|ma)], # where S^x = del(S)/del(x), F^x = del(F)/del(x). I_occ = np.diag(np.ones(nocc)) I_vir = np.diag(np.ones(nvir)) epsilon = np.asarray(wfn.epsilon_a()) eps_diag = epsilon[v].reshape(-1, 1) - epsilon[o] # Build the electronic hessian G G = 4 * MO[o, v, o, v] G -= MO[o, o, v, v].swapaxes(1, 2) G -= MO[o, v, o, v].swapaxes(1, 3) G += np.einsum("ai,ij,ab->iajb", eps_diag, I_occ, I_vir) G_ref = np.load(os.path.join(datadir, "G.npy")) np.testing.assert_allclose(G, G_ref, rtol=0, atol=1.0e-10) # Inverse of G Ginv = np.linalg.inv(G.reshape(nocc * nvir, -1)) Ginv = Ginv.reshape(nocc, nvir, nocc, nvir) B = {} F_grad = {} U = {} # Build F_pq^x now for atom in range(natoms): for p in range(3): key = str(atom) + cart[p] F_grad[key] = deriv1["T" + key] F_grad[key] += deriv1["V" + key] F_grad[key] += 2.0 * np.einsum("pqmm->pq", deriv1["TEI" + key][:, :, o, o]) F_grad[key] -= 1.0 * np.einsum("pmmq->pq", deriv1["TEI" + key][:, o, o, :]) F_grad_ref = np.load(os.path.join(datadir, f"F_grad_{key}.npy")) np.testing.assert_allclose(F_grad[key], F_grad_ref, rtol=0, atol=1.0e-10) psi4.core.print_out("\n\n CPHF Coefficients:\n") # Build B_ia^x now for atom in range(natoms): for p in range(3): key = str(atom) + cart[p] B[key] = np.einsum("ia,ii->ia", deriv1["S" + key][o, v], F[o, o]) B[key] -= F_grad[key][o, v] B[key] += 2.0 * np.einsum("iamn,mn->ia", MO[o, v, o, o], deriv1["S" + key][o, o]) B[key] += -1.0 * np.einsum("inma,mn->ia", MO[o, o, o, v], deriv1["S" + key][o, o]) print(f"B[{key}]") print(B[key]) B_ref = np.load(os.path.join(datadir, f"B_{key}.npy")) np.testing.assert_allclose(B[key], B_ref.T, rtol=0, atol=1.0e-10) # Compute U^x now: U_ia^x = G^(-1)_iajb * B_jb^x U[key] = np.einsum("iajb,jb->ia", Ginv, B[key]) psi4.core.print_out("\n") UMat = psi4.core.Matrix.from_array(U[key]) UMat.name = key UMat.print_out() U_ref = np.load(os.path.join(datadir, f"U_{key}.npy")) np.testing.assert_allclose(U[key], U_ref.T, rtol=0, atol=1.0e-10) # Build the response Hessian for atom1 in range(natoms): for atom2 in range(atom1 + 1): for p in range(3): for q in range(3): key1 = str(atom1) + cart[p] key2 = str(atom2) + cart[q] key1S = "S" + key1 key2S = "S" + key2 r = 3 * atom1 + p c = 3 * atom2 + q Hes["R"][r][c] = -2.0 * np.einsum( "ij,ij->", deriv1[key1S][o, o], F_grad[key2][o, o] ) Hes["R"][r][c] -= 2.0 * np.einsum( "ij,ij->", deriv1[key2S][o, o], F_grad[key1][o, o] ) Hes["R"][r][c] += 4.0 * np.einsum( "ii,mi,mi->", F[o, o], deriv1[key2S][o, o], deriv1[key1S][o, o] ) Hes["R"][r][c] += 4.0 * np.einsum( "ij,mn,ijmn->", deriv1[key1S][o, o], deriv1[key2S][o, o], MO[o, o, o, o], ) Hes["R"][r][c] -= 2.0 * np.einsum( "ij,mn,inmj->", deriv1[key1S][o, o], deriv1[key2S][o, o], MO[o, o, o, o], ) Hes["R"][r][c] -= 4.0 * np.einsum("ia,ia->", U[key2], B[key1]) Hes["R"][c][r] = Hes["R"][r][c] Hes_ref = np.load(os.path.join(datadir, "Hes_R.npy")) np.testing.assert_allclose(Hes["R"], Hes_ref, rtol=0, atol=1.0e-10) Mat = psi4.core.Matrix.from_array(Hes["R"]) Mat.name = " RESPONSE HESSIAN" Mat.print_out() for key in Hes: Hessian += Hes[key] # print('deriv1_mat') # print(deriv1_mat.keys()) # print('deriv1') # print(deriv1.keys()) # print('deriv2_mat') # print(deriv2_mat.keys()) # print('deriv2') # print(deriv2.keys()) # print('B') # print(B.keys()) # print('F_grad') # print(F_grad.keys()) # print('U') # print(U.keys()) # print('Hes') # print(Hes.keys()) Mat = psi4.core.Matrix.from_array(Hessian) Mat.name = " TOTAL HESSIAN" Mat.print_out() # pylint: disable=bad-whitespace H_psi4 = psi4.core.Matrix.from_list( [ [ 7.613952269164418751e-02, 0.000000000000000000e00, 0.000000000000000000e00, -3.806976134297335168e-02, 0.000000000000000000e00, 0.000000000000000000e00, -3.806976134297410108e-02, 0.000000000000000000e00, 0.000000000000000000e00, ], [ 0.000000000000000000e00, 4.829053723748517601e-01, 0.000000000000000000e00, 0.000000000000000000e00, -2.414526861845633920e-01, 1.589001558536450587e-01, 0.000000000000000000e00, -2.414526861845646133e-01, -1.589001558536444758e-01, ], [ 0.000000000000000000e00, 0.000000000000000000e00, 4.373449597848400039e-01, 0.000000000000000000e00, 7.344233774055003439e-02, -2.186724798895446076e-01, 0.000000000000000000e00, -7.344233774054893804e-02, -2.186724798895475219e-01, ], [ -3.806976134297335168e-02, 0.000000000000000000e00, 0.000000000000000000e00, 4.537741758645107149e-02, 0.000000000000000000e00, 0.000000000000000000e00, -7.307656243475501093e-03, 0.000000000000000000e00, 0.000000000000000000e00, ], [ 0.000000000000000000e00, -2.414526861845633920e-01, 7.344233774055003439e-02, 0.000000000000000000e00, 2.578650065921952450e-01, -1.161712467970963669e-01, 0.000000000000000000e00, -1.641232040762596878e-02, 4.272890905654690846e-02, ], [ 0.000000000000000000e00, 1.589001558536450587e-01, -2.186724798895446076e-01, 0.000000000000000000e00, -1.161712467970963669e-01, 1.977519807685419462e-01, 0.000000000000000000e00, -4.272890905654720684e-02, 2.092049912100946499e-02, ], [ -3.806976134297410108e-02, 0.000000000000000000e00, 0.000000000000000000e00, -7.307656243475501093e-03, 0.000000000000000000e00, 0.000000000000000000e00, 4.537741758645268131e-02, 0.000000000000000000e00, 0.000000000000000000e00, ], [ 0.000000000000000000e00, -2.414526861845646133e-01, -7.344233774054893804e-02, 0.000000000000000000e00, -1.641232040762596878e-02, -4.272890905654720684e-02, 0.000000000000000000e00, 2.578650065921969103e-01, 1.161712467970957008e-01, ], [ 0.000000000000000000e00, -1.589001558536444758e-01, -2.186724798895475219e-01, 0.000000000000000000e00, 4.272890905654690846e-02, 2.092049912100946499e-02, 0.000000000000000000e00, 1.161712467970957008e-01, 1.977519807685442221e-01, ], ] ) H_python_mat = psi4.core.Matrix.from_array(Hessian) psi4.compare_matrices(H_psi4, H_python_mat, 10, "RHF-HESSIAN-TEST") # TEST
# Memory for Psi4 in GB psi4.core.set_memory(int(2e9), False) psi4.core.set_output_file('output.dat', False) # Memory for numpy in GB numpy_memory = 2 mol = psi4.geometry(""" O H 1 1.1 H 1 1.1 2 104 symmetry c1 """) # Set some options psi4.set_options({"basis": "cc-pvdz", "scf_type": "pk", "e_convergence": 1e-8}) # Set defaults maxiter = 40 E_conv = 1.0E-8 D_conv = 1.0E-3 # Integral generation from Psi4's MintsHelper wfn = psi4.core.Wavefunction.build(mol, psi4.core.get_global_option('BASIS')) t = time.time() mints = psi4.core.MintsHelper(wfn.basisset()) S = np.asarray(mints.ao_overlap()) # Get nbf and ndocc for closed shell molecules nbf = wfn.nso() ndocc = wfn.nalpha()
def _test_scf5(): """scf5""" #! Test of all different algorithms and reference types for SCF, on singlet and triplet O2, using the cc-pVTZ basis set and using ERD integrals. psi4.print_stdout(' Case Study Test of all SCF algorithms/spin-degeneracies: Singlet-Triplet O2') psi4.print_stdout(' -Integral package: {}'.format(psi4.core.get_global_option('integral_package'))) #Ensure that the checkpoint file is always nuked psi4.core.IOManager.shared_object().set_specific_retention(32,False) Eref_nuc = 30.78849213614545 Eref_sing_can = -149.58723684929720 Eref_sing_df = -149.58715054487624 Eref_uhf_can = -149.67135517240553 Eref_uhf_df = -149.67125624291961 Eref_rohf_can = -149.65170765757173 Eref_rohf_df = -149.65160796208073 singlet_o2 = psi4.geometry(""" 0 1 O O 1 1.1 units angstrom """) triplet_o2 = psi4.geometry(""" 0 3 O O 1 1.1 units angstrom """) singlet_o2.update_geometry() triplet_o2.update_geometry() psi4.print_stdout(' -Nuclear Repulsion:') assert psi4.compare_values(Eref_nuc, triplet_o2.nuclear_repulsion_energy(), 9, "Triplet nuclear repulsion energy") assert psi4.compare_values(Eref_nuc, singlet_o2.nuclear_repulsion_energy(), 9, "Singlet nuclear repulsion energy") psi4.set_options({ 'basis': 'cc-pvtz', 'df_basis_scf': 'cc-pvtz-jkfit', 'print': 2}) print(' -Singlet RHF:') psi4.set_module_options('scf', {'reference': 'rhf'}) psi4.set_module_options('scf', {'scf_type': 'pk'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_can, E, 6, 'Singlet PK RHF energy') psi4.set_module_options('scf', {'scf_type': 'direct'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_can, E, 6, 'Singlet Direct RHF energy') psi4.set_module_options('scf', {'scf_type': 'out_of_core'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_can, E, 6, 'Singlet Disk RHF energy') psi4.set_module_options('scf', {'scf_type': 'df'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_df, E, 6, 'Singlet DF RHF energy') print(' -Singlet UHF:') psi4.set_module_options('scf', {'reference': 'uhf'}) psi4.set_module_options('scf', {'scf_type': 'pk'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_can, E, 6, 'Singlet PK UHF energy') psi4.set_module_options('scf', {'scf_type': 'direct'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_can, E, 6, 'Singlet Direct UHF energy') psi4.set_module_options('scf', {'scf_type': 'out_of_core'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_can, E, 6, 'Singlet Disk UHF energy') psi4.set_module_options('scf', {'scf_type': 'df'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_df, E, 6, 'Singlet DF UHF energy') print(' -Singlet CUHF:') psi4.set_module_options('scf', {'reference': 'cuhf'}) psi4.set_module_options('scf', {'scf_type': 'pk'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_can, E, 6, 'Singlet PK CUHF energy') psi4.set_module_options('scf', {'scf_type': 'direct'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_can, E, 6, 'Singlet Direct CUHF energy') psi4.set_module_options('scf', {'scf_type': 'out_of_core'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_can, E, 6, 'Singlet Disk CUHF energy') psi4.set_module_options('scf', {'scf_type': 'df'}) E = psi4.energy('scf', molecule=singlet_o2) assert psi4.compare_values(Eref_sing_df, E, 6, 'Singlet DF CUHF energy') psi4.set_options({ 'basis': 'cc-pvtz', 'df_basis_scf': 'cc-pvtz-jkfit', 'guess': 'core', 'print': 2}) print(' -Triplet UHF:') psi4.set_module_options('scf', {'reference': 'uhf'}) psi4.set_module_options('scf', {'scf_type': 'pk'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_uhf_can, E, 6, 'Triplet PK UHF energy') psi4.set_module_options('scf', {'scf_type': 'direct'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_uhf_can, E, 6, 'Triplet Direct UHF energy') psi4.set_module_options('scf', {'scf_type': 'out_of_core'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_uhf_can, E, 6, 'Triplet Disk UHF energy') psi4.set_module_options('scf', {'scf_type': 'df'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_uhf_df, E, 6, 'Triplet DF UHF energy') psi4.core.clean() print(' -Triplet ROHF:') psi4.set_module_options('scf', {'reference': 'rohf'}) psi4.set_module_options('scf', {'scf_type': 'pk'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_rohf_can, E, 6, 'Triplet PK ROHF energy') psi4.core.clean() psi4.set_module_options('scf', {'scf_type': 'direct'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_rohf_can, E, 6, 'Triplet Direct ROHF energy') psi4.core.clean() psi4.set_module_options('scf', {'scf_type': 'out_of_core'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_rohf_can, E, 6, 'Triplet Disk ROHF energy') psi4.core.clean() psi4.set_module_options('scf', {'scf_type': 'df'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_rohf_df, E, 6, 'Triplet DF ROHF energy') psi4.core.clean() print(' -Triplet CUHF:') psi4.set_module_options('scf', {'reference': 'cuhf'}) psi4.set_module_options('scf', {'scf_type': 'pk'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_rohf_can, E, 6, 'Triplet PK CUHF energy') psi4.core.clean() psi4.set_module_options('scf', {'scf_type': 'direct'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_rohf_can, E, 6, 'Triplet Direct CUHF energy') psi4.core.clean() psi4.set_module_options('scf', {'scf_type': 'out_of_core'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_rohf_can, E, 6, 'Triplet Disk CUHF energy') psi4.core.clean() psi4.set_module_options('scf', {'scf_type': 'df'}) E = psi4.energy('scf', molecule=triplet_o2) assert psi4.compare_values(Eref_rohf_df, E, 6, 'Triplet DF CUHF energy')