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 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_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 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 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_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 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 __init__(self, filename = 'Options.ini'): config = configparser.ConfigParser() # using configparser to read in options from input config.read(filename) self.mol = psi4.geometry(config['DEFAULT']['molecule']) self.mol.update_geometry() basis = psi4.core.BasisSet.build(self.mol, 'BASIS', config['DEFAULT']['basis']) mints = psi4.core.MintsHelper(basis) # using mints from psi4 for integrals self.max_iter = int(config['SCF']['max_iter']) self.ntot = mints.basisset().nbf() # number of total orbitals self.nelec = -self.mol.molecular_charge() for A in range(self.mol.natom()): self.nelec += int(self.mol.Z(A)) self.ndocc = int(self.nelec/2) # number of doubly occupied orbitals S = mints.ao_overlap().to_array() # one electron overlap integral T = mints.ao_kinetic().to_array() # one electron kinetic energy integral V = mints.ao_potential().to_array() # one electron potential energy integral self.G = mints.ao_eri().to_array() # two-electron integrals self.H = T + V # hamiltonian self.C = np.zeros_like(self.H) # eigenvectors self.e = np.zeros(len(self.H)) # orbital energies self.E_SCF = 0.0 self.A = np.matrix(la.inv(la.sqrtm(S))) # orthogonalizer
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_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_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_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 __init__(self, centers, basis_name ): """ """ # Create the molecule object that we need mol_string = "" self.center_numbers = [] self.centers = [] cent_num = -1 for i, center in enumerate(centers): if center not in self.centers[:i]: self.centers.append(Vector(center)) mol_string += "H {} {} {}\n".format(center[0], center[1], center[2]) cent_num += 1 self.center_numbers.append(cent_num) else: self.center_numbers.append(self.centers.index(center)) self.molecule = psi4.geometry("symmetry c1\n" + mol_string.strip()) #----------------------------------------# # Create the BasisSet objects needed self.basis_name = basis_name psi4.options.basis = self.basis_name self.basis = BasisSet.construct(IntDataSet.parser, self.molecule, 'BASIS') #----------------------------------------# # Create the MintsHelper and the factories self.mints = MintsHelper(self.basis) self.factory = self.mints.integral() #----------------------------------------# # Create the list of IntData objects self.int_data = {}
def __init__(self, options_ini): self.config = configparser.ConfigParser() self.config.read(options_ini) self.molecule = psi4.geometry(self.config['DEFAULT']['molecule']) self.molecule.update_geometry() self.V_nuc = self.molecule.nuclear_repulsion_energy() self.options = {} self.options['BASIS'] = self.config['DEFAULT']['basis'] self.options['SCF_MAX_ITER'] = self.config.getint('SCF', 'max_iter', fallback=50) self.options['DIIS'] = self.config.getboolean('SCF', 'diis', fallback=True) self.options['DIIS_NVECTOR'] = self.config.getint('SCF', 'diis_nvector', fallback=6) self.options['DIIS_START'] = self.config.getint('SCF', 'diis_start', fallback=6) self.basis = psi4.core.BasisSet.build(self.molecule, 'BASIS', self.options['BASIS'], puream=0) self.mints = psi4.core.MintsHelper(self.basis) self.S = self.mints.ao_overlap().to_array() self.T = self.mints.ao_kinetic().to_array() self.V = self.mints.ao_potential().to_array() self.g = self.mints.ao_eri().to_array() self.H = self.T + self.V A = self.mints.ao_overlap() A.power(-0.5, 1.e-16) self.A = A.to_array() self.spin = 0
def __init__(self, options): mol = psi4.geometry( options['DEFAULT']['molecule'] ) mol.update_geometry() self.basisName = options['DEFAULT']['basis'] self.basis = psi4.core.BasisSet.build(mol, "BASIS", self.basisName, puream=0) self.getIntegrals() mult = mol.multiplicity() nelec = self.getNelec(mol) self.Vnu = mol.nuclear_repulsion_energy() self.maxiter = int( options['SCF']['max_iter'] ) self.conv = 10**( -int(options['SCF']['conv']) ) self.dConv = 10**( -int(options['SCF']['d_conv']) ) self.Na = int( 0.5*(nelec+mult-1) ) self.Nb = nelec - self.Na self.Da = np.zeros((self.X.shape)) self.Db = np.zeros((self.X.shape)) self.E = 0.0 self.converged = False self.options = options
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_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_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 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_mp2d(): 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 """) mol = eneyne.to_schema(dtype=2) expected = 0.00632174635953 resinp = { 'schema_name': 'qcschema_input', 'schema_version': 1, 'molecule': mol, 'driver': 'energy', #gradient', 'model': { 'method': 'mp2d-mp2-dmp2' }, 'keywords': {}, } jrec = qcng.compute(resinp, 'mp2d', raise_error=True) jrec = jrec.dict() assert psi4.compare_values(expected, jrec['extras']['qcvars']['CURRENT ENERGY'], 7, 'E') assert psi4.compare_values(expected, jrec['extras']['qcvars']['DISPERSION CORRECTION ENERGY'], 7, 'disp E') assert psi4.compare_values(expected, jrec['extras']['qcvars']['MP2-DMP2 DISPERSION CORRECTION ENERGY'], 7, 'mp2d disp E')
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 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_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 pe_wfn_qcvars(): psi4.core.clean_variables() he = psi4.geometry('He') wfn = psi4.core.Wavefunction.build(he, 'cc-pvdz') for pv, pvv in _vars_entered.items(): psi4.core.set_variable(pv, pvv) wfn.set_variable(pv, pvv) 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 tddft_systems(): psi4.core.clean() # Canonical unrestricted system ch2 = psi4.geometry("""0 3 C 0.000000 0.000000 0.159693 H -0.000000 0.895527 -0.479080 H -0.000000 -0.895527 -0.479080 no_reorient no_com """) # Canonical restricted system 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 no_reorient no_com """) return {'UHF': ch2, 'RHF': h2o}
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_water(): mol = psi4.geometry(""" O H 1 1.1 H 1 1.1 2 104.5 """) rhf_object = qp.RHF(mol, "sto-3g") rhf_energy = rhf_object.compute_energy() assert rhf_energy == pytest.approx(-74.9418022615317909, 1.e-5) mp2_object = qp.MP2(rhf_object) mp2_energy = mp2_object.compute_energy() assert mp2_energy == pytest.approx(-74.9908766157, 1.e-5)
def compute_DFMP2(Settings, silent=False): t0 = time.time() printif = print if not silent else lambda *k, **w: None Escf, Ca, Cb, epsa, epsb, = compute_uhf(Settings, return_C=True, return_integrals=False) printif(""" =================================================== Density-Fitting Spin-Orbital Møller-Plesset Perturbation Theory {} =================================================== """.format('\U0001F347' + '\U000027A1' + emoji('wine'))) tasks = """ Building: \U0001F426 Spin-Orbital arrays {} \U0001F986 J^(-1/2) (P|Q) {} \U0001F989 (uv|P) {} \U0001F9A2 b(ia|Q) {}""" printif(tasks.format('','','','')) # Create Spin-Orbital arrays tsave = [] t = time.time() C = np.block([ [Ca, np.zeros(Ca.shape)], [np.zeros(Cb.shape), Cb] ]) eps = np.concatenate((epsa, epsb)) nmo = len(eps) ## Sorting orbitals s = np.argsort(eps) eps = eps[s] C = C[:,s] tsave.append(time.time() -t) show_progress(tsave, printif) # Create slices nelec = Settings['nalpha'] + Settings['nbeta'] o = slice(0, nelec) v = slice(nelec, nmo) # Build J^(-1/2) using Psi4 t = time.time() molecule = psi4.geometry(Settings['molecule']) basis = psi4.core.BasisSet.build(molecule, 'BASIS', Settings['basis'], puream=0) dfbasis = psi4.core.BasisSet.build(molecule, 'DF_BASIS_MP2', Settings['df_basis'], puream=0) mints = psi4.core.MintsHelper(basis) zero = psi4.core.BasisSet.zero_ao_basis_set() Jinvs = np.squeeze(mints.ao_eri(dfbasis, zero, dfbasis, zero).np) Jinvs = psi4.core.Matrix.from_array(Jinvs) Jinvs.power(-0.5, 1.e-14) Jinvs = Jinvs.np tsave.append(time.time()-t) show_progress(tsave, printif) # Get integrals uvP t = time.time() ao_uvP = np.squeeze(mints.ao_eri(basis, basis, dfbasis, zero).np) fh = slice(0, int(nmo/2)) sh = slice(int(nmo/2), nmo) ## Build spin-blocks uvP = np.zeros((nmo, nmo, ao_uvP.shape[2])) uvP[fh, fh, :] = ao_uvP uvP[sh, sh, :] = ao_uvP tsave.append(time.time()-t) show_progress(tsave, printif) # Get b(iaP) t = time.time() biaQ = np.einsum('ui, va, uvP, PQ -> iaQ', C[:,o], C[:, v], uvP, Jinvs, optimize='optimal') tsave.append(time.time()-t) show_progress(tsave, printif) # Get MP2 energy printif('\n{} Computing DF-MP2 energy'.format('\U0001F9ED'), end= ' ') t = time.time() Emp2 = 0 new = np.newaxis eo = eps[o] ev = eps[v] for i in range(nelec): for j in range(nelec): D = -ev[:, new] - ev[new, :] D = D + eo[i] + eo[j] D = 1.0/D bAB = np.einsum('aQ, bQ-> ab', biaQ[i,:,:], biaQ[j,:,:]) bBA = np.einsum('bQ, aQ-> ab', biaQ[i,:,:], biaQ[j,:,:]) Emp2 += np.einsum('ab, ab->', np.square(bAB-bBA), D, optimize='optimal') Emp2 = Emp2/4.0 tsave.append(time.time()-t) printif('\n{} DF-MP2 Correlation Energy: {:>16.10f}'.format(emoji('bolt'), Emp2)) printif('\U0001F308 Final Electronic Energy: {:>16.10f}'.format(Emp2+Escf)) printif('\n{} Total Computation time: {:10.5f} seconds'.format('\U0000231B',time.time() - t0)) # Compare results with SO-MP2 printif('\n \U0001F4C8 Comparing results with regular MP2:') t0 = time.time() E0mp2 = compute_SOMP2(Settings, psi4compare=False, silent=True) printif('\n{} MP2 Correlation Energy: {:>16.10f}'.format(emoji('bolt'), E0mp2)) printif('{} DF error: {:>16.10f}'.format('\U0000274C', E0mp2-Emp2)) printif('\n{} Total Computation time: {:10.5f} seconds'.format('\U0000231B',time.time() - t0)) # Compare with Psi4 psi4.set_options({'basis': Settings['basis'], 'df_basis_mp2' : Settings['df_basis'], 'e_convergence' : 1e-12, 'scf_type': 'pk', 'puream' : False, 'reference': 'uhf'}) psi4_mp2 = psi4.energy('mp2') printif('\n\n{} Psi4 DF-MP2 Energy: {:>16.10f}'.format(emoji('eyes'), psi4_mp2))
def run_psi4_adi(q, params_, full_id): """ This function executes the Psi4 quantum chemistry calculations and returns the key properties needed for dynamical calculations. Args: q ( MATRIX(ndof, ntraj) ): coordinates of the particles [ units: Bohr ] params ( dictionary ): model parameters * **params["labels"]** ( list of strings ): the labels of atomic symbolc - for all atoms, and in a order that is consistent with the coordinates (in triples) stored in `q`. The number of this labels is `natoms`, such that `ndof` = 3 * `natoms`. [ Required ] * **params["nstates"]** ( int ): the total number of electronic states in this model [ default: 1 - just the ground state ] * **params["grad_method_gs"]** ( string ): the name of the methodology to compute the energy and gradients on the ground state [ defaut: "ccsd/sto-3g" ] Examples: "pbe/sto-3g", "mp2/aug-cc-pVDZ", "ccsd/aug-cc-pVDZ" # ground state energies, gradients * **params["grad_method_ex"]** ( string ): the name of the methodology to compute the energy and gradients on the excited states [ defaut: "eom-ccsd/sto-3g" ] Examples: "eom-ccsd/aug-cc-pVDZ", # excited state energies, gradients If you need just excited state energies (but not gradients), consider: "cisd/aug-cc-pVDZ", adc/aug-cc-pVDZ * **params["charge"]** ( int ): the total charge of the system [ default: 0 ] * **params["spin_multiplicity"]** ( int ): the total spin multiplicity [ default: 1 - singlet ] * **params["options"]** ( dictionary ): additional parameters of calculations [ default: empty ] Examples: - {} - noting extra - {'reference':'rohf'}, - {'roots_per_irrep':[3, 0, 0, 0], 'prop_root':1, 'reference':'rohf'} - {'num_roots':3, 'follow_root':2, 'reference':'rohf'} - for state-resolved gradients * **params["verbosity"]** ( int ): the level of output of the execution-related information [ default : 0] full_id ( intList ): the "path" to the Hamiltonian in the Hamiltonian's hierarchy. Usually, this is Py2Cpp_int([0, itraj]) - the index of the trajectory in a swarm of trajectories Returns: PyObject: obj, with the members: * obj.ham_adi ( CMATRIX(nstates,nstates) ): adiabatic Hamiltonian * obj.hvib_adi ( CMATRIX(nstates,nstates) ): vibronic Hamiltonian in the adiabatic basis * obj.d1ham_adi ( list of ndof CMATRIX(nstates, nstates) objects ): derivatives of the adiabatic Hamiltonian w.r.t. the nuclear coordinate """ # Make a copy of the input parameters dictionary params = dict(params_) # Defaults critical_params = ["labels"] default_params = { "nstates": 1, "grad_method_gs": "ccsd/sto-3g", "grad_method_ex": "eom-ccsd/sto-3g", "charge": 0, "spin_multiplicity": 1, "options": {}, "verbosity": 0 } comn.check_input(params, default_params, critical_params) # Extract the key variables grad_method_gs = params["grad_method_gs"] grad_method_ex = params["grad_method_ex"] charge = params["charge"] spin_multiplicity = params["spin_multiplicity"] labels = params["labels"] nstates = params["nstates"] options = params["options"] verbosity = params["verbosity"] natoms = len(labels) ndof = 3 * natoms obj = tmp() obj.ham_adi = CMATRIX(nstates, nstates) obj.hvib_adi = CMATRIX(nstates, nstates) obj.d1ham_adi = CMATRIXList() for idof in range(ndof): obj.d1ham_adi.append(CMATRIX(nstates, nstates)) Id = Cpp2Py(full_id) indx = Id[-1] # Setup and execute the PSI4 calculations psi4.core.set_output_file('tmp.dat', False) coords_str = scan.coords2xyz(labels, q, indx) mol = psi4.geometry(F""" {charge} {spin_multiplicity} {coords_str } units bohr """) for istate in range(nstates): E, grad = None, None if istate == 0: # Compute the energy if verbosity > 0: print("Doing state 0 energy") E, wfc = psi4.energy(grad_method_gs, molecule=mol, return_wfn=True) # Compute force at the converged density if verbosity > 0: print("Doing state 0 gradient") grad = np.asarray(psi4.gradient(grad_method_gs, ref_wfn=wfc)) else: opt = dict(options) opt.update({ 'prop_root': istate, 'roots_per_irrep': [3, 0, 0, 0], 'reference': 'rohf' }) psi4.set_options(opt) # Compute the energy if verbosity > 0: print(F"Doing state {istate} energy") E, wfc = psi4.energy(grad_method_ex, molecule=mol, return_wfn=True) # Compute force at the converged density if verbosity > 0: print(F"Doing state {istate} gradient") grad = np.asarray(psi4.gradient(grad_method_ex, ref_wfn=wfc)) obj.ham_adi.set(istate, istate, E * (1.0 + 0.0j)) obj.hvib_adi.set(istate, istate, E * (1.0 + 0.0j)) for iatom in range(natoms): obj.d1ham_adi[3 * iatom + 0].set(istate, istate, grad[iatom, 0] * (1.0 + 0.0j)) obj.d1ham_adi[3 * iatom + 1].set(istate, istate, grad[iatom, 1] * (1.0 + 0.0j)) obj.d1ham_adi[3 * iatom + 2].set(istate, istate, grad[iatom, 2] * (1.0 + 0.0j)) return obj
__copyright__ = "(c) 2014-2018, The Psi4NumPy Developers" __license__ = "BSD-3-Clause" __date__ = "2017-05-16" import numpy as np import psi4 import os import sys sys.path.append('./') import md_helper psi4.core.set_output_file('md_output.dat', False) molec = psi4.geometry(""" H 0 0 0 H 0 0 1 """) # Global Constants (Atomic Units conversion) fs_timeau = 41.34137314 amu2au = 1822.8884850 #MD Options timestep = 5 # Time step for each iteration in time atomic units max_md_step = 100 # Number of MD iterations veloc0 = np.zeros((2, 3)) # Numpy array (natoms,3) with inital velocities trajec = True # Boolean: Save all trajectories in a single xyz file (md_trajectories) for visualization grad_method = 'hf/3-21g' # Method (QC with basis set) for energy and gradient int_alg = 'veloc_verlet' # Algorithm to use as integrator opt = False # Optimize geometry using F=ma
def test_dipole_h2_2_field(): """H2 dimer""" psi4.set_memory('2 GiB') psi4.core.set_output_file('output.dat', False) psi4.set_options({ 'basis': '6-31G', '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["(H2)_2"]) 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) # narrow Gaussian pulse F_str = 0.01 sigma = 0.01 center = 0.05 V = gaussian_laser(F_str, 0, sigma, center=center) rtcc = pycc.rtcc(cc, cclambda, ccdensity, V, magnetic=True) mints = psi4.core.MintsHelper(cc.ref.basisset()) dipole_ints = mints.ao_dipole() m_ints = mints.ao_angular_momentum() C = np.asarray(cc.ref.Ca_subset("AO", "ACTIVE")) ref_mu = [] ref_m = [] for axis in range(3): ref_mu.append(C.T @ np.asarray(dipole_ints[axis]) @ C) ref_m.append(C.T @ (np.asarray(m_ints[axis]) * -0.5) @ C) assert np.allclose(ref_mu[axis], rtcc.mu[axis]) assert np.allclose(ref_m[axis] * 1.0j, rtcc.m[axis]) ref_mu_tot = sum(ref_mu) / np.sqrt(3.0) assert np.allclose(ref_mu_tot, rtcc.mu_tot) rtcc = pycc.rtcc(cc, cclambda, ccdensity, V, magnetic=True, kick="Y") mints = psi4.core.MintsHelper(cc.ref.basisset()) dipole_ints = mints.ao_dipole() m_ints = mints.ao_angular_momentum() C = np.asarray(cc.ref.Ca_subset("AO", "ACTIVE")) ref_mu = [] ref_m = [] for axis in range(3): ref_mu.append(C.T @ np.asarray(dipole_ints[axis]) @ C) ref_m.append(C.T @ (np.asarray(m_ints[axis]) * -0.5) @ C) assert np.allclose(ref_mu[axis], rtcc.mu[axis]) assert np.allclose(ref_m[axis] * 1.0j, rtcc.m[axis]) assert np.allclose(ref_mu[1], rtcc.mu_tot)
def ishida_morokuma(params, output_file): """ This function runs the Ishida-Morokuma irc procedure """ max_steps = 1000 #params = Params() line_step_size = 0.3333 * params.step_size #line_step_size = 0.025*params.step_size current_geom = params.geometry mol = psi4.geometry(params.geometry) starting_vec = np.asarray(params.ts_vec) grad_method = "%s/%s" % (params.method, params.basis) steps = 0 E = 0.0 previous_E = 0.0 del_E = 0.0 energies = [] current_geom = np.asarray(mol.geometry()) #print(current_geom) output = open(output_file, "a") output.write('\n\n--Intrinsic Reaction Coordinate (%s)--\n' % (params.direction)) output.write( '\n--------------------------------------------------------------------------------------\n' ) output.write('\n{:>20} {:>20} {:>20} {:>20}\n'.format( 'Coordinate', 'E', 'Delta E', 'Gradient Norm')) output.write( '-------------------------------------------------------------------------------------\n' ) output.close() last_energy = None while (steps <= max_steps): if (steps == 0): grad_0 = mass_weight(params.natoms, starting_vec, mol) E_0 = energy_calc(params, current_geom, mol) else: grad_0, E_0 = grad_calc(params, current_geom, mol) if (last_energy): del_E = E_0 - last_energy if ((last_energy and (E_0 > last_energy) and steps > params.grace_period)): output = open(output_file, "a") print( "\nIRC Energy Has Increased! You're Likely Near a Minimum!\n") output.close() break if (last_energy and np.abs(del_E) < params.e_conv and steps > params.grace_period): output = open(output_file, "a") print("\nIRC Has Converged!\n") output.close() break mol.save_xyz_file('imk_step_' + str(steps) + '.xyz', False) coords_1 = euler_step(params.natoms, current_geom, grad_0, params.step_size, mol) current_geom = coords_1 #mol.set_geometry(psi4.core.Matrix.from_array(current_geom)) grad_1, E_1 = grad_calc(params, current_geom, mol) grad_0_norm = np.linalg.norm(grad_0) grad_1_norm = np.linalg.norm(grad_1) # Calculate Bisector (Eq. 6) D = grad_0 / grad_0_norm - grad_1 / grad_1_norm D_normed = D / np.linalg.norm(D) line_xs = [ 0, ] line_energies = [ E_1, ] line_step_size_thresh = 1.5 * line_step_size #line_step_size_thresh = 2.0*line_step_size # Find useful point by projecting grad_1 on D grad_1_normed = grad_1 / grad_1_norm step_D1 = grad_1 * D_normed * D_normed * line_step_size step_D1_norm = np.linalg.norm(step_D1) # if step_D1_norm < line_step_size_thresh: # coords_1 = mass_weight_geom(params.natoms, coords_1, mol) # current_geom = coords_1 + step_D1 # current_geom = un_mass_weight_geom(params.natoms, current_geom, mol) # mol.set_geometry(psi4.core.Matrix.from_array(current_geom)) # step_D1_E = psi4.energy(grad_method) # line_xs.append(step_D1_norm) # line_energies.append(step_D1_E) # Otherwise take a step along D # else: step_D2 = line_step_size * D_normed step_D2_norm = np.linalg.norm(step_D2) coords_1 = mass_weight_geom(params.natoms, coords_1, mol) current_geom = coords_1 + step_D2 current_geom = un_mass_weight_geom(params.natoms, coords_1, mol) #mol.set_geometry(psi4.core.Matrix.from_array(current_geom)) #step_D2_E = psi4.energy(grad_method) step_D2_E = energy_calc(params, current_geom, mol) #line_xs.append(step_D2_norm) line_xs.append(step_D2_norm) line_energies.append(step_D2_E) # Calculate 3rd point by taking a half step size if (line_energies[1] >= line_energies[0]): step_D3 = 0.5 * line_step_size * D_normed # Half Step Size #new_del = 0.5*line_step_size else: step_D3 = 2.0 * line_step_size * D_normed #Double Step Size #new_del = 2.0*line_step_size step_D3_norm = np.linalg.norm(step_D3) #coords_1 = mass_weight_geom(params.natoms, coords_1, mol) current_geom = coords_1 + step_D3 current_geom = un_mass_weight_geom(params.natoms, current_geom, mol) #mol.set_geometry(psi4.core.Matrix.from_array(current_geom)) #step_D3_E = psi4.energy(grad_method) step_D3_E = energy_calc(params, current_geom, mol) line_xs.append(step_D3_norm) line_energies.append(step_D3_E) real_minimum = parabolic_fit(line_xs, line_energies) current_geom = coords_1 + (real_minimum * D_normed) current_geom = un_mass_weight_geom(params.natoms, current_geom, mol) mol.set_geometry(psi4.core.Matrix.from_array(current_geom)) last_energy = E_0 #params.damp -= 0.5 if (params.direction == "backward"): coord = -1 * steps * params.step_size else: coord = steps * params.step_size print_step(output_file, coord, E_0, del_E, grad_0_norm) steps = steps + 1 output = open(output_file, "a") output.write( '-------------------------------------------------------------------------------------\n' ) output.close() with open('irc_%s.xyz' % params.direction, 'w') as outfile: for i in range(steps): with open('imk_step_' + str(i) + '.xyz') as infile: outfile.write(infile.read()) os.system('rm imk_step*')
for ix in range(coeff.shape[0] - 1): F_diis += coeff[ix]*F_list[ix] return F_diis psi4.core.set_output_file('output.dat', False) bond_dist = 1.4632*bohr2ang cmpd = 'HeH' # here is how we define the geometry mol = psi4.geometry(""" He H 1 {: .5f} symmetry c1 """.format(bond_dist)) the_basis = 'sto-3g' psi4.set_options({'guess':'core', 'basis':'{}'.format(the_basis), 'scf_type':'pk', 'e_convergence':1e-8, 'reference': 'uhf'}) mol.set_molecular_charge(1) maxiter = 40 # energy convergence criterion E_conv = 1.0e-6
__copyright__ = "(c) 2014-2018, The Psi4NumPy Developers" __license__ = "BSD-3-Clause" __date__ = "2014-07-29" import time import numpy as np from helper_CC import * np.set_printoptions(precision=5, linewidth=200, suppress=True) import psi4 psi4.set_memory('2 GB') 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.set_options({'basis': 'cc-pvdz'}) # CCSD settings E_conv = 1.e-8 maxiter = 20 max_diis = 8 compare_psi4 = True freeze_core = False # Build CCSD object ccsd = helper_CCSD(mol, memory=2)
# examples/api/04_casscf-triplet-guess.py """Example of a CASSCF computation on singlet methylene starting from triplet ROHF orbitals (from psi4)""" import psi4 import forte psi4.geometry(""" 0 3 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__multiplicity': 1, # <-- to override multiplicity = 3 assumed from geometry 'forte__active_space_solver': 'fci', 'forte__restricted_docc': [1, 0, 0, 0], 'forte__active': [3, 0, 2, 2], } ) psi4.energy('forte', ref_wfn=wfn)
return G # psi4 introduction! # first we can set an outfile if we want to dump all the calc info psi4.core.set_output_file('output.dat', False) bond_dist = 1.4632 * bohr2ang cmpd = 'HeH+' # here is how we define the geometry mol = psi4.geometry(''' He H 1 {: .5f} symmetry c1 '''.format(bond_dist)) # set charge to positive 1 mol.set_molecular_charge(1) mol.set_multiplicity(1) the_basis = 'sto-3g' # the_basis = 'cc-pvtz' # set our calculation options # our guess is the core guess, -> can also be sad (superposition of atomic densities) # scf_type -> ERI algorithm, pk is default # reference -> rhf, uhf, and maybe rohf psi4.set_options({
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')
# |+++++++|###########| -----." _'#######' +++++++++++\ # # |+++++++|############\. \\ // /#######/++++ S@yaN +++\ # # _ _ _ _____ _ # # | | | | __ _ _ __ | |_ _ __ ___ ___ | ___|___ ___ | | __ # # | |_| | / _` || '__|| __|| '__|/ _ \ / _ \ _____ | |_ / _ \ / __|| |/ / # # | _ || (_| || | | |_ | | | __/| __/|_____|| _|| (_) || (__ | < # # |_|_|_| \__,_||_| _ \__||_| \___| \___| |_| \___/ \___||_|\_| # ######################################################################################""" # SETUP INITIAL CONDITIONS print(shrek) psi4.core.be_quiet() print('\nReading input...', end=' ') molecule = psi4.geometry(Settings['molecule']) molecule.update_geometry() if Settings['nalpha'] != Settings['nbeta']: raise NameError('No open shell stuff plz') ndocc = Settings['nalpha'] Vnuc = molecule.nuclear_repulsion_energy() basis = psi4.core.BasisSet.build(molecule, 'BASIS', Settings['basis']) mints = psi4.core.MintsHelper(basis) scf_max_iter = Settings['scf_max_iter'] print(emoji('check'))
def test_mdi_water(): psi4.geometry(""" 0 1 O H 1 1.0 H 1 1.0 2 104.5 """) psi4.set_options({ 'reference': 'uhf', 'scf_type': 'direct', 'e_convergence': 1e-12, }) scf_method = "scf/cc-pVDZ" psi4.mdi_engine.mdi_init("-role DRIVER -name Psi4 -method TEST") engine = psi4.mdi_engine.MDIEngine(scf_method) # Test the <NATOMS command natom = engine.send_natoms() assert natom == 3 # Test the <COORDS command coords = engine.send_coords() expected = [ 0.0, 0.0, -0.12947688966627896, 0.0, -1.4941867446308548, 1.027446098871551, 0.0, 1.4941867446308548, 1.027446098871551 ] assert compare_values(expected, coords, atol=1.e-7) # Test the >COORDS command expected = [ 0.1, 0.0, -0.12947688966627896, 0.0, -1.4341867446308548, 1.027446098871551, 0.0, 1.4941867446308548, 1.027446098871551 ] engine.recv_coords(expected) coords = engine.send_coords() assert compare_values(expected, coords, atol=1.e-7) # Test the <CHARGES command charges = engine.send_charges() expected = [8.0, 1.0, 1.0] assert compare_values(expected, charges, atol=1.e-7) # Test the <ELEMENTS command elements = engine.send_elements() expected = [8.0, 1.0, 1.0] assert compare_values(expected, elements, atol=1.e-7) # Test the <MASSES command masses = engine.send_masses() expected = [15.99491461957, 1.00782503223, 1.00782503223] assert compare_values(expected, masses, atol=1.e-6) # Test the SCF command engine.run_scf() # Test the <ENERGY command energy = engine.send_energy() expected = -76.02320201768676 assert compare_values(expected, energy, atol=1.e-6) # Test the <FORCES command forces = engine.send_forces() expected = [ 0.004473733542292732, -0.01775852359379196, -0.051757651796320636, -0.0016762687719661835, -0.024093270269019917, 0.019393138772564877, -0.0027974647702799747, 0.04185179386282589, 0.03236451302360538 ] assert compare_values(expected, forces, atol=1.e-6) # Test the >MASSES command expected = [15.99491461957, 3.0, 2.0] engine.recv_masses(expected) masses = engine.send_masses() assert compare_values(expected, masses, atol=1.e-7) # Test the <DIMENSIONS command expected = [1, 1, 1] dimensions = engine.send_dimensions() assert compare_values(expected, dimensions, atol=1.e-7) # Test the <TOTCHARGE command totcharge = engine.send_total_charge() expected = 0.0 assert compare_values(expected, totcharge, atol=1.e-7) # Test the >TOTCHARGE command expected = 1.0 engine.recv_total_charge(expected) totcharge = engine.send_total_charge() assert compare_values(expected, totcharge, atol=1.e-7) # Test the <ELEC_MULT command multiplicity = engine.send_multiplicity() expected = 1 assert compare_values(expected, multiplicity, atol=1.e-7) # Test the >ELEC_MULT command expected = 2 engine.recv_multiplicity(expected) multiplicity = engine.send_multiplicity() assert compare_values(expected, multiplicity, atol=1.e-7) # Test the >NLATTICE, >CLATTICE, and >LATTICE commands nlattice = 2 clattice = [-3.0, 1.0, 0.0, 4.0, 3.0, 0.0] lattice = [-1.0, -0.5] engine.recv_nlattice(nlattice) engine.recv_clattice(clattice) engine.recv_lattice(lattice) # Test the final energy engine.run_scf() energy = engine.send_energy() expected = -76.03284774075954 assert compare_values(expected, energy, atol=1.e-6) forces = engine.send_forces() expected = [ 0.032656171616, -0.027255620629, -0.02211206073, 0.015827924001, -0.009687198705, 0.011685024025, 0.026352703866, 0.008313469614, 0.033873286169, ] assert compare_values(expected, forces, atol=1.e-6) # Test the EXIT command engine.exit() return 0
# Summary: optimizes intermolecular coordinates between two frozen monomers. # Split dimers in input with "--" mol = psi4.geometry(""" N1 0.843999981880188 0.4560000002384186 0.9229999780654907 H2 1.371999979019165 0.4950000047683716 1.7979999780654907 C3 1.6430000066757202 1.125 -0.11299999803304672 H4 2.0 2.0969998836517334 0.24300000071525574 H5 0.9869999885559082 1.3070000410079956 -0.9710000157356262 C6 2.7790000438690186 0.15299999713897705 -0.5040000081062317 H7 3.688999891281128 0.3840000033378601 0.05900000035762787 H8 3.0309998989105225 0.22200000286102295 -1.565999984741211 C9 2.2309999465942383 -1.2400000095367432 -0.1120000034570694 H10 2.865999937057495 -1.7070000171661377 0.6470000147819519 H11 2.184999942779541 -1.9279999732971191 -0.9620000123977661 C12 0.8299999833106995 -0.9409999847412109 0.4690000116825104 H13 0.5419999957084656 -1.6089999675750732 1.2860000133514404 H14 0.06800000369548798 -1.0269999504089355 -0.3140000104904175 -- x 2 1.0 1 90.00 12 dih O 2 rAH 15 90.00 1 180.00 H 16 0.9572 2 127.74 15 0.0 H 16 0.9572 2 127.74 15 180.0 rAH = 2.0 dih = 0.0 nocom unit angstrom """) # Ordering of reference atoms is essential for properly defining contraints. # Note that if either of the theta angles are linear. optking will crash.
H 5 R 3 P 4 T H 5 D 6 P 3 X H 7 R 5 P 6 T R = 0.75 D = 1.5 P = 90.0 T = 60.0 X = 180.0 symmetry c1 """)''' mol = psi4.geometry(""" O -0.028962160801 -0.694396279686 -0.049338350190 O 0.028962160801 0.694396279686 -0.049338350190 H 0.350498145881 -0.910645626300 0.783035421467 H -0.350498145881 0.910645626300 0.783035421467 symmetry c1 """) psi4.set_options({ 'basis': 'sto-3g', 'guess': 'sad', 'scf_type': 'pk', 'e_convergence': 1e-10, 'd_convergence': 1e-10, 'save_jk': 'true' }) # Compute RHF energy with psi4 psi4.set_module_options('SCF', {'E_CONVERGENCE': 1e-10})
try: import psi4 have_psi4 = True except: have_psi4 = False nthreads = 2 # MB-pol optimized water geometry mol = """ O -6.738646395e-02 -1.491617397e+00 -1.095035971e-10 H 8.141855337e-01 -1.866159045e+00 -2.044214632e-10 H 7.436878209e-02 -5.443285903e-01 4.259078718e-11 """ print(mol) method = "BLYP" basis = "cc-pvdz" model = "{}/{}".format(method, basis) if have_psi4: psi4.core.set_output_file("psi4.out", False) psi4.set_memory("1GB") psi4.geometry(mol) psi4.set_num_threads(nthreads) energy = psi4.energy(model) print("E({}) = {}".format(model, energy)) else: print("psi4 not available")
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.6484189450, 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.properties('scf', properties=props) assert psi4.compare_values(psi4.variable("CURRENT ENERGY"), -38.91591819679808, 6, "SCF energy") assert psi4.compare_values(psi4.variable('SCF DIPOLE X'), 0.000000000000, 4, "SCF DIPOLE X") assert psi4.compare_values(psi4.variable('SCF DIPOLE Y'), 0.000000000000, 4, "SCF DIPOLE Y") assert psi4.compare_values(psi4.variable('SCF DIPOLE Z'), 0.572697798348, 4, "SCF DIPOLE Z") assert psi4.compare_values(psi4.variable('SCF QUADRUPOLE XX'), -7.664066833060, 4, "SCF QUADRUPOLE XX") assert psi4.compare_values(psi4.variable('SCF QUADRUPOLE YY'), -6.097755074075, 4, "SCF QUADRUPOLE YY") assert psi4.compare_values(psi4.variable('SCF QUADRUPOLE ZZ'), -7.074596012050, 4, "SCF QUADRUPOLE ZZ") assert psi4.compare_values(psi4.variable('SCF QUADRUPOLE XY'), 0.000000000000, 4, "SCF QUADRUPOLE XY") assert psi4.compare_values(psi4.variable('SCF QUADRUPOLE XZ'), 0.000000000000, 4, "SCF QUADRUPOLE XZ") assert psi4.compare_values(psi4.variable('SCF QUADRUPOLE YZ'), 0.000000000000, 4, "SCF QUADRUPOLE YZ") psi4.properties('B3LYP', properties=props) assert psi4.compare_values(psi4.variable('CURRENT ENERGY'), -39.14134740550916, 6, "B3LYP energy") assert psi4.compare_values(psi4.variable('B3LYP DIPOLE X'), 0.000000000000, 4, "B3LYP DIPOLE X") assert psi4.compare_values(psi4.variable('B3LYP DIPOLE Y'), -0.000000000000, 4, "B3LYP DIPOLE Y") assert psi4.compare_values(psi4.variable('B3LYP DIPOLE Z'), 0.641741521158, 4, "B3LYP DIPOLE Z") assert psi4.compare_values(psi4.variable('B3LYP QUADRUPOLE XX'), -7.616483183211, 4, "B3LYP QUADRUPOLE XX") assert psi4.compare_values(psi4.variable('B3LYP QUADRUPOLE YY'), -6.005896804551, 4, "B3LYP QUADRUPOLE YY") assert psi4.compare_values(psi4.variable('B3LYP QUADRUPOLE ZZ'), -7.021817489904, 4, "B3LYP QUADRUPOLE ZZ") assert psi4.compare_values(psi4.variable('B3LYP QUADRUPOLE XY'), 0.000000000000, 4, "B3LYP QUADRUPOLE XY") assert psi4.compare_values(psi4.variable('B3LYP QUADRUPOLE XZ'), 0.000000000000, 4, "B3LYP QUADRUPOLE XZ") assert psi4.compare_values(psi4.variable('B3LYP QUADRUPOLE YZ'), -0.000000000000, 4, "B3LYP QUADRUPOLE YZ")
functional = results.functional charge = int(results.charge) if results.charge is not None else 0 multiplicity = int( results.multiplicity) if results.multiplicity is not None else 1 sys.argv = [sys.argv[0]] # ----------------------- # Psi4 # ----------------------- psi4.set_memory(os.environ.get('PSI4_MAX_MEMORY') + " MB") psi4.core.set_num_threads(int(os.environ.get('OMP_NUM_THREADS'))) molecule = psi4.geometry(""" {charge} {multiplicity} {atomic_coords} """.format(charge=charge, multiplicity=multiplicity, atomic_coords=atomic_coords)) gradient, wfn = psi4.gradient('uhf/{}'.format(basis_set), molecule=molecule, return_wfn=True) energy = wfn.energy() force = gradient.to_array().tolist() properties = {"energy": energy, "force": force} stringified_properties = json.dumps(properties) print('atoms+bits properties:\n~{}~'.format(stringified_properties))
np.einsum('jkab, ilcd, klcd -> ijab', T, T, anti_tensor[o_sl, o_sl, v_sl, v_sl]) ) + 0.25 * np.einsum( 'ijcd, klab, klcd -> ijab', T, T, anti_tensor[o_sl, o_sl, v_sl, v_sl]) + ( np.einsum('ikac, jlbd, klcd -> ijab', T, T, anti_tensor[o_sl, o_sl, v_sl, v_sl]) - np.einsum('jkac, ilbd, klcd -> ijab', T, T, anti_tensor[o_sl, o_sl, v_sl, v_sl])) for i, j, a, b in np.ndindex(T_new.shape): T[i, j, a, b] = t_sum_0[i, j, a, b] / (evals[i] + evals[j] - evals[s(a)] - evals[s(b)]) energy = np.sum(anti_tensor[o_sl, o_sl, v_sl, v_sl] * T) / 4 print(energy) energy_diff = abs(previous_energy - energy) return energy if __name__ == "__main__": psi4.set_memory('500 MB') h2o = psi4.geometry(""" 1 2 O H 1 1.1 H 1 1.1 2 104.0 """) hf_data = uhf.uhf(h2o)[2:] # Throw away first two data points... # My answers differ from Andreas's in the tenths place. # Likely cause: He did more UHF iterations than I did. print(ccd(*hf_data))
def main(): import sys import numpy as np import psi4 from spatial_to_spin_orbital import spatial_to_spin_orbital_oei from spatial_to_spin_orbital import spatial_to_spin_orbital_tei do_eom_ccsd = True # set molecule mol = psi4.geometry(""" 0 1 O 0.000000000000 0.000000000000 -0.068516219320 H 0.000000000000 -0.790689573744 0.543701060715 H 0.000000000000 0.790689573744 0.543701060715 no_reorient nocom symmetry c1 """) # set options psi4_options_dict = { 'basis': 'sto-3g', 'scf_type': 'pk', 'e_convergence': 1e-10, 'd_convergence': 1e-10 } psi4.set_options(psi4_options_dict) # compute the Hartree-Fock energy and wave function scf_e, wfn = psi4.energy('SCF', return_wfn=True) # number of doubly occupied orbitals no = wfn.nalpha() # total number of orbitals nmo = wfn.nmo() # number of virtual orbitals nv = nmo - no # orbital energies epsilon = np.asarray(wfn.epsilon_a()) # molecular orbitals (spatial): C = wfn.Ca() # use Psi4's MintsHelper to generate integrals mints = psi4.core.MintsHelper(wfn.basisset()) # build the one-electron integrals H = np.asarray(mints.ao_kinetic()) + np.asarray(mints.ao_potential()) H = np.einsum('uj,vi,uv', C, C, H) # unpack one-electron integrals in spin-orbital basis sH = spatial_to_spin_orbital_oei(H, nmo, no) # build the two-electron integrals: tei = np.asarray(mints.mo_eri(C, C, C, C)) # unpack two-electron integrals in spin-orbital basis stei = spatial_to_spin_orbital_tei(tei, nmo, no) # antisymmetrize g(ijkl) = <ij|kl> - <ij|lk> = (ik|jl) - (il|jk) gtei = np.einsum('ikjl->ijkl', stei) - np.einsum('iljk->ijkl', stei) # occupied, virtual slices n = np.newaxis o = slice(None, 2 * no) v = slice(2 * no, None) # build spin-orbital fock matrix fock = sH + np.einsum('piqi->pq', gtei[:, o, :, o]) # orbital energies eps = np.zeros(2 * nmo) for i in range(0, 2 * nmo): eps[i] = fock[i, i] # energy denominators e_abij = 1 / (-eps[v, n, n, n] - eps[n, v, n, n] + eps[n, n, o, n] + eps[n, n, n, o]) e_ai = 1 / (-eps[v, n] + eps[n, o]) nsvirt = 2 * nv nsocc = 2 * no # hartree-fock energy hf_energy = 1.0 * einsum('ii', fock[o, o]) - 0.5 * einsum( 'ijij', gtei[o, o, o, o]) # ccsd iterations from ccsd import ccsd_iterations from ccsd import ccsd_energy t1 = np.zeros((nsvirt, nsocc)) t2 = np.zeros((nsvirt, nsvirt, nsocc, nsocc)) t1, t2 = ccsd_iterations(t1, t2, fock, gtei, o, v, e_ai, e_abij, hf_energy, e_convergence=1e-10, r_convergence=1e-10, diis_size=8, diis_start_cycle=4) cc_energy = ccsd_energy(t1, t2, fock, gtei, o, v) nuclear_repulsion_energy = mol.nuclear_repulsion_energy() print("") print(" CCSD Correlation Energy: {: 20.12f}".format(cc_energy - hf_energy)) print(" CCSD Total Energy: {: 20.12f}".format( cc_energy + nuclear_repulsion_energy)) print("") # check ccsd energy against psi4 assert np.isclose(cc_energy + nuclear_repulsion_energy, -75.019715133639338, atol=1e-9) print( ' CCSD Total Energy..........................................................PASSED' ) print('') if not do_eom_ccsd: return # now eom-ccsd? print(" ==> EOM-CCSD <==") print("") from eom_ccsd import build_eom_ccsd_H # populate core list for super inefficicent implementation of CVS approximation core_list = [] #core_list.append(0) #core_list.append(5) H = build_eom_ccsd_H(fock, gtei, o, v, t1, t2, nsocc, nsvirt, core_list) print(' eigenvalues of e(-T) H e(T):') print('') print(' %5s %20s %20s' % ('state', 'total energy', 'excitation energy')) en, vec = np.linalg.eig(H) en.sort() for i in range(1, min(21, len(en))): print(' %5i %20.12f %20.12f' % (i, en[i] + nuclear_repulsion_energy, en[i] - cc_energy)) print('')
import psi4 import numpy as np # In[2]: # Initial setup psi4.set_memory('2 GB') psi4.set_num_threads(2) file_prefix = 'methane_HF-DZ' ch4 = psi4.geometry(""" symmetry c1 0 1 C -0.85972 2.41258 0.00000 H 0.21028 2.41258 0.00000 H -1.21638 2.69390 -0.96879 H -1.21639 3.11091 0.72802 H -1.21639 1.43293 0.24076 """) # Geometry optimization psi4.set_output_file(file_prefix + '_geomopt.dat', False) psi4.set_options({'g_convergence': 'gau_tight'}) psi4.optimize('scf/cc-pVDZ', molecule=ch4) # In[3]: # Run vibrational frequency analysis psi4.set_output_file(file_prefix + '_vibfreq.dat', False) scf_energy, scf_wfn = psi4.frequency('scf/cc-pVDZ',
#! A simple Psi 4 input script to compute MP2 from a RHF reference import psi4 import time import numpy as np psi4.set_output_file("output.dat", False) mol = psi4.geometry(""" H 0.5288 0.1610 0.9359 C 0.0000 0.0000 0.0000 H 0.2051 0.8240 -0.6786 H 0.3345 -0.9314 -0.4496 H -1.0685 -0.0537 0.1921 symmetry c1 """) psi4.set_options({'basis': 'cc-pVDZ'}) # Compute RHF refernce psi4.core.print_out('\nStarting RHF...\n') t = time.time() RHF_E, wfn = psi4.energy('SCF', return_wfn=True) psi4.core.print_out('...RHF finished in %.3f seconds: %16.10f\n' % (time.time() - t, RHF_E)) # Split eigenvectors and eigenvalues into o and v eps_occ = np.asarray(wfn.epsilon_a_subset("AO", "ACTIVE_OCC")) eps_vir = np.asarray(wfn.epsilon_a_subset("AO", "ACTIVE_VIR"))
psi4.set_output_file("output.dat", False) refnuc = 204.01995818061 #TEST refscf = -228.95763005900784 #TEST bz = psi4.geometry(""" X X 1 RXX X 2 RXX 1 90.0 C 3 RCC 2 90.0 1 0.0 C 3 RCC 2 90.0 1 60.0 C1 3 RCC 2 90.0 1 120.0 C 3 RCC 2 90.0 1 180.0 C1 3 RCC 2 90.0 1 240.0 C 3 RCC 2 90.0 1 300.0 # unnecessary comment H1 3 RCH 2 90.0 1 0.0 H 3 RCH 2 90.0 1 60.0 H 3 RCH 2 90.0 1 120.0 H1 3 RCH 2 90.0 1 180.0 H 3 RCH 2 90.0 1 240.0 H 3 RCH 2 90.0 1 300.0 RCC = 1.3915 RCH = 2.4715 RXX = 1.00 """) # Here we specify some of the basis sets manually. They could be written to one or more external # files and included by adding the directory to environment variable PSIPATH # # The format of these external files follows the same format as those below, where there's a [name]
def psi4_sapt(self): self.int_ = [] self.elst_ = [] self.exch_ = [] self.ind_ = [] self.disp_ = [] all_atoms = self.frag_A + self.frag_B au_to_kcal = 627.51 count = 0 output = open(self.outfile, "a") output.write('\n\n--SAPT Decomposition--\n') output.write( '\n-------------------------------------------------------------------------------------------------' ) output.write('\n{:>15} {:>15} {:>15} {:>15} {:>15} {:>15}\n'.format( 'IRC Point', 'E_int(kcal)', 'E_elst(kcal)', 'E_exch(kcal)', 'E_ind(kcal)', 'E_disp(kcal)')) output.write( '-------------------------------------------------------------------------------------------------\n' ) output.close() scale_sapt = False # See if the user is requesting a scaled SAPT0 calculation if (self.keywords['ssapt0_scale'] or self.keywords['SSAPT0_SCALE']): scale_sapt = True for geometry in self.geometries: output = open(self.outfile, "a") psi4.core.set_output_file("psi4_output/irc_%d_sapt.out" % count, False) geometry += "symmetry c1" psi4.geometry(geometry) # Adds fsapt capabilities if (self.do_fsapt): try: os.mkdir('fsapt_output') except FileExistsError: pass try: os.mkdir('s-fsapt_output') except FileExistsError: pass self.keywords[ 'FISAPT_FSAPT_FILEPATH'] = 'fsapt_output/fsapt%d' % count if (scale_sapt): self.keywords[ 'FISAPT_FSSAPT_FILEPATH'] = 's-fsapt_output/fsapt%d' % count psi4.set_options(self.keywords) #print("pyREX:SAPT Calculation on IRC Point %d" %(count)) psi4.set_num_threads(self.nthreads) if (self.set_memory): psi4.set_memory(self.memory_allocation) e_int = psi4.energy(self.method) #TODO: Actually have this create the SAPT files necessary for FSAPT partitioning. Make user options as well # for fragment definitions. Something in the sapt block. if (self.do_fsapt): fsaptA_outfile = open('fsapt_output/fsapt%d/fA.dat' % count, 'w+') if (scale_sapt): s_fsaptA_outfile = open( 's-fsapt_output/fsapt%d/fA.dat' % count, 'w+') for i in range(len(self.monomer_A_labels)): fsaptA_outfile.write("%s" % self.monomer_A_labels[i]) if (scale_sapt): s_fsaptA_outfile.write("%s" % self.monomer_A_labels[i]) for j in range(len(self.monomer_A_frags[i])): if (j == len(self.monomer_A_frags[i]) - 1): fsaptA_outfile.write( " %d \n" % (all_atoms.index(self.monomer_A_frags[i][j]) + 1)) if (scale_sapt): s_fsaptA_outfile.write( " %d \n" % (all_atoms.index( self.monomer_A_frags[i][j]) + 1)) else: fsaptA_outfile.write( " %d " % (all_atoms.index(self.monomer_A_frags[i][j]) + 1)) if (scale_sapt): s_fsaptA_outfile.write( " %d " % (all_atoms.index( self.monomer_A_frags[i][j]) + 1)) fsaptA_outfile.close() s_fsaptA_outfile.close() fsaptB_outfile = open('fsapt_output/fsapt%d/fB.dat' % count, 'w+') if (scale_sapt): s_fsaptB_outfile = open( 's-fsapt_output/fsapt%d/fB.dat' % count, 'w+') for i in range(len(self.monomer_B_labels)): fsaptB_outfile.write("%s" % self.monomer_B_labels[i]) if (scale_sapt): s_fsaptB_outfile.write("%s" % self.monomer_B_labels[i]) for j in range(len(self.monomer_B_frags[i])): if (j == len(self.monomer_B_frags[i]) - 1): fsaptB_outfile.write( " %d \n" % (all_atoms.index(self.monomer_B_frags[i][j]) + 1)) if (scale_sapt): s_fsaptB_outfile.write( " %d \n" % (all_atoms.index( self.monomer_B_frags[i][j]) + 1)) else: fsaptB_outfile.write( " %d " % (all_atoms.index(self.monomer_B_frags[i][j]) + 1)) if (scale_sapt): s_fsaptB_outfile.write( " %d " % (all_atoms.index( self.monomer_B_frags[i][j]) + 1)) fsaptB_outfile.close() s_fsaptB_outfile.close() e_int = psi4.core.variable("SAPT TOTAL ENERGY") e_elst = psi4.core.variable("SAPT ELST ENERGY") e_exch = psi4.core.variable("SAPT EXCH ENERGY") e_ind = psi4.core.variable("SAPT IND ENERGY") e_disp = psi4.core.variable("SAPT DISP ENERGY") self.int_.append(e_int) self.elst_.append(e_elst) self.exch_.append(e_exch) self.ind_.append(e_ind) self.disp_.append(e_disp) output.write( '\n{:>15} {:>15.4f} {:>15.4f} {:>15.4f} {:>15.4f} {:>15.4f}\n'. format(count, e_int * au_to_kcal, e_elst * au_to_kcal, e_exch * au_to_kcal, e_ind * au_to_kcal, e_disp * au_to_kcal)) count = count + 1 output.write( '-------------------------------------------------------------------------------------\n' ) output.close() return self.int_, self.elst_, self.exch_, self.ind_, self.disp_
__copyright__ = "(c) 2014-2018, The Psi4NumPy Developers" __license__ = "BSD-3-Clause" __date__ = "2017-12-17" import time import numpy as np np.set_printoptions(precision=15, linewidth=200, suppress=True) import psi4 psi4.set_memory(int(1e9), False) psi4.core.set_output_file('output.dat', False) psi4.core.set_num_threads(4) mol = psi4.geometry(""" O H 1 R H 1 R 2 104 symmetry c1 """) # physical constants changed, so geometry changes slightly from pkg_resources import parse_version if parse_version(psi4.__version__) >= parse_version("1.3a1"): mol.R = 1.1 * 0.52917721067 / 0.52917720859 else: mol.R = 1.1 psi4.core.set_active_molecule(mol) options = {'BASIS':'STO-3G', 'SCF_TYPE':'PK', 'E_CONVERGENCE':1e-10, 'D_CONVERGENCE':1e-10
def test_dft_atomic_blocking(): """calculate XC energy per atom with psi4numpy""" mol = psi4.geometry(""" 0 1 O 0.000000000000 0.000000000000 -0.068516219310 H 0.000000000000 -0.790689573744 0.543701060724 H 0.000000000000 0.790689573744 0.543701060724 no_com no_reorient symmetry c1 """) psi4.set_options({ "BASIS": "def2-SVP", "DFT_BLOCK_SCHEME": "ATOMIC", "DFT_SPHERICAL_POINTS": 590, "DFT_RADIAL_POINTS": 85, "DFT_REMOVE_DISTANT_POINTS": 0, "D_convergence": 1e-8, }) svwn_w, wfn = psi4.energy("SVWN", return_wfn=True) xc_ref = -8.9396369264084168 # Default Octree blocking xc_psi4 = wfn.variable("DFT XC ENERGY") Vpot = wfn.V_potential() D = np.array(wfn.Da()) V = np.zeros_like(D) xc_e = 0.0 rho = [] points_func = Vpot.properties()[0] superfunc = Vpot.functional() grid = Vpot.grid() # Loop over atoms and their blocks for atom in range(mol.nallatom()): xc_atom = 0 for block in grid.atomic_blocks()[atom]: # Obtain block information points_func.compute_points(block) npoints = block.npoints() lpos = np.array(block.functions_local_to_global()) psi4.core.print_out( f"This block belongs to atom {block.parent_atom()}\n") # Obtain the grid weight w = np.array(block.w()) # Compute phi! phi = np.array( points_func.basis_values()["PHI"])[:npoints, :lpos.shape[0]] # Build a local slice of D lD = D[(lpos[:, None], lpos)] # Copmute rho rho = 2.0 * np.einsum("pm,mn,pn->p", phi, lD, phi, optimize=True) inp = {} inp["RHO_A"] = psi4.core.Vector.from_array(rho) # Compute the kernel ret = superfunc.compute_functional(inp, -1) # Compute the XC energy vk = np.array(ret["V"])[:npoints] xc_atom += np.einsum("a,a->", w, vk, optimize=True) xc_e += xc_atom psi4.core.print_out(f"XC Energy per Atom {xc_atom}\n") psi4.core.print_out(f"Total XC Energy {xc_e}\n") assert psi4.compare_values(xc_ref, xc_psi4, 7, "psi4 XC energy") assert psi4.compare_values(xc_ref, xc_e, 7, "psi4numpy XC energy")
def create_psi_mol(**kwargs): """Builds a qforte Molecule object directly from a psi4 calculation. Returns ------- Molecule The qforte Molecule object which holds the molecular information. """ kwargs.setdefault('symmetry', 'c1') kwargs.setdefault('charge', 0) kwargs.setdefault('multiplicity', 1) mol_geometry = kwargs['mol_geometry'] basis = kwargs['basis'] multiplicity = kwargs['multiplicity'] charge = kwargs['charge'] qforte_mol = Molecule(mol_geometry=mol_geometry, basis=basis, multiplicity=multiplicity, charge=charge) if not use_psi4: raise ImportError("Psi4 was not imported correctely.") # By default, the number of frozen orbitals is set to zero kwargs.setdefault('num_frozen_docc', 0) kwargs.setdefault('num_frozen_uocc', 0) # run_scf is not read, because we always run SCF to get a wavefunction object. kwargs.setdefault('run_mp2', 0) kwargs.setdefault('run_ccsd', 0) kwargs.setdefault('run_cisd', 0) kwargs.setdefault('run_fci', 0) # Setup psi4 calculation(s) psi4.set_memory('2 GB') psi4.core.set_output_file(kwargs['filename'] + '.out', False) p4_geom_str = f"{int(charge)} {int(multiplicity)}" for geom_line in mol_geometry: p4_geom_str += f"\n{geom_line[0]} {geom_line[1][0]} {geom_line[1][1]} {geom_line[1][2]}" p4_geom_str += f"\nsymmetry {kwargs['symmetry']}" p4_geom_str += f"\nunits angstrom" print(' ==> Psi4 geometry <==') print('-------------------------') print(p4_geom_str) p4_mol = psi4.geometry(p4_geom_str) scf_ref_type = "rhf" if multiplicity == 1 else "rohf" psi4.set_options({ 'basis': basis, 'scf_type': 'pk', 'reference': scf_ref_type, 'e_convergence': 1e-8, 'd_convergence': 1e-8, 'ci_maxiter': 100, 'num_frozen_docc': kwargs['num_frozen_docc'], 'num_frozen_uocc': kwargs['num_frozen_uocc'] }) # run psi4 caclulation p4_Escf, p4_wfn = psi4.energy('SCF', return_wfn=True) # Run additional computations requested by the user if (kwargs['run_mp2']): qforte_mol.mp2_energy = psi4.energy('MP2') if (kwargs['run_ccsd']): qforte_mol.ccsd_energy = psi4.energy('CCSD') if (kwargs['run_cisd']): qforte_mol.cisd_energy = psi4.energy('CISD') if kwargs['run_fci']: if kwargs['num_frozen_uocc'] == 0: qforte_mol.fci_energy = psi4.energy('FCI') else: print( '\nWARNING: Skipping FCI computation due to a Psi4 bug related to FCI with frozen virtuals.\n' ) # Get integrals using MintsHelper. mints = psi4.core.MintsHelper(p4_wfn.basisset()) C = p4_wfn.Ca_subset("AO", "ALL") scalars = p4_wfn.scalar_variables() p4_Enuc_ref = scalars["NUCLEAR REPULSION ENERGY"] # Do MO integral transformation mo_teis = np.asarray(mints.mo_eri(C, C, C, C)) mo_oeis = np.asarray(mints.ao_kinetic()) + np.asarray(mints.ao_potential()) mo_oeis = np.einsum('uj,vi,uv', C, C, mo_oeis) nmo = np.shape(mo_oeis)[0] nalpha = p4_wfn.nalpha() nbeta = p4_wfn.nbeta() nel = nalpha + nbeta frozen_core = p4_wfn.frzcpi().sum() frozen_virtual = p4_wfn.frzvpi().sum() # Get symmetry information orbitals = [] for irrep, block in enumerate(p4_wfn.epsilon_a_subset("MO", "ACTIVE").nph): for orbital in block: orbitals.append([orbital, irrep]) orbitals.sort() hf_orbital_energies = [] orb_irreps_to_int = [] for row in orbitals: hf_orbital_energies.append(row[0]) orb_irreps_to_int.append(row[1]) del orbitals point_group = p4_mol.symmetry_from_input().lower() irreps = p4_mol.irrep_labels() orb_irreps = [irreps[i] for i in orb_irreps_to_int] # If frozen_core > 0, compute the frozen core energy and transform one-electron integrals frozen_core_energy = 0 if frozen_core > 0: for i in range(frozen_core): frozen_core_energy += 2 * mo_oeis[i, i] # Note that the two-electron integrals out of Psi4 are in the Mulliken notation for i in range(frozen_core): for j in range(frozen_core): frozen_core_energy += 2 * mo_teis[i, i, j, j] - mo_teis[i, j, j, i] # Incorporate in the one-electron integrals the two-electron integrals involving both frozen and non-frozen orbitals. # This also ensures that the correct orbital energies will be obtained. for p in range(frozen_core, nmo - frozen_virtual): for q in range(frozen_core, nmo - frozen_virtual): for i in range(frozen_core): mo_oeis[p, q] += 2 * mo_teis[p, q, i, i] - mo_teis[p, i, i, q] # Make hf_reference hf_reference = [1] * (nel - 2 * frozen_core) + [0] * ( 2 * (nmo - frozen_virtual) - nel) # Build second quantized Hamiltonian Hsq = qforte.SQOperator() Hsq.add(p4_Enuc_ref + frozen_core_energy, [], []) for i in range(frozen_core, nmo - frozen_virtual): ia = (i - frozen_core) * 2 ib = (i - frozen_core) * 2 + 1 for j in range(frozen_core, nmo - frozen_virtual): ja = (j - frozen_core) * 2 jb = (j - frozen_core) * 2 + 1 Hsq.add(mo_oeis[i, j], [ia], [ja]) Hsq.add(mo_oeis[i, j], [ib], [jb]) for k in range(frozen_core, nmo - frozen_virtual): ka = (k - frozen_core) * 2 kb = (k - frozen_core) * 2 + 1 for l in range(frozen_core, nmo - frozen_virtual): la = (l - frozen_core) * 2 lb = (l - frozen_core) * 2 + 1 if (ia != jb and kb != la): Hsq.add(mo_teis[i, l, k, j] / 2, [ia, jb], [kb, la]) # abba if (ib != ja and ka != lb): Hsq.add(mo_teis[i, l, k, j] / 2, [ib, ja], [ka, lb]) # baab if (ia != ja and ka != la): Hsq.add(mo_teis[i, l, k, j] / 2, [ia, ja], [ka, la]) # aaaa if (ib != jb and kb != lb): Hsq.add(mo_teis[i, l, k, j] / 2, [ib, jb], [kb, lb]) # bbbb # Set attributes qforte_mol.nuclear_repulsion_energy = p4_Enuc_ref qforte_mol.hf_energy = p4_Escf qforte_mol.hf_reference = hf_reference qforte_mol.sq_hamiltonian = Hsq qforte_mol.hamiltonian = Hsq.jw_transform() qforte_mol.point_group = [point_group, irreps] qforte_mol.orb_irreps = orb_irreps qforte_mol.orb_irreps_to_int = orb_irreps_to_int qforte_mol.hf_orbital_energies = hf_orbital_energies qforte_mol.frozen_core = frozen_core qforte_mol.frozen_virtual = frozen_virtual qforte_mol.frozen_core_energy = frozen_core_energy # Order Psi4 to delete its temporary files. psi4.core.clean() return qforte_mol
from helper_SAPT import * np.set_printoptions(precision=5, linewidth=200, threshold=2000, suppress=True) import psi4 # Set Psi4 & NumPy Memory Options psi4.set_memory('2 GB') psi4.core.set_output_file('output.dat', False) numpy_memory = 2 # Set molecule to dimer dimer = psi4.geometry(""" O -0.066999140 0.000000000 1.494354740 H 0.815734270 0.000000000 1.865866390 H 0.068855100 0.000000000 0.539142770 -- O 0.062547750 0.000000000 -1.422632080 H -0.406965400 -0.760178410 -1.771744500 H -0.406965400 0.760178410 -1.771744500 symmetry c1 """) psi4.set_options({'basis': 'jun-cc-pVDZ', 'e_convergence': 1e-8, 'd_convergence': 1e-8}) sapt = helper_SAPT(dimer, memory=8, algorithm='AO') # Build intermediates int_timer = sapt_timer('intermediates') Pi = np.dot(sapt.orbitals['a'], sapt.orbitals['a'].T) Pj = np.dot(sapt.orbitals['b'], sapt.orbitals['b'].T)
def cqed_rhf(lambda_vector, molecule_string, psi4_options_dict): """Computes the QED-RHF energy and density Arguments --------- lambda_vector : 1 x 3 array of floats the electric field vector, see e.g. Eq. (1) in [DePrince:2021:094112] and (15) in [Haugland:2020:041043] molecule_string : string specifies the molecular geometry options_dict : dictionary specifies the psi4 options to be used in running the canonical RHF Returns ------- cqed_rhf_dictionary : dictionary Contains important quantities from the cqed_rhf calculation, with keys including: 'RHF ENERGY' -> result of canonical RHF calculation using psi4 defined by molecule_string and psi4_options_dict 'CQED-RHF ENERGY' -> result of CQED-RHF calculation, see Eq. (13) of [McTague:2021:ChemRxiv] 'CQED-RHF C' -> orbitals resulting from CQED-RHF calculation 'CQED-RHF DENSITY MATRIX' -> density matrix resulting from CQED-RHF calculation 'CQED-RHF EPS' -> orbital energies from CQED-RHF calculation 'PSI4 WFN' -> wavefunction object from psi4 canonical RHF calcluation 'CQED-RHF DIPOLE MOMENT' -> total dipole moment from CQED-RHF calculation (1x3 numpy array) 'NUCLEAR DIPOLE MOMENT' -> nuclear dipole moment (1x3 numpy array) 'DIPOLE ENERGY' -> See Eq. (14) of [McTague:2021:ChemRxiv] 'NUCLEAR REPULSION ENERGY' -> Total nuclear repulsion energy Example ------- >>> cqed_rhf_dictionary = cqed_rhf([0., 0., 1e-2], '''\nMg\nH 1 1.7\nsymmetry c1\n1 1\n''', psi4_options_dictionary) """ # define geometry using the molecule_string mol = psi4.geometry(molecule_string) # define options for the calculation psi4.set_options(psi4_options_dict) # run psi4 to get ordinary scf energy and wavefunction object psi4_rhf_energy, wfn = psi4.energy("scf", return_wfn=True) # Create instance of MintsHelper class mints = psi4.core.MintsHelper(wfn.basisset()) # Grab data from wavfunction # number of doubly occupied orbitals ndocc = wfn.nalpha() # grab all transformation vectors and store to a numpy array C = np.asarray(wfn.Ca()) # use canonical RHF orbitals for guess CQED-RHF orbitals Cocc = C[:, :ndocc] # form guess density D = np.einsum("pi,qi->pq", Cocc, Cocc) # [Szabo:1996] Eqn. 3.145, pp. 139 # Integrals required for CQED-RHF # Ordinary integrals first V = np.asarray(mints.ao_potential()) T = np.asarray(mints.ao_kinetic()) I = np.asarray(mints.ao_eri()) # Extra terms for Pauli-Fierz Hamiltonian # nuclear dipole mu_nuc_x = mol.nuclear_dipole()[0] mu_nuc_y = mol.nuclear_dipole()[1] mu_nuc_z = mol.nuclear_dipole()[2] # electronic dipole integrals in AO basis mu_ao_x = np.asarray(mints.ao_dipole()[0]) mu_ao_y = np.asarray(mints.ao_dipole()[1]) mu_ao_z = np.asarray(mints.ao_dipole()[2]) # \lambda \cdot \mu_el (see within the sum of line 3 of Eq. (9) in [McTague:2021:ChemRxiv]) l_dot_mu_el = lambda_vector[0] * mu_ao_x l_dot_mu_el += lambda_vector[1] * mu_ao_y l_dot_mu_el += lambda_vector[2] * mu_ao_z # compute electronic dipole expectation value with # canonincal RHF density mu_exp_x = np.einsum("pq,pq->", 2 * mu_ao_x, D) mu_exp_y = np.einsum("pq,pq->", 2 * mu_ao_y, D) mu_exp_z = np.einsum("pq,pq->", 2 * mu_ao_z, D) # need to add the nuclear term to the sum over the electronic dipole integrals mu_exp_x += mu_nuc_x mu_exp_y += mu_nuc_y mu_exp_z += mu_nuc_z rhf_dipole_moment = np.array([mu_exp_x, mu_exp_y, mu_exp_z]) # We need to carry around the electric field dotted into the nuclear dipole moment # and the electric field dotted into the RHF electronic dipole expectation value # see prefactor to sum of Line 3 of Eq. (9) in [McTague:2021:ChemRxiv] # \lambda_vector \cdot \mu_{nuc} l_dot_mu_nuc = (lambda_vector[0] * mu_nuc_x + lambda_vector[1] * mu_nuc_y + lambda_vector[2] * mu_nuc_z) # \lambda_vecto \cdot < \mu > where <\mu> contains electronic and nuclear contributions l_dot_mu_exp = (lambda_vector[0] * mu_exp_x + lambda_vector[1] * mu_exp_y + lambda_vector[2] * mu_exp_z) # dipole energy, Eq. (14) in [McTague:2021:ChemRxiv] # 0.5 * (\lambda_vector \cdot \mu_{nuc})** 2 # - (\lambda_vector \cdot <\mu> ) ( \lambda_vector\cdot \mu_{nuc}) # +0.5 * (\lambda_vector \cdot <\mu>) ** 2 d_c = (0.5 * l_dot_mu_nuc**2 - l_dot_mu_nuc * l_dot_mu_exp + 0.5 * l_dot_mu_exp**2) # quadrupole arrays Q_ao_xx = np.asarray(mints.ao_quadrupole()[0]) Q_ao_xy = np.asarray(mints.ao_quadrupole()[1]) Q_ao_xz = np.asarray(mints.ao_quadrupole()[2]) Q_ao_yy = np.asarray(mints.ao_quadrupole()[3]) Q_ao_yz = np.asarray(mints.ao_quadrupole()[4]) Q_ao_zz = np.asarray(mints.ao_quadrupole()[5]) # Pauli-Fierz 1-e quadrupole terms, Line 2 of Eq. (9) in [McTague:2021:ChemRxiv] Q_PF = -0.5 * lambda_vector[0] * lambda_vector[0] * Q_ao_xx Q_PF -= 0.5 * lambda_vector[1] * lambda_vector[1] * Q_ao_yy Q_PF -= 0.5 * lambda_vector[2] * lambda_vector[2] * Q_ao_zz # accounting for the fact that Q_ij = Q_ji # by weighting Q_ij x 2 which cancels factor of 1/2 Q_PF -= lambda_vector[0] * lambda_vector[1] * Q_ao_xy Q_PF -= lambda_vector[0] * lambda_vector[2] * Q_ao_xz Q_PF -= lambda_vector[1] * lambda_vector[2] * Q_ao_yz # Pauli-Fierz 1-e dipole terms scaled by # (\lambda_vector \cdot \mu_{nuc} - \lambda_vector \cdot <\mu>) # Line 3 in full of Eq. (9) in [McTague:2021:ChemRxiv] d_PF = (l_dot_mu_nuc - l_dot_mu_exp) * l_dot_mu_el # ordinary H_core H_0 = T + V # Add Pauli-Fierz terms to H_core # Eq. (11) in [McTague:2021:ChemRxiv] H = H_0 + Q_PF + d_PF # Overlap for DIIS S = mints.ao_overlap() # Orthogonalizer A = S^(-1/2) using Psi4's matrix power. A = mints.ao_overlap() A.power(-0.5, 1.0e-16) A = np.asarray(A) print("\nStart SCF iterations:\n") t = time.time() E = 0.0 Enuc = mol.nuclear_repulsion_energy() Eold = 0.0 E_1el_crhf = np.einsum("pq,pq->", H_0 + H_0, D) E_1el = np.einsum("pq,pq->", H + H, D) print("Canonical RHF One-electron energy = %4.16f" % E_1el_crhf) print("CQED-RHF One-electron energy = %4.16f" % E_1el) print("Nuclear repulsion energy = %4.16f" % Enuc) print("Dipole energy = %4.16f" % d_c) # Set convergence criteria from psi4_options_dict if "e_convergence" in psi4_options_dict: E_conv = psi4_options_dict["e_convergence"] else: E_conv = 1.0e-7 if "d_convergence" in psi4_options_dict: D_conv = psi4_options_dict["d_convergence"] else: D_conv = 1.0e-5 t = time.time() # maxiter maxiter = 500 for SCF_ITER in range(1, maxiter + 1): # Build fock matrix: [Szabo:1996] Eqn. 3.154, pp. 141 J = np.einsum("pqrs,rs->pq", I, D) K = np.einsum("prqs,rs->pq", I, D) # Pauli-Fierz 2-e dipole-dipole terms, line 2 of Eq. (12) in [McTague:2021:ChemRxiv] M = np.einsum("pq,rs,rs->pq", l_dot_mu_el, l_dot_mu_el, D) N = np.einsum("pr,qs,rs->pq", l_dot_mu_el, l_dot_mu_el, D) # Build fock matrix: [Szabo:1996] Eqn. 3.154, pp. 141 # plus Pauli-Fierz terms Eq. (12) in [McTague:2021:ChemRxiv] F = H + J * 2 - K + 2 * M - N diis_e = np.einsum("ij,jk,kl->il", F, D, S) - np.einsum( "ij,jk,kl->il", S, D, F) diis_e = A.dot(diis_e).dot(A) dRMS = np.mean(diis_e**2)**0.5 # SCF energy and update: [Szabo:1996], Eqn. 3.184, pp. 150 # Pauli-Fierz terms Eq. 13 of [McTague:2021:ChemRxiv] SCF_E = np.einsum("pq,pq->", F + H, D) + Enuc + d_c print( "SCF Iteration %3d: Energy = %4.16f dE = % 1.5E dRMS = %1.5E" % (SCF_ITER, SCF_E, (SCF_E - Eold), dRMS)) if (abs(SCF_E - Eold) < E_conv) and (dRMS < D_conv): break Eold = SCF_E # Diagonalize Fock matrix: [Szabo:1996] pp. 145 Fp = A.dot(F).dot(A) # Eqn. 3.177 e, C2 = np.linalg.eigh(Fp) # Solving Eqn. 1.178 C = A.dot(C2) # Back transform, Eqn. 3.174 Cocc = C[:, :ndocc] D = np.einsum("pi,qi->pq", Cocc, Cocc) # [Szabo:1996] Eqn. 3.145, pp. 139 # update electronic dipole expectation value mu_exp_x = np.einsum("pq,pq->", 2 * mu_ao_x, D) mu_exp_y = np.einsum("pq,pq->", 2 * mu_ao_y, D) mu_exp_z = np.einsum("pq,pq->", 2 * mu_ao_z, D) mu_exp_x += mu_nuc_x mu_exp_y += mu_nuc_y mu_exp_z += mu_nuc_z # update \lambda \cdot <\mu> l_dot_mu_exp = (lambda_vector[0] * mu_exp_x + lambda_vector[1] * mu_exp_y + lambda_vector[2] * mu_exp_z) # Line 3 in full of Eq. (9) in [McTague:2021:ChemRxiv] d_PF = (l_dot_mu_nuc - l_dot_mu_exp) * l_dot_mu_el # update Core Hamiltonian H = H_0 + Q_PF + d_PF # update dipole energetic contribution, Eq. (14) in [McTague:2021:ChemRxiv] d_c = (0.5 * l_dot_mu_nuc**2 - l_dot_mu_nuc * l_dot_mu_exp + 0.5 * l_dot_mu_exp**2) if SCF_ITER == maxiter: psi4.core.clean() raise Exception("Maximum number of SCF cycles exceeded.") print("Total time for SCF iterations: %.3f seconds \n" % (time.time() - t)) print("QED-RHF energy: %.8f hartree" % SCF_E) print("Psi4 SCF energy: %.8f hartree" % psi4_rhf_energy) rhf_one_e_cont = ( 2 * H_0 ) # note using H_0 which is just T + V, and does not include Q_PF and d_PF rhf_two_e_cont = ( J * 2 - K ) # note using just J and K that would contribute to ordinary RHF 2-electron energy pf_two_e_cont = 2 * M - N SCF_E_One = np.einsum("pq,pq->", rhf_one_e_cont, D) SCF_E_Two = np.einsum("pq,pq->", rhf_two_e_cont, D) CQED_SCF_E_Two = np.einsum("pq,pq->", pf_two_e_cont, D) CQED_SCF_E_D_PF = np.einsum("pq,pq->", 2 * d_PF, D) CQED_SCF_E_Q_PF = np.einsum("pq,pq->", 2 * Q_PF, D) assert np.isclose( SCF_E_One + SCF_E_Two + CQED_SCF_E_D_PF + CQED_SCF_E_Q_PF + CQED_SCF_E_Two, SCF_E - d_c - Enuc, ) cqed_rhf_dict = { "RHF ENERGY": psi4_rhf_energy, "CQED-RHF ENERGY": SCF_E, "1E ENERGY": SCF_E_One, "2E ENERGY": SCF_E_Two, "1E DIPOLE ENERGY": CQED_SCF_E_D_PF, "1E QUADRUPOLE ENERGY": CQED_SCF_E_Q_PF, "2E DIPOLE ENERGY": CQED_SCF_E_Two, "CQED-RHF C": C, "CQED-RHF DENSITY MATRIX": D, "CQED-RHF EPS": e, "PSI4 WFN": wfn, "RHF DIPOLE MOMENT": rhf_dipole_moment, "CQED-RHF DIPOLE MOMENT": np.array([mu_exp_x, mu_exp_y, mu_exp_z]), "NUCLEAR DIPOLE MOMENT": np.array([mu_nuc_x, mu_nuc_y, mu_nuc_z]), "DIPOLE ENERGY": d_c, "NUCLEAR REPULSION ENERGY": Enuc, } return cqed_rhf_dict
P[i, j] = np.vdot(iEVA, jEVA) + np.vdot(iEVB, jEVB) P[i, j] /= 2 f = np.array([0] * N + [-1]) q = np.linalg.solve(P, f) weightFocks = [(fa * q, fb * q) for q, (fa, fb) in zip(q, focks)] return tuple([sum(i) for i in zip(*weightFocks)]) if __name__ == '__main__': config = cfp.ConfigParser() config.read('Options.ini') molecule = psi4.geometry(config['DEFAULT']['molecule']) molecule.update_geometry() basis = psi4.core.BasisSet.build(molecule, "BASIS", config['DEFAULT']['basis'], puream=0) mints = psi4.core.MintsHelper(basis) scf = config['SCF'] uhf = UHF(molecule, mints, scf['maxIter'], scf['conv'], scf['diis'], scf['diis_start'], scf['diis_nvector']) uhf.computeEnergy()
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)')