def test_pcmsolver(): """pcmsolver/scf""" #! pcm nucenergy = 12.0367196636183458 polenergy = -0.0053060443528559 totalenergy = -55.4559426361734040 NH3 = psi4.geometry(""" symmetry c1 N -0.0000000001 -0.1040380466 0.0000000000 H -0.9015844116 0.4818470201 -1.5615900098 H -0.9015844116 0.4818470201 1.5615900098 H 1.8031688251 0.4818470204 0.0000000000 units bohr no_reorient no_com """) psi4.set_options({ 'basis': 'STO-3G', 'scf_type': 'pk', 'pcm': True, 'pcm_scf_type': 'total', }) psi4.pcm_helper(""" Units = Angstrom Medium { SolverType = IEFPCM Solvent = Water } Cavity { RadiiSet = UFF Type = GePol Scaling = False Area = 0.3 Mode = Implicit } """) print('RHF-PCM, total algorithm') energy_scf1, wfn1 = psi4.energy('scf', return_wfn=True) assert psi4.compare_values(nucenergy, NH3.nuclear_repulsion_energy(), 10, "Nuclear repulsion energy (PCM, total algorithm)") #TEST assert psi4.compare_values(totalenergy, energy_scf1, 10, "Total energy (PCM, total algorithm)") #TEST assert psi4.compare_values(polenergy, wfn1.get_variable("PCM POLARIZATION ENERGY"), 6, "Polarization energy (PCM, total algorithm)") #TEST psi4.set_options({'pcm_scf_type': 'separate'}) print('RHF-PCM, separate algorithm') energy_scf2 = psi4.energy('scf') assert psi4.compare_values(totalenergy, energy_scf2, 10, "Total energy (PCM, separate algorithm)") assert psi4.compare_values(polenergy, psi4.get_variable("PCM POLARIZATION ENERGY"), 6, "Polarization energy (PCM, separate algorithm)") # Now force use of UHF on NH3 to check sanity of the algorithm with PCM psi4.set_options({'pcm_scf_type': 'total', 'reference': 'uhf'}) print('UHF-PCM, total algorithm') energy_scf3 = psi4.energy('scf') assert psi4.compare_values(totalenergy, energy_scf3, 10, "Total energy (PCM, separate algorithm)") assert psi4.compare_values(polenergy, psi4.get_variable("PCM POLARIZATION ENERGY"), 6, "Polarization energy (PCM, separate algorithm)")
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_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_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 hide_test_xtpl_fn_fn_error(): psi4.geometry('He') with pytest.raises(psi4.UpgradeHelper) as e: psi4.energy('cbs', scf_basis='cc-pvdz', scf_scheme=psi4.driver_cbs.xtpl_highest_1) assert 'Replace extrapolation function with function name' in str(e)
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 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 hide_test_xtpl_cbs_fn_error(): psi4.geometry('He') with pytest.raises(psi4.UpgradeHelper) as e: psi4.energy(psi4.cbs, scf_basis='cc-pvdz') #psi4.energy(psi4.driver.driver_cbs.complete_basis_set, scf_basis='cc-pvdz') assert 'Replace cbs or complete_basis_set function with cbs string' in str(e)
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 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 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_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_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_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 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_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_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 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 _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_mrcc(): """mrcc/ccsdt""" #! CCSDT cc-pVDZ energy for the H2O molecule using MRCC h2o = psi4.geometry(""" o h 1 1.0 h 1 1.0 2 104.5 """) psi4.set_options({ 'basis': 'cc-pvdz', 'freeze_core': 'true'}) psi4.energy('mrccsdt') assert psi4.compare_values( 8.801465529972, psi4.variable("NUCLEAR REPULSION ENERGY"), 6, 'NRE') assert psi4.compare_values(-76.021418445155, psi4.variable("SCF TOTAL ENERGY"), 6, 'SCF') assert psi4.compare_values( -0.204692406830, psi4.variable("MP2 CORRELATION ENERGY") , 6, 'MP2 correlation') assert psi4.compare_values( -0.217715210258, psi4.variable("CCSDT CORRELATION ENERGY"), 6, 'CCSDT correlation') assert psi4.compare_values(-76.239133655413, psi4.variable("CURRENT ENERGY"), 6, 'CCSDT')
def test_snsmp2(): """snsmp2/he-he""" HeHe = psi4.geometry(""" 0 1 He 0 0 0 -- He 2 0 0 """) e = psi4.energy('sns-mp2') assert psi4.compare_values(0.00176708227, psi4.variable('SNS-MP2 TOTAL ENERGY'), 5, "SNS-MP2 IE [Eh]")
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_grimme_3c(): s16di = 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 symmetry c1 """) ene = psi4.energy('pbeh3c', bsse_type='nocp') assert psi4.compare_values(-2.153, ene * psi4.constants.hartree2kcalmol, 0.03, 'S22-16 PBEh-3c/def2-mSVP') psi4.set_options({'basis': 'cc-pvdz'}) # try to confuse method psi4.set_options({'scf_type': 'pk'}) ene = psi4.energy('hf3c/', bsse_type='nocp') assert psi4.compare_values(-0.00240232, ene, 6, 'S22-16 HF-3c/minix')
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 plot_density(self, which_density, iso=0.020, slices=1, delete_cubefile=True): psi4.set_options({'cubeprop_tasks': ['density']}) energy, wfn = psi4.energy(self.method, molecule=self.geometry, return_wfn=True) psi4.cubeprop(wfn) if which_density == 'Da': D, D_info = read_cube('Da.cube') elif which_density == 'Db': D, D_info = read_cube('Db.cube') elif which_density == 'Ds': D, D_info = read_cube('Ds.cube') elif which_density == 'Dt': D, D_info = read_cube('Dt.cube') if delete_cubefile == True: os.remove('Da.cube') os.remove('Db.cube') os.remove('Ds.cube') os.remove('Dt.cube') fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 10)) print(D.shape) # for i in range(0): # for j in range(0): ax.imshow(D[60, :, :], interpolation="nearest") for i in range(D.shape[1]): for j in range(D.shape[2]): if np.isclose(D[60, i, j], iso, 0.3e-1) == True: # if (i+j) % 0 == 0: ax.scatter(j, i, color="white") return D
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_df_mp2(mol_str): geometry = psi4.geometry(quest.mollib[mol_str]) basis = "STO-3G" rhf_options = \ { 'e_conv': 1.e-8, 'd_conv': 1.e-8, 'diis': True, 'max_diis': 7, 'max_iter': 100, } mol = quest.Molecule(geometry, basis) wafu = quest.Wavefunction(mol, rhf_options) scf_energy = quest.scf_module.compute_rhf(wafu) mp2_energy = quest.mp2.df_mp2(wafu) psi4.set_options({"scf_type": "df"}) psi4_mp2_energy = psi4.energy('mp2/' + basis, molecule=geometry)
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 _base_tdscf_test(molecule, ref_scf_energy, ref_pe_energy, exc_energies, osc_strengths): scf_energy, wfn = psi4.energy("TD-SCF", return_wfn=True, molecule=molecule) assert compare_values(ref_pe_energy, wfn.variable("PE ENERGY"), 6, "PE Energy contribution") assert compare_values(ref_scf_energy, scf_energy, 6, "Total PE-SCF Energy") e_calc = [] r_calc = [] for i in range(len(exc_energies)): e_calc.append( wfn.variable( f'TD-HF ROOT 0 -> ROOT {i+1} EXCITATION ENERGY - A SYMMETRY')) r_calc.append( wfn.variable( f'TD-HF ROOT 0 -> ROOT {i+1} OSCILLATOR STRENGTH (LEN) - A SYMMETRY' )) assert compare_arrays(exc_energies, e_calc, 4, f'PE EXCITATION ENERGY') assert compare_arrays(osc_strengths, r_calc, 4, f'PE OSCILLATOR STRENGTH')
def test_GGA_unrestricted_one_shell(hydrogen): psi4.core.clean() psi4.core.be_quiet() psi4.set_options({ "DFT_SPHERICAL_POINTS": 6, "DFT_RADIAL_POINTS": 12, }) psi4.set_options({"reference": "uks"}) psi4_energy = psi4.energy("pbe/cc-pVDZ", molecule=hydrogen) h = pdft.UMolecule(hydrogen, "cc-pvdz", "pbe") h.scf() pdft_energy = h.energy assert np.isclose(psi4_energy, pdft_energy, rtol=1e-2)
def test_OH_molden(inp_oh, datadir): mol = psi4.geometry(""" 0 2 O H 1 0.970369 symmetry c1 """) psi4.set_options({ 'basis': 'dz', 'scf_type': 'pk', 'd_convergence': 8, 'reference': inp_oh['ref'] }) molden_file = f"{inp_oh['name']}.molden" ref = datadir.join(f"{inp_oh['name']}.ref") e, wfn = psi4.energy('scf', return_wfn=True, molecule=mol) wfn.write_molden(molden_file, do_virtual=True, use_natural=False) assert compare_moldenfiles(ref, molden_file)
def execute_job(): job_id = {job_id} molecule = "{molecule}" method = "{method}" basis = "{basis}" number_of_threads = {num_threads} memory = "{memory}" try: max_threads = int(subprocess.check_output(["grep", "-c", "cores", "/proc/cpuinfo"])) print("Maximum threads: {format}".format(max_threads)) except: print("Error detecting number of cores. \n Maxium threads: 1") max_threads = 1 if number_of_threads > max_threads: print("Input number of threads ({format}) greater than max threads ({format}), limiting number of threads to max threads".format(number_of_threads, max_threads)) number_of_threads = max_threads print("Running Job") print("Molcule: {format}".format(molecule)) print("Method: {format}".format(method)) print("Basis: {format}".format(basis)) print("Threads {format}".format(number_of_threads)) print("Memory: {format}".format(memory)) psi4.core.set_output_file("job_{format}.log".format(job_id), False) psi4.set_memory(memory) psi4.geometry(molecule) psi4.set_num_threads(number_of_threads) try: energy = psi4.energy("{format}/{format}".format(method, basis)) print("Energy: {format}".format(energy)) success = True except ValueError: success = False print("Iterations failed to Converge") with open("job_{format}.out".format(job_id), "w") as out_file: out_file.write("Job: {format}\n".format(job_id)) if success: out_file.write("Energy: {format}".format(energy)) else: out_file.write("Failure")
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')
def test_H2O_molden(inp_h2o, datadir): mol = psi4.geometry(""" 0 1 O H 1 0.951342 H 1 0.951342 2 112.505645 """) psi4.set_options({ 'basis': 'dz', 'scf_type': 'pk', }) psi4.set_options(inp_h2o['options']) molden_file = f"{inp_h2o['name']}.molden" ref = datadir.join(f"{inp_h2o['name']}.ref") e, wfn = psi4.energy(inp_h2o['energy'], return_wfn=True, molecule=mol) wfn.write_molden(molden_file, do_virtual=inp_h2o['do_virtual'], use_natural=inp_h2o['use_natural']) assert compare_moldenfiles(ref, molden_file)
def HFenergy(row): psi4.set_memory('500 MB') #charge = +1, spin multipicity = 2 h2o = psi4.geometry(""" 1 2 O {} {} {} C {} {} {} H {} {} {} H {} {} {} """.format(*row)) psi4.set_options({'reference': 'uhf'}) #Energy calculated using UHF/cc-pVDZ try: return psi4.energy('scf/cc-pvdz') except: #In case there's a convergence error or alike return 0.0
def test_dft_grid_threaded_raise(): dimer = psi4.geometry(""" 1 1 K -4.067042 -1.894214 0.002270 """) psi4.set_options({ "dft_grid_name": "SG1", "dft_vv10_radial_points": 50, "dft_vv10_spherical_points": 194, "dft_nuclear_scheme": "treutler", "dft_radial_scheme": "EM", "basis": "def2-TZVPPD", }) with pytest.raises(RuntimeError) as e: ene = psi4.energy("wB97M-V") assert "There is no SG-1 grid defined for the requested atomic number" in str(e.value)
def test_psi4_dfmp2(): """dfmp2-1""" #! Density fitted MP2 cc-PVDZ/cc-pVDZ-RI computation of formic acid dimer binding energy #! using automatic counterpoise correction. Monomers are specified using Cartesian coordinates. Enuc = 235.94662124 Ecp = -0.0224119246 formic_dim = psi4.geometry(""" 0 1 C -1.888896 -0.179692 0.000000 O -1.493280 1.073689 0.000000 O -1.170435 -1.166590 0.000000 H -2.979488 -0.258829 0.000000 H -0.498833 1.107195 0.000000 -- 0 1 C 1.888896 0.179692 0.000000 O 1.493280 -1.073689 0.000000 O 1.170435 1.166590 0.000000 H 2.979488 0.258829 0.000000 H 0.498833 -1.107195 0.000000 units angstrom no_reorient """) psi4.set_options({ 'basis': 'cc-pvdz', 'df_basis_scf': 'cc-pvdz-jkfit', 'df_basis_mp2': 'cc-pvdz-ri', # not necessary to specify df_basis* for most basis sets 'scf_type': 'df', 'guess': 'sad', 'd_convergence': 11, }) e_cp = psi4.energy('mp2', bsse_type='cp') assert psi4.compare_values(Enuc, formic_dim.nuclear_repulsion_energy(), 7, "Nuclear Repulsion Energy") assert psi4.compare_values(Ecp, e_cp, 5, "CP Corrected cc-pVDZ/cc-pVDZ-RI DFMP2")
def test_pao_H8(): """PAO-CCSD Test""" # Psi4 Setup psi4.set_memory('1 GB') psi4.core.set_output_file('output.dat', False) psi4.set_options({'basis': 'DZ', 'scf_type': 'pk', 'guess': 'core', 'mp2_type': 'conv', 'freeze_core': 'False', 'e_convergence': 1e-12, 'd_convergence': 1e-12, 'r_convergence': 1e-12, 'diis': 8}) mol = psi4.geometry(""" H 0.000000 0.000000 0.000000 H 0.750000 0.000000 0.000000 H 0.000000 1.500000 0.000000 H 0.375000 1.500000 -0.649520 H 0.000000 3.000000 0.000000 H -0.375000 3.000000 -0.649520 H 0.000000 4.500000 -0.000000 H -0.750000 4.500000 -0.000000 symmetry c1 noreorient nocom """) rhf_e, rhf_wfn = psi4.energy('SCF', return_wfn=True) maxiter = 75 e_conv = 1e-12 r_conv = 1e-12 max_diis = 8 ccsd = pycc.ccwfn(rhf_wfn, local='PAO', local_cutoff=2e-2) eccsd = ccsd.solve_cc(e_conv, r_conv, maxiter, max_diis) # (H2)_4 REFERENCE: psi3_ref = -0.108914240219735 assert (abs(psi3_ref - eccsd) < 1e-7)
def _run_init(self): "Solve unperturbed SCF equations" for frag in self._frags: frag.set_point_group(psi4.core.PointGroup('c1')) frag.reset_point_group('c1') frag.fix_orientation(True) frag.print_out() en, wfn = psi4.energy('scf', return_wfn=True, molecule=frag) bfs = wfn.basisset() assert bfs.nbf() <= MAX_NBF, " Maximum number of basis functions %d exceeded!" % MAX_NBF mints = psi4.core.MintsHelper(bfs) jk = psi4.core.JK.build(bfs, jk_type="Direct") jk.set_memory(int(5e8)) # 4GB jk.initialize() X = self._orthogonalizer(numpy.asarray(wfn.S())) eps = numpy.asarray(wfn.epsilon_a()) C = numpy.asarray(wfn.Ca()) Co = numpy.asarray(wfn.Ca_subset("AO","OCC")) H = numpy.asarray(wfn.H()) F = numpy.asarray(wfn.Fa()) D = numpy.asarray(wfn.Da()) # self._ens .append(en) # Total energy of a fragment self._ndocc.append(wfn.nalpha()) # number of doubly-occupied MO's self._nbfs .append(bfs.nbf()) # number of basis functions self._bfs .append(bfs) # basis set self._mints.append(mints) # Integral calculator self._jks .append(jk) # JK calculator self._Xs .append(X) # AO orthogonalizer (S^-1/2) self._eps .append(eps) # Eigenvalues of Fock matrix self._Cs .append(Co) # LCAO-MO coefficients (occ) self._Csall.append(C) # LCAO-MO coefficients (occ+vir) self._H .append(H) # Hcore matrix in original basis self._Hs .append(H) # Effective Hcore matrix in original basis self._Fs .append(F) # Fock matrix in original basis self._Ds .append(D) # One-particle density matrix in original basis self._wfn .append(wfn) # SCF wavefunction object # compute interfragment nuclear repulsion energy self.enuc = self._interfragmentNuclearRepulsionEnergy() # self.en_0 = None return
def test_restricted_TDA_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, _ = build_RHF_AB_C1_triplet(wfn) ni, na, _, _ = A_ref.shape nia = ni * na A_ref = A_ref.reshape((nia, nia)) # Build engine eng = TDRSCFEngine(wfn, ptype='tda', triplet=True) # our "guess"" vectors ID = [psi4.core.Matrix.from_array(v.reshape((ni, na))) for v in tuple(np.eye(nia).T)] A_test = np.column_stack([x.to_array().flatten() for x in eng.compute_products(ID)[0]]) assert compare_arrays(A_ref, A_test, 8, "RHF Ax C1 products")
def psi4_scf(params, geometries): """ Function to run SCF along IRC using PSI4, returns array of energies at each geometry. """ print_header(params.outfile) energies = [] wavefunctions = [] count = 0 start = time.time() level_of_theory = "%s/%s" % (params.method, params.basis) if (params.do_solvent): set_solvent_parameters(params) for geometry in geometries: output = open(params.outfile, "a") psi4.core.set_output_file("psi4_output/irc_%d.out" % count, False) geom = geometry geom += "\nsymmetry c1" mol = psi4.geometry(geom) psi4.set_options(params.keywords) #print("pyREX:Single Point Calculation on IRC Point %d" %(count)) psi4.set_num_threads(params.nthreads) if (params.set_memory): psi4.set_memory(params.memory_allocation) energy, wfn = psi4.energy(level_of_theory, return_wfn=True) #wfn = psi4.core.Wavefunction.build(mol, self.basis) ndocc = wfn.doccpi()[0] #print(ndocc) eps = np.array(wfn.epsilon_a()) #print(eps) homo_energy = eps[ndocc - 1] lumo_energy = eps[ndocc] energies.append(energy) wavefunctions.append(wfn) output.write('{:>20.2f} {:>20.4f} {:>20.4f} {:>20.4f}\n'.format( params.coordinates[count], energy, homo_energy, lumo_energy)) count = count + 1 output.close() print_footer(params.outfile) end = time.time() print("psi4 Time = %f" % (end - start)) return energies, wavefunctions
def test_unrestricted_TDA_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 eng = TDUSCFEngine(wfn, ptype='tda') 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{IA, KC} A{IA, kc}] [ I{KC, JB} | 0{KC,jb}] = [A x X_I0] = [ A_IAJB, A_iaJB] # [ A{ia, KC} A{ia, kc}] [ O{kc, JB} | X{kc,jb}] [A x X_0I] = [ A_IAjb, A_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)] Ax_I0 = eng.compute_products(X_I0)[0] Ax_0I = eng.compute_products(X_0I)[0] A_IAJB_test = np.column_stack([x[0].to_array().flatten() for x in Ax_I0]) assert compare_arrays(A_ref['IAJB'].reshape(nIA, nIA), A_IAJB_test, 8, "A_IAJB") A_iaJB_test = np.column_stack([x[1].to_array().flatten() for x in Ax_I0]) assert compare_arrays(A_ref['iaJB'].reshape(nia, nIA), A_iaJB_test, 8, "A_iaJB") A_IAjb_test = np.column_stack([x[0].to_array().flatten() for x in Ax_0I]) assert compare_arrays(A_ref['IAjb'].reshape(nIA, nia), A_IAjb_test, 8, "A_IAjb") A_iajb_test = np.column_stack([x[1].to_array().flatten() for x in Ax_0I]) assert compare_arrays(A_ref['iajb'].reshape(nia, nia), A_iajb_test, 8, "A_iajb")
def FMO1iter(fragList, rmsd): # create the new wfn objects in the 3rd array posiiton rmsd = createChargefield(fragList, list(range(len(fragList))), new=True) for count, i in enumerate(fragList): fragnums = list(range(len(fragList))) fragnums.remove(count) createChargefield(fragList, fragnums) E, wfn = psi4.energy(theory, return_wfn=True, molecule=fragList[i][0]) fragList[i] += [wfn] # delete the old wfn objects for i in fragList: del fragList[i][1] # calculate the FMO cluster energy fragEnergies = [] for i in fragList: fragEnergies += [fragList[i][1].energy()] FMOEnergy = np.sum(fragEnergies) return (FMOEnergy, fragEnergies, rmsd)
def energy(geom, confId, method='HF-3C', **kwargs): """ Finds the energy of a given molecule :param geom: an RDKit.Mol or a string :param confId: the ID of the conformer to optimize :param method: the PSI4 method to calculate the H**O and LUMO :return: wavefunction (energy is available under wavefunction.energy) """ try: geom = make_psi4_geometry(geom, confId) psi4.activate(geom) psi4.core.IO.set_default_namespace(str(id(geom))) psi4.core.set_global_option("MAXITER", 1000) return psi4.energy(method, return_wfn=True, **kwargs)[1] except Exception as e: print(e) return np.nan
def test_export_ao_elec_dip_deriv(): h2o = psi4.geometry(""" O H 1 1.0 H 1 1.0 2 101.5 symmetry c1 """) rhf_e, wfn = psi4.energy('SCF/cc-pVDZ', molecule=h2o, return_wfn=True) mints = psi4.core.MintsHelper(wfn.basisset()) natoms = h2o.natom() cart = ['_X', '_Y', '_Z'] D = wfn.Da() D.add(wfn.Db()) D_np = np.asarray(D) deriv1_mat = {} deriv1_np = {} MU_Gradient = np.zeros((3 * natoms, 3)) for atom in range(natoms): deriv1_mat["MU_" + str(atom)] = mints.ao_elec_dip_deriv1(atom) for mu_cart in range(3): for atom_cart in range(3): map_key = "MU" + cart[mu_cart] + "_" + str( atom) + cart[atom_cart] deriv1_np[map_key] = np.asarray( deriv1_mat["MU_" + str(atom)][3 * mu_cart + atom_cart]) MU_Gradient[3 * atom + atom_cart, mu_cart] += np.einsum("uv,uv->", deriv1_np[map_key], D_np) PSI4_MU_Grad = mints.dipole_grad(D) G_python_MU_mat = psi4.core.Matrix.from_array(MU_Gradient) assert psi4.compare_matrices(PSI4_MU_Grad, G_python_MU_mat, 10, "DIPOLE_GRADIENT_TEST") # TEST
def test_scsmp2(inp): """Formerly known as dfmp2-4""" h2o = psi4.geometry(""" O H 1 1.0 H 1 1.0 2 90.0 """) psi4.set_options({'basis': 'cc-pvdz'}) psi4.set_options(inp['options']) ene, wfn = psi4.energy(inp['name'], return_wfn=True) ref_block = _ref_h2o_ccpvdz[inp['options']['mp2_type']] #ref_corl = ref_block[inp['pv'] + ' CORRELATION ENERGY'] #ref_tot = ref_block[inp['pv'] + ' TOTAL ENERGY'] ref_corl = ref_block['MP2 CORRELATION ENERGY'] ref_tot = ref_block['MP2 TOTAL ENERGY'] ref_custom_corl = ref_block[inp['custom'] + ' CORRELATION ENERGY'] ref_custom_tot = ref_block[inp['custom'] + ' TOTAL ENERGY'] for obj in [psi4.core, wfn]: for pv in [ 'HF TOTAL ENERGY', 'SCF TOTAL ENERGY', 'MP2 SAME-SPIN CORRELATION ENERGY', 'MP2 OPPOSITE-SPIN CORRELATION ENERGY', 'MP2 CORRELATION ENERGY', 'MP2 TOTAL ENERGY', 'SCS-MP2 CORRELATION ENERGY', 'SCS-MP2 TOTAL ENERGY', 'CURRENT REFERENCE ENERGY' ]: assert compare_values(ref_block[pv], obj.variable(pv), 5, pv) assert compare_values(ref_custom_corl, obj.variable('CUSTOM SCS-MP2 CORRELATION ENERGY'), 5, 'custom scsmp2 corl') assert compare_values(ref_custom_tot, obj.variable('CUSTOM SCS-MP2 TOTAL ENERGY'), 5, 'custom scsmp2 ') assert compare_values(ref_corl, obj.variable('CURRENT CORRELATION ENERGY'), 5, 'current corl') assert compare_values(ref_tot, obj.variable('CURRENT ENERGY'), 5, 'current') assert compare_values(ref_tot, ene, 5, 'return') assert compare_values(ref_tot, wfn.energy(), 5, 'wfn')
def test_aci1(): import math import psi4 import forte from forte import forte_options ref_aci = -75.010199198896 rel_tol = 1e-9 abs_tol = 1e-8 h2o = psi4.geometry(""" O H 1 0.96 H 1 0.96 2 104.5 """) psi4.set_options({'basis': "sto-3g"}) E_scf, wfn = psi4.energy('scf', return_wfn=True) state = forte.StateInfo(na=5, nb=5, multiplicity=1, twice_ms=0, irrep=0) dim = psi4.core.Dimension([4, 0, 1, 2]) options = psi4.core.get_options() options.set_current_module('FORTE') forte_options.update_psi_options(options) forte.startup() forte.banner() mo_space_info = forte.make_mo_space_info(wfn, forte_options) ints = forte.make_forte_integrals(wfn, options, mo_space_info) scf_info = forte.SCFInfo(wfn) solver = forte.make_active_space_solver('ACI', state, scf_info, mo_space_info, ints, forte_options) energy = solver.compute_energy() assert math.isclose(energy, ref_aci, abs_tol=abs_tol, rel_tol=rel_tol) print("\n\nACI Energy = {}".format(energy)) forte.cleanup()
def test_weird_basis(subject, bas, ans, mols, request): """non-consecutive angular momentum basis set patterns""" mol = mols[subject] ref = "rhf" if mol.multiplicity() == 1 else "uhf" psi4.set_options({ "reference": ref, "guess": "core", "scf_type": "pk", "df_scf_guess": "false", "basis": "anonymous1234", }) def basisspec_psi4_yo__anonymous1234(mol, role): mol.set_basis_all_atoms("test", role=role) return {"test": bas} psi4.driver.qcdb.libmintsbasisset.basishorde[ "ANONYMOUS1234"] = basisspec_psi4_yo__anonymous1234 ene = psi4.energy("scf", molecule=mol) assert compare_values(ans, ene, 6, request.node.name)
def CISD(ISE=False): print('\n --------- CASCI STARTED --------- \n') # Number of molecular orbitals is determined from the size of One-electron integral scf_e, wfn = psi4.energy('scf', return_wfn=True) nelec = wfn.nalpha() + wfn.nbeta() C = wfn.Ca() ndocc = wfn.doccpi()[0] nmo = wfn.nmo() nvir = nmo - ndocc eps = np.asarray(wfn.epsilon_a()) nbf = C.shape[0] Vnuc = wfn.molecule().nuclear_repulsion_energy() print("Number of Electrons: {}".format(nelec)) print("Number of Basis Functions: {}".format(nbf)) print("Number of Molecular Orbitals: {}".format(nmo)) print("Number of Doubly ocuppied MOs: {}\n".format(ndocc)) # Build integrals from Psi4 MINTS print("Converting atomic integrals to MO integrals...") t = time.time() mints = psi4.core.MintsHelper(wfn.basisset()) ERI = np.asarray(mints.mo_eri(C, C, C, C)) OEI = np.asarray(mints.ao_kinetic()) + np.asarray(mints.ao_potential()) OEI = np.einsum('up,vq,uv->pq', C, C, OEI) print("Completed in {} seconds!".format(time.time() - t)) Ecas, Ccas, ref, determinants = compute(OEI, ERI, nelec, ndocc, nvir, verb=True, ISE=ISE) print('Final CISD energy: {:<15.10f}'.format(Ecas + Vnuc))
def test_fcidump_scf_energy(): """Compare FCIDUMP computed SCF energy against call to energy()""" Ne = psi4.geometry(""" Ne 0 0 0 """) psi4.set_options({ 'basis': 'cc-pVDZ', 'scf_type': 'pk', 'reference': 'uhf', 'd_convergence': 1e-8, 'e_convergence': 1e-8 }) scf_e, scf_wfn = psi4.energy('scf', return_wfn=True) psi4.fcidump(scf_wfn, fname='FCIDUMP_SCF', oe_ints=['EIGENVALUES']) intdump = psi4.fcidump_from_file('FCIDUMP_SCF') e_dict = psi4.energies_from_fcidump(intdump) fcidump_e = e_dict['SCF TOTAL ENERGY'] assert psi4.compare_values(scf_e, fcidump_e, 5, 'SCF energy') #TEST
def test_mcmurchie_davidson_multipoles_gradient(mol_h2o): psi4.set_options({'basis': 'cc-pvdz'}) _, wfn = psi4.energy('HF', molecule=mol_h2o, return_wfn=True) order = 8 ints_grad = fdiff_multipole_integral(mol_h2o, 'cc-pvdz', [1.0, 2.0, 3.0], order=order) nmul = cumulative_cart_dim(order) - 1 grad_fdiff = np.einsum('ncmij,ij->ncm', ints_grad, wfn.Da().np).reshape(-1, nmul) mints = psi4.core.MintsHelper(wfn.basisset()) # test against finite differences grad = mints.multipole_grad(D=wfn.Da(), order=order, origin=[1.0, 2.0, 3.0]) np.testing.assert_allclose(grad_fdiff, grad.np, atol=1e-8) # test that we get the same result from the 'hard-wired' dipole_grad grad_dip = mints.dipole_grad(wfn.Da()) grad = mints.multipole_grad(D=wfn.Da(), order=1, origin=[0.0, 0.0, 0.0]) np.testing.assert_allclose(grad_dip.np, grad.np, atol=1e-14)
def test_scf(mol_str): basis = 'sto-3g' molecule = quest.Molecule(quest.mollib[mol_str], basis) rhf_options = \ { 'e_conv': 1.e-8, 'd_conv': 1.e-8, 'diis': True, 'max_diis': 7, 'max_iter': 100, } wfn = quest.Wavefunction(molecule, rhf_options) # Compute RHF scf_energy = quest.scf_module.compute_rhf(wfn) psi4.set_options({"scf_type": "pk"}) ref_energy = psi4.energy("SCF" + "/" + basis, molecule=molecule.mol) assert np.allclose(ref_energy, scf_energy)
def test_pe_adc1(): """LR-PE-ADC(1)/sto-3g formaldehyde in presence of 6 water molecules cross-reference against PE-CIS from Psi4 itself""" mol = psi4.geometry(__geoms['formaldehyde']) potfile = _dump_potential('pna_6w') psi4.set_options({ 'basis': 'sto-3g', 'pe': True, 'scf_type': 'pk', 'pe__potfile': potfile, 'roots_per_irrep': [5], 'qc_module': 'adcc', 'tdscf_states': 5, 'tdscf_tda': True, }) _, wfn_tdhf = psi4.energy('td-hf', return_wfn=True) _, wfn_adc = psi4.properties('adc(1)', properties=["oscillator_strength", "dipole"], environment='linear_response', return_wfn=True) for i in range(5): assert compare_values(wfn_tdhf.variable(f'TD-HF ROOT 0 -> ROOT {i+1} EXCITATION ENERGY'), wfn_adc.variable(f'ADC ROOT 0 -> ROOT {i+1} EXCITATION ENERGY'), 5, f"PE-ADC(1) Excitation Energy Root {i+1}")
def test_mp2(mol_str): mol_str = quest.mollib[mol_str] basis = "sto-3g" rhf_options = \ { 'e_conv': 1.e-8, 'd_conv': 1.e-8, 'diis': True, 'max_diis': 7, 'max_iter': 100, } molecule = quest.Molecule(mol_str, basis) wfn = quest.Wavefunction(molecule, rhf_options) scf_energy = quest.scf_module.compute_rhf(wfn) mp2_energy = quest.mp2.mp2(wfn) psi4.set_options({"scf_type": "pk", "mp2_type": "conv"}) ref_energy = psi4.energy("MP2" + "/" + basis, molecule=molecule.mol) assert np.allclose(mp2_energy, ref_energy)