def test_psi4_cc(): """cc1""" #! RHF-CCSD 6-31G** all-electron optimization of the H2O molecule psi4.core.clean() h2o = psi4.geometry(""" O H 1 0.97 H 1 0.97 2 103.0 """) psi4.set_options({"basis": '6-31G**'}) psi4.optimize('ccsd') refnuc = 9.1654609427539 refscf = -76.0229427274435 refccsd = -0.20823570806196 reftotal = -76.2311784355056 assert psi4.compare_values(refnuc, h2o.nuclear_repulsion_energy(), 3, "Nuclear repulsion energy") assert psi4.compare_values(refscf, psi4.get_variable("SCF total energy"), 5, "SCF energy") assert psi4.compare_values(refccsd, psi4.get_variable("CCSD correlation energy"), 4, "CCSD contribution") assert psi4.compare_values(reftotal, psi4.get_variable("Current energy"), 7, "Total energy")
def test_h2o_constrained(inp): """Constrained optimization of the square water molecule""" h2o = psi4.geometry(""" O H 1 1.0 H 1 1.0 2 90.0 """) psi4.set_options({'basis': 'cc-pvdz', 'g_convergence': 'gau_tight'}) psi4.set_options(inp['options']) # geometric specific options geometric_keywords = { 'coordsys': 'tric', 'enforce': 0.0, 'constraints': { 'set': [{ 'type': 'angle', 'indices': [1, 0, 2], 'value': 90.0 }] } } e, wfn = psi4.optimize(inp['name'], return_wfn=True, engine='geometric', optimizer_keywords=geometric_keywords) assert compare_values(inp['ref_ene'], e, 6) assert compare_values(inp['ref_nuc'], h2o.nuclear_repulsion_energy(), 3)
def _optimize_with_psi4(self, xyzfile): psi4mol = xyzfile_to_psi4mol(xyzfile) e, wfn = psi4.optimize('pbeh3c/def2-svp', molecule=psi4mol) output = wfn.gradient().print_out() return output
def test_v2rdm6(): #! cc-pvdz N2 (6,6) active space Test DQG print(' N2 / cc-pVDZ / DQG(6,6), geometry optimization') import psi4 n2 = psi4.geometry(""" 0 1 n n 1 1.1 """) psi4.set_options({ 'basis': 'cc-pvdz', 'scf_type': 'pk', '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', { 'positivity': 'dqg', #'r_convergence': 1e-7, 'r_convergence': 1e-6, 'e_convergence': 1e-5, 'orbopt_gradient_convergence': 1e-8, 'maxiter': 20000, }) psi4.activate(n2) psi4.optimize('v2rdm-casscf') refnuc = 23.1968666562054260 refscf = -108.95016246035139 refv2rdm = -109.095505119442 assert psi4.compare_values(refnuc, n2.nuclear_repulsion_energy(), 4, "Nuclear repulsion energy") assert psi4.compare_values(refscf, psi4.variable("SCF TOTAL ENERGY"), 5, "SCF total energy") assert psi4.compare_values(refv2rdm, psi4.variable("CURRENT ENERGY"), 4, "v2RDM-CASSCF total energy")
def optimize(molecule, config): print("Optimizing geometry...") e = psi4.optimize(config['config_generator']['method'] + '/' + config['config_generator']['basis'], molecule=molecule) print("") return molecule, e
def surf_psi4(params, output_file): natoms = params.natoms geom = params.geometry #print(geom) geom += "symmetry c1\n" geom += "no_reorient\n" geom += "no_com" #print(geom) #print(geom) mol = psi4.geometry(geom) if (params.constraint_type == 'angle'): coord_constraint = 'fixed_bend' if (params.constraint_type == 'bond'): coord_constraint = 'fixed_distance' if (params.constraint_type == 'dihedral'): coord_constraint = 'fixed_dihedral' output = open(output_file, "a") output.write( '\n\n--%s surface scan for fixed %s of atoms %s--\n' % (params.scan_type, params.constraint_type, params.constrained_atoms)) output.write( '\n--------------------------------------------------------------------------------------\n' ) output.write('\n{:>20} {:>20}\n'.format('Coordinate', 'E')) output.write( '-------------------------------------------------------------------------------------\n' ) output.close() surf_out = open("surface_scan.xyz", "w+") surf_out.close() for constrained_value in params.constrained_values: #print(params.constrained_values) fixed_coord = params.constrained_atoms + str(constrained_value) #print(fixed_coord) psi4.set_options(params.keywords) psi4.set_module_options('Optking', {coord_constraint: fixed_coord}) psi4.set_num_threads(params.nthreads) psi4.core.set_output_file( "psi4_output/surf_%.2f.out" % constrained_value, False) surf_out = open("surface_scan.xyz", "a") surf_out.write("%s\n" % natoms) surf_out.write( "%s surface scan with fixed %s of %f\n" % (params.scan_type, params.constraint_type, constrained_value)) if (params.scan_type == 'relaxed'): E = psi4.optimize("%s/%s" % (params.method, params.basis)) pre_string = mol.create_psi4_string_from_molecule() #print(pre_string) struct = pre_string.split("\n", 7)[7] #print(struct) surf_out.write(struct[:-1]) if (params.scan_type == 'unrelaxed'): E = psi4.energy("%s/%s" % (params.method, params.basis)) output = open(output_file, "a") output.write('\n{:>20.4f} {:>20.7f}\n'.format(constrained_value, E)) output.close()
def opt_geom(smiles): mol = Chem.MolFromSmiles(smiles) xyz, mol = mol_to_xyz(mol) psi4.set_memory('4 GB') psi4.set_num_threads(4) method_basis = args.method + '/' + args.basis geom = psi4.geometry(xyz) opt_e = psi4.optimize(method_basis, molecule=geom) print("SMILES: " + smiles + ", Optimization Energy: " + str(opt_e) + " H") return opt_e
def main(): psi4.set_output_file("mol.dat", True) #psi4.set_memory('500 MB') numpy_memory = 2 mol = psi4.geometry(""" 1 1 C 3.90950 0.68560 0.10610 C 2.93030 1.66840 -0.12400 C 1.60330 1.25720 -0.21570 C 1.24210 -0.05730 -0.07630 C 2.19240 -1.05850 0.13520 C 3.54650 -0.67450 0.23220 O 4.53670 -1.62920 0.45160 C -0.13100 -0.11120 -0.22930 C -0.50400 1.21160 -0.47900 O 0.55400 2.00210 -0.45930 C -1.86070 1.70710 -0.75070 O -2.00120 2.70720 -1.50580 N -3.00950 1.14140 -0.09490 C -3.26330 -0.24370 -0.51740 C -2.35130 -1.25070 0.20540 C -0.95890 -1.35200 -0.42120 H 4.94980 0.97540 0.17990 H 3.20070 2.71030 -0.23560 H 1.90390 -2.09700 0.22760 H 4.31140 -2.61260 0.54640 H -2.87840 1.19990 0.94160 H -3.85220 1.71520 -0.33480 H -4.31490 -0.50250 -0.25980 H -3.17530 -0.34740 -1.62310 H -2.26950 -1.00900 1.28760 H -2.82510 -2.25410 0.13390 H -1.04420 -1.56690 -1.50800 H -0.44100 -2.21470 0.04790""") psi4.energy('scf/cc-pvdz', molecule=mol) psi4.optimize('scf/cc-pvdz', molecule=mol)
def test_h2o(inp, engine): """Optimization of the square water molecule""" h2o = psi4.geometry(""" O H 1 1.0 H 1 1.0 2 90.0 """) psi4.set_options({'basis': 'cc-pvdz', 'g_convergence': 'gau_tight'}) psi4.set_options(inp['options']) e, wfn = psi4.optimize(inp['name'], return_wfn=True, engine=engine) assert compare_values(inp['ref_ene'], e, 6) assert compare_values(inp['ref_nuc'], h2o.nuclear_repulsion_energy(), 3)
def test_psi4_cc(): """cc1""" #! RHF-CCSD 6-31G** all-electron optimization of the H2O molecule psi4.core.clean() h2o = psi4.geometry(""" O H 1 0.97 H 1 0.97 2 103.0 """) psi4.set_options({"basis": '6-31G**'}) psi4.optimize('ccsd') refnuc = 9.1654609427539 refscf = -76.0229427274435 refccsd = -0.20823570806196 reftotal = -76.2311784355056 assert psi4.compare_values(refnuc, h2o.nuclear_repulsion_energy(), 3, "Nuclear repulsion energy") assert psi4.compare_values(refscf, psi4.get_variable("SCF total energy"), 5, "SCF energy") assert psi4.compare_values(refccsd, psi4.get_variable("CCSD correlation energy"), 4, "CCSD contribution") assert psi4.compare_values(reftotal, psi4.get_variable("Current energy"), 7, "Total energy")
def _geometry_optimize(molecule, resp_type): # HF/6-31g* if resp_type == "RESP1": psi4.set_options({ "basis": "6-31g*", "geom_maxiter": 1000, "maxiter": 500, "opt_coordinates": "cartesian", }) psi4.optimize("hf", molecule=molecule) energy = psi4.energy("hf", molecule=molecule) # HF/6-31g*, HF/cc-pV(D+d)Z, PW6B95/cc-pV(D+d)Z elif resp_type == "RESP2": psi4.set_options({ "basis": "6-31g*", "geom_maxiter": 1000, "maxiter": 500, "opt_coordinates": "cartesian", }) psi4.optimize("hf", molecule=molecule) psi4.set_options({ "basis": "cc-pV(D+d)Z", "geom_maxiter": 1000, "maxiter": 500, "opt_coordinates": "cartesian", }) psi4.optimize("hf", molecule=molecule) psi4.set_options({ "basis": "cc-pV(D+d)Z", "geom_maxiter": 1000, "maxiter": 200, "dft_spherical_points": 590, "dft_radial_points": 99, "dft_pruning_scheme": "robust", "opt_coordinates": "cartesian", }) psi4.optimize("pw6b95", molecule=molecule) energy = psi4.energy("pw6b95", molecule=molecule) psi4.core.clean() return molecule, energy
def optimize(mol: psi4.core.Molecule, method: str = "wB97X/6-31g*") -> unit.Quantity: """Runs a minimization for a psi4 molecule object instance using a specified method (default: wB97X/6-31g*). Note: 6-31g* is equivalente to 6-31g(d) according to http://www.psicode.org/psi4manual/master/basissets_tables.html Parameters ---------- mol : psi4.core.Molecule psi4 object instance method : str specifies the method to use Returns ------- energy : unit.Quantity energy of optimized geometry """ e, wfn = psi4.optimize(method, return_wfn=True, molecule=mol) return (e * hartree_to_kJ_mol) * unit.kilojoule_per_mole, wfn
def test_mp2d_opt(): h2 = psi4.geometry(""" 0 1 H H 1 R units bohr R = 1.7007535129120455 """) psi4.set_options({ 'scf_type': 'df', 'd_convergence': 12, 'e_convergence': 12, 'g_convergence': 'gau_verytight', }) ene, wfn = psi4.optimize('mp2d/cc-pvdz', return_wfn=True, molecule=h2) assert compare_values(1.4259, h2.R, 'h2 bond length', atol=1.e-3)
def opt(params, label, natoms, geom): """ Optimizes individual fragments for strain energy calculations. """ level_of_theory = "%s/%s" % (params.method, params.basis) output = open(params.outfile, "a") frag = "" geom = geom.split('\n')[:(natoms + 2)] for i in range(natoms + 2): frag += "%s\n" % geom[i] frag += "symmetry c1" print("Geometry Optimization on Fragment %s" % label) psi4.set_options(params.keywords) psi4.geometry(frag) psidump = "psi4_output/fragment_%s_opt.out" % label psi4.core.set_output_file(psidump, False) psi4.set_num_threads(params.nthreads) e = psi4.optimize(level_of_theory) #psi4.core.clean() return e
def optimize(geom, confId=None, method='HF-3C', **kwargs): """ Optimizes the given conformation. :param mol: an RDKit.Mol or a string :param confId: the ID of the conformer to optimize, if needed :param method: the PSI4 method to use :return: wavefunction (energy is available under wavefunction.energy) """ try: geom = make_psi4_geometry(geom, confId) psi4.activate(geom) psi4.core.IO.set_default_namespace(str(id(geom))) psi4.core.set_global_option("MAXITER", 1000) return psi4.optimize(method, return_wfn=True, **kwargs)[1] except Exception as e: pass return np.nan
hartree2ev = psi4.constants.hartree2ev psi4.set_output_file("output.dat", False) benz = psi4.geometry(""" pubchem:benzene """) psi4.set_options({ "REFERENCE": "RHF", "MAX_ENERGY_G_CONVERGENCE": 8, "BASIS": "STO-3G", "DF_BASIS_SCF": "CC-PVDZ-RI" }) psi4.optimize('scf') psi4.set_options({ "REFERENCE": "RHF", "BASIS": "CC-PVDZ", "DF_BASIS_SCF": "CC-PVDZ-JKFIT" }) e_sing_rhf = psi4.energy('scf') benz.set_multiplicity(3) psi4.set_options({"REFERENCE": "ROHF"}) e_trip_rohf = psi4.energy('scf') psi4.set_options({"REFERENCE": "UHF"}) e_trip_uhf = psi4.energy('scf')
# MMFF(Merck Molecular Force Field) で構造最適化する MMFFOptimizeMolecule(mol) #UFF(Universal Force Field)普遍力場で構造最適化したい場合は #UFFOptimizeMolecule(mol) conf = mol.GetConformer() # Psi4 に入力可能な形式に変換する。 # 電荷とスピン多重度を設定(下は、電荷0、スピン多重度1) mol_input = "0 1" #各々の原子の座標をXYZフォーマットで記述 for atom in mol.GetAtoms(): mol_input += "\n " + atom.GetSymbol() + " " + str(conf.GetAtomPosition(atom.GetIdx()).x)\ + " " + str(conf.GetAtomPosition(atom.GetIdx()).y)\ + " " + str(conf.GetAtomPosition(atom.GetIdx()).z) molecule = psi4.geometry(mol_input) # 計算手法(汎関数)、基底関数を設定 level = "b3lyp/6-31G*" # 計算手法(汎関数)、基底関数の例 #theory = ['hf', 'b3lyp'] #basis_set = ['sto-3g', '3-21G', '6-31G(d)', '6-31+G(d,p)', '6-311++G(2d,p)'] # 構造最適化計算を実行 energy, wave_function = psi4.optimize(level, molecule=molecule, return_wfn=True)
import psi4 from sys import argv mol_file = argv[1] molecule_name = (mol_file.split('/')[-1]).split('.')[0] molecule_dir = '/'.join(mol_file.split('/')[:-1]) with open(mol_file, 'r') as mol: mol = psi4.core.Molecule.from_string(mol.read(), dtype='xyz') mol.set_molecular_charge(charge) ##input mol.set_multiplicity(multiplicity) ##input psi4.set_memory('2 GB') psi4.set_num_threads(2) psi4.set_module_options('alpha', {'DFT_OMEGA': omega}) ##input psi4.set_output_file(molecule_name + '_geometry_optimization.dat', False) psi4.set_options({'basis': 'def2-TZVP'}) final_energy = psi4.optimize('LRC-wPBEH', molecule=mol) mol.save_xyz_file(molecule_name + '_geometry_final.xyz', False) json_data = {"molecule_name": molecule_name, "final_energy": final_energy} json_file = ("{}/energy_{}.txt".format(molecule_dir, molecule_name)) with open(json_file, 'w') as f: json.dump(json_data, f, indent=2)
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) # Run vibrational frequency analysis psi4.set_output_file(file_prefix + '_vibfreq.dat', False) scf_energy, scf_wfn = psi4.frequency('scf/cc-pVDZ', molecule=ch4, return_wfn=True, dertype='gradient') # Save "raw" frequencies into a variable scf_wfn_freq = scf_wfn.frequency_analysis['omega'][2] print(scf_wfn_freq) # Eliminate imaginary parts of frequencies, scf_wfn_real=scf_wfn_freq.real # round the frequencies (to the nearest whole number), scf_wfn_round=np.rint(scf_wfn_real)
print(n2o4) # **Pregunta 2.** Calule la energía de la molécula de $NO_2$ con HF y la base aug-cc-pvdz. [Complete donde haga falta - Reemplace las X] # In[2]: import psi4 NO2 = psi4.geometry(""" 0 2 N -4.39539 1.87380 0.00000 O -3.90978 3.09520 -0.00000 O -3.65594 0.93810 0.00000 units angstrom """) psi4.set_options({'reference': 'uhf'}) no2 = psi4.optimize("HF/aug-cc-pvdz") print(no2) # **Pregunta a.** Calcule el $\Delta U$ de la reacción $N_2O_4 <=> 2NO_2$ según HF. # In[3]: (2 * no2 - n2o4) * 2625.5 # **Pregunta 3.** Calule la energía de la molécula de $N_2O_4$ con DFT B3LYP y la base aug-cc-pvdz. # In[4]: import psi4 psi4.set_memory("2 gb") psi4.geometry("""
def run_psi4(calculation, mol, method, basis, **psi4opts): """Execute current psi4 setup with passed molecule. Handle exceptions and stderr/stdout""" logging.debug("Beginning Psi4 {} calculation with {}/{}".format( calculation, method, basis)) # capture stderr & stdout and write to log # std_out = sys.stdout # this is probably already handled by the cube # std_err = sys.stderr # psi_out = io.StringIO() # psi_err = io.StringIO() # sys.stdout = psi_out # sys.stderr = psi_err # execute with exception handling wave_fcn = None try: setup_psi4(**psi4opts) # logging.warn(str(os.path.abspath(psidatadir))) psi4.set_options({"basis": basis}) if calculation == "energy": logging.info("Psi4 call {}: {}/{}".format(calculation, method, basis)) ret_val, wave_fcn = psi4.energy(method, molecule=mol, return_wfn=True) elif calculation == "optimize": logging.info("Psi4 call {}: {}/{}".format(calculation, method, basis)) ret_val, wave_fcn = psi4.optimize(method, molecule=mol, return_wfn=True) else: raise ValueError("Unrecognized calculation type.") except psi4.ValidationError as e: logging.error("Failed to read setup: {}".format(e)) ret_val, wave_fcn = None, None except psi4.ConvergenceError as e: logging.error("Failed to converge: {}".format(e)) logging.error("error msg {}".format(e)) ret_val, wave_fcn = None, None except psi4.Dftd3Error as e: logging.error("Dftd3Error {}".format(e)) ret_val, wave_fcn = None, None except psi4.PsiException as e: logging.error("Failed to properly execute psi4 {} ({}/{})".format( calculation, method, basis)) logging.error("Psi4 Error: {}".format(e)) ret_val, wave_fcn = None, None except Exception as e: logging.error("Unexpected error in psi4: {}".format(e)) logging.error("Unexpected error in psi4: %s", sys.exc_info()[0]) ret_val, wave_fcn = None, None else: logging.info("Successful psi4 execution {} ({}/{})".format( calculation, method, basis)) cleanup_psi4() # return and reset stderr, stdout # psi4.core.flush_outfile() # this is probably already handled by the cube # logging.info('errorlen {} outlen {}'.format(len(psi_err.getvalue()),len(psi_out.getvalue()))) # logging.error(psi_err.getvalue()) # logging.info(psi_out.getvalue()) # sys.stdout = std_out # sys.stderr = std_err return ret_val, wave_fcn
def cmd(method, mol): optimize(method, molecule=mol)
import psi4 hartree2ev = psi4.constants.hartree2ev psi4.set_output_file("output.dat", False) benz = psi4.geometry(""" pubchem:benzene """) psi4.set_options({"REFERENCE" : "RHF", "MAX_ENERGY_G_CONVERGENCE" : 8, "BASIS" : "STO-3G", "DF_BASIS_SCF" : "CC-PVDZ-RI"}) psi4.optimize('scf') psi4.set_options({"REFERENCE" : "RHF", "BASIS" : "CC-PVDZ", "DF_BASIS_SCF" : "CC-PVDZ-JKFIT"}) e_sing_rhf = psi4.energy('scf') benz.set_multiplicity(3) psi4.set_options({"REFERENCE" : "ROHF"}) e_trip_rohf = psi4.energy('scf') psi4.set_options({"REFERENCE" : "UHF"}) e_trip_uhf = psi4.energy('scf') vertical_uhf = hartree2ev * (e_trip_uhf - e_sing_rhf)
def __init__(self, geometry, basis, reference, **kwargs): import psi4 self.optimize = False self.scf = False self.mp2 = False self.bfgs_ic3epa = False self.ccsd = False self.cepa1 = False self.ccsdpt = False self.cepa0 = False self.shucc = False self.lam_cepa = None self.lccd = False self.acpf = False self.psi_acpf = False self.psi_aqcc = False self.psi_cepa0 = False self.olccd_iters = 50 self.uacpf = False self.aqcc = False self.uaqcc = False self.run_ic3epa = False self.ocepa = False self.fci = False self.d_convergence = 1e-6 self.r_convergence = 1e-5 self.run_svd = False self.sys_name = "Unnamed system:" self.ucc3 = False self.tol = 1e-14 self.log_file = 'out.dat' self.mem = '24GB' for key, value in kwargs.items(): setattr(self, key, value) try: assert reference == 'rhf' or reference == 'uhf' except: print("Only \"rhf\" or \"uhf\" allowed.") exit() self.reference = reference print(self.sys_name) psi4.geometry(geometry) #psi4.core.be_quiet() psi4.core.clean() if os.path.exists(self.log_file): cha = 'a' else: cha = 'w' log = open(self.log_file, cha) log.write(self.sys_name) psi4.set_memory(self.mem) if self.optimize != False: psi4.set_options({'reference': self.reference, 'scf_type': 'pk', 'g_convergence': 'GAU_TIGHT', 'd_convergence': self.d_convergence}) psi4.set_options({'opt_coordinates': self.optimize, 'geom_maxiter': 500, 'mp2_type': 'conv'}) #Some intermediates tweaked to converge problem systems, final optimization obviously kept the same. #E, wfnopt = psi4.optimize('scf/6-311G(d,p)', return_wfn = True) #E, wfnopt = psi4.optimize('mp2/6-311G(d,p)', return_wfn = True) E, wfnopt = psi4.optimize('b3lyp/6-311G(d,p)', return_wfn = True) log.write((wfnopt.molecule().create_psi4_string_from_molecule())) psi4.set_options({'reference': reference, 'basis': basis, 'd_convergence': self.d_convergence, 'scf_type': 'pk', 'r_convergence': self.r_convergence, 'maxiter': 100, 'cc_type': 'conv', 'mo_maxiter': self.mo_maxiter}) self.hf_energy, wfn = psi4.energy('scf', return_wfn = True) if self.scf == True: print("HF energy:".ljust(30)+("{0:20.16f}".format(self.hf_energy))) if self.mp2 == True: print("MP2 energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('mp2')))) if self.ccsd == True: print("CCSD energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('ccsd')))) if self.ccsdpt == True: print("CCSD(T) energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('ccsd(t)')))) if self.lccd == True: print("LCCD energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('lccd')))) if self.cepa1 == True and self.reference == 'rhf': print("CEPA(1) energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('cepa(1)')))) if self.ocepa == True: print("OCEPA energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('olccd')))) if self.fci == True: print("FCI energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('fci')))) if self.psi_acpf == True: print("ACPF energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('acpf')))) if self.psi_aqcc == True: print("AQCC energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('aqcc')))) if self.psi_cepa0 == True: print("CEPA(0) energy:".ljust(30)+("{0:20.16f}".format(psi4.energy('cepa(0)')))) mints = psi4.core.MintsHelper(wfn.basisset()) ca = wfn.Ca() cb = wfn.Cb() self.fa = wfn.Fa() self.fb = wfn.Fb() self.j_aaaa = np.array(mints.mo_eri(ca, ca, ca, ca)) self.j_abab = np.array(mints.mo_eri(ca, ca, cb, cb)) self.j_baba = np.array(mints.mo_eri(cb, cb, ca, ca)) self.j_bbbb = np.array(mints.mo_eri(cb, cb, cb, cb)) self.fa.transform(ca) if reference != 'rhf': self.fb.transform(cb) self.fa = np.array(self.fa) self.fb = np.array(self.fb) self.j_aaaa = self.j_aaaa.swapaxes(1, 2) self.j_abab = self.j_abab.swapaxes(1, 2) self.j_baba = self.j_baba.swapaxes(1, 2) self.j_bbbb = self.j_bbbb.swapaxes(1, 2) k_aaaa = copy.copy(self.j_aaaa) k_bbbb = copy.copy(self.j_bbbb) k_aaaa = k_aaaa.swapaxes(2, 3) k_bbbb = k_bbbb.swapaxes(2, 3) self.l_aaaa = self.j_aaaa - k_aaaa self.l_bbbb = self.j_bbbb - k_bbbb self.noa = wfn.Ca_subset("AO", "ACTIVE_OCC").shape[1] self.nob = wfn.Cb_subset("AO", "ACTIVE_OCC").shape[1] self.nva = wfn.Ca_subset("AO", "ACTIVE_VIR").shape[1] self.nvb = wfn.Cb_subset("AO", "ACTIVE_VIR").shape[1] self.aopairs = np.triu_indices(self.noa, k=1) self.avpairs = np.triu_indices(self.nva, k=1) self.bopairs = np.triu_indices(self.nob, k=1) self.bvpairs = np.triu_indices(self.nvb, k=1) psi4.core.clean() self.b = self.cepa_b() self.b = at.collapse_tensor(self.b, self) self.b = at.concatenate_amps(self.b, self) if self.cepa0 == True: cepa = self.cepa() print("CEPA(0) energy:".ljust(30)+("{0:20.16f}".format(cepa))) if self.acpf == True: self.s2_term = False self.shift = 'acpf' acpf = self.shifted_cepa() print("ACPF energy:".ljust(30)+("{0:20.16f}".format(acpf))) if self.aqcc == True: self.s2_term = False self.shift = 'aqcc' aqcc = self.shifted_cepa() print("AQCC energy:".ljust(30)+("{0:20.16f}".format(aqcc))) if self.shucc == True: self.lam = 1 c3epa = self.c3epa() print("UCC-2 energy:".ljust(30)+("{0:20.16f}".format(c3epa))) ''' if self.ucc3 == True: self.lam = 1 b = self.b x = 0*b #res = scipy.optimize.minimize(self.ucc3_energy, x, jac = self.ucc3_gradient, method = 'bfgs', options = {'gtol': 1e-5, 'disp': True}) #res = scipy.optimize.minimize(self.ucc3_energy, x, jac = self.numerical_ucc3_gradient, method = 'bfgs', options = {'gtol': 1e-5, 'disp': True}) res = scipy.optimize.minimize(self.ucc3_energy, x, jac = None, method = 'bfgs', options = {'gtol': 1e-9, 'disp': True}) print("UCC(3) energy:".ljust(30)+("{0:20.16f}".format(res.fun))) self.x = res.x x = res.x self.shift = 'ucc3' if self.reference == 'rhf': x2 = at.rhf_to_uhf(x, self) shift = [] for i in range(0, len(x2)): shift.append(x2[i]**2) shift = np.array(shift) shift = at.uhf_to_rhf(shift, self) else: shift = [] for i in range(0, len(x)): shift.append(x[i]**2) shift = np.array(shift) #print('shift') #print(shift) #print('gradient') #print(self.shifted_A(x)+self.b) ''' if self.lam_cepa != None: self.lam = self.lam_cepa c3epa = self.c3epa() print("λ-C3EPA energy:".ljust(30)+("{0:20.16f}".format(c3epa))) if self.run_ic3epa == True: self.lam = 0 c3epa = self.ic3epa() #print("IC3EPA energy:".ljust(30)+("{0:20.16f}".format(c3epa))) if self.uacpf == True: self.s2_term = True self.shift = 'acpf' uacpf = self.shifted_cepa() print("UACPF energy:".ljust(30)+("{0:20.16f}".format(uacpf))) if self.uaqcc == True: self.s2_term = True self.shift = 'aqcc' uaqcc = self.shifted_cepa() print("UAQCC energy:".ljust(30)+("{0:20.16f}".format(uaqcc))) if self.ucc3 == True: self.lam = 1 self.shift = 'ucc3' ucc3 = self.shifted_cepa() print("UCC(3) energy:".ljust(30)+("{0:20.16f}".format(ucc3))) if self.bfgs_ic3epa == True: b = self.cepa_b() b = at.collapse_tensor(b, self) b = at.concatenate_amps(b, self) x = 0*b res = scipy.optimize.minimize(self.bfgs_ic3epa_energy, x, method = 'bfgs', options = {'gtol': 1e-10}) print("Variational IC3EPA energy:".ljust(30)+("{0:20.16f}".format(self.bfgs_ic3epa_energy(res.x))))
#FLAGXYZ """) mol.fix_com(True) mol.fix_orientation(True) psi4.core.set_num_threads(NUMTHREADS) psi4.set_options({'basis': 'cc-pvdz'}) psi4.set_options({'maxiter': 500}) psi4.set_options({'cachelevel': 1}) psi4.set_options({'reference': 'rhf'}) psi4.set_options({'opt_coordinates': 'cartesian'}) psi4.set_options({'geom_maxiter': 200}) # --- GEO-OPT with B3LYP --- # E, wf = psi4.optimize('B3LYP', molecule=mol, return_wfn=True) # extract the geometry in angstroms xyz = wf.molecule().geometry().to_array(True, True) * 0.529177 # converted to angs # save the some matrixes numpy.save("S", wf.S().to_array(False, True)) numpy.save("D-B3LYP", wf.Da().to_array(False, True)) numpy.save("F-B3LYP", wf.Fa().to_array(False, True)) numpy.save("C-B3LYP", wf.Ca().to_array(False, True)) numpy.save("H-B3LYP", wf.H().to_array(False, True)) numpy.save("e-B3LYP", wf.epsilon_a().to_array(False, True)) # save the xyz fxyz = open("GEOM-B3LYP.xyz", "w")
def compute(self, elements, positions, rvec=None, charge=0, multiplicity=1, field_type='dipole', dipole_strength=[0, 0, 0], forces=False, optimize=False, opt_cartesian=False, uhf=False, max_iters=None): if not rvec is None: print( 'Warning: psi4 does not work with periodic boundary conditions. Ignoring them.' ) self.molecule_string = MoleculeString(elements, positions, charge=charge, multiplicity=multiplicity, reorient=False, no_symmetry=True, no_com=True, verbose=False) self.mol = psi4.geometry( self.molecule_string.geometry) # De input moet in angstrom staan if field_type == 'dipole': #print('Perturbing with a constant electric field') options = { 'basis': self.basis, 'PERTURB_H': True, 'PERTURB_WITH': 'DIPOLE', 'PERTURB_DIPOLE': list(dipole_strength) } if opt_cartesian: options['OPT_COORDINATES'] = 'cartesian' if uhf: options['reference'] = 'uhf' if not max_iters is None: options['GEOM_MAXITER'] = max_iters psi4.set_options(options) if optimize: self.energy, self.wavefunction = psi4.optimize(self.method, return_wfn=True) if forces: self.gradient = self.wavefunction.gradient() return self.energy, mol.geometry( ).np / angstrom, self.gradient.np else: return self.energy, self.mol.geometry().np / angstrom if forces: self.gradient, self.wavefunction = psi4.gradient(self.method, return_wfn=True) self.energy = self.wavefunction.energy() return self.energy, self.gradient.np else: self.energy, self.wavefunction = psi4.energy(self.method, return_wfn=True) return self.energy
t = datetime.datetime.fromtimestamp(time.time()) psi4.set_num_threads(nthread=2) psi4.set_memory('2GB') psi4.set_output_file('{}{}{}_{}{}.log'.format(t.year, t.month, t.day, t.hour, t.minute)) m_xylene = psi4.geometry(''' 0 1 H 1.28968 -0.58485 2.54537 C 0.72665 -0.53821 1.60812 C -0.66059 -0.63788 1.62278 H -1.18866 -0.76325 2.57379 C -1.38281 -0.57923 0.43824 H -2.47598 -0.65808 0.46597 C -0.70870 -0.41532 -0.78014 C -1.44994 -0.24691 -1.99137 C 0.68999 -0.31852 -0.79417 H 1.23196 -0.19170 -1.73873 C 1.39668 -0.37916 0.39958 C 2.48879 -0.30069 0.38763 H -2.49493 -0.35404 -1.78784 H -1.14694 -0.98824 -2.70096 H -1.26259 0.72757 -2.39162 H 2.86211 -0.36704 1.38820 H 2.77426 0.63858 -0.03801 H 2.89720 -1.09694 -0.19896 ''') psi4.optimize('b3lyp/6-311+g(d,p)', molecule=m_xylene)
import psi4 #as psi4 import numpy as np psi4.set_output_file("output.dat", True) psi4.set_memory('500 MB') numpy_memory = 2 h2o = psi4.geometry(""" O 0.0 0.0 0.0 H 1.0 0.0 0.0 H 0.0 1.0 0.0 symmetry c1 """) #psi4.set_options({'basis': 'cc-pcdz'}) psi4.energy('scf/cc-pvdz', molecule=h2o) psi4.optimize('scf/cc-pvdz', molecule=h2o) scf_e, scf_wfn = psi4.frequency('scf/cc-pvdz', molecule=h2o, return_wfn=True, dertype=1)
AllChem.EmbedMolecule(mol, AllChem.ETKDGv2()) AllChem.UFFOptimizeMolecule(mol) conf = mol.GetConformer(-1) xyz = '0 1' for atom, (x, y, z) in zip(mol.GetAtoms(), conf.GetPositions()): xyz += '\n' xyz += '{}\t{}\t{}\t{}'.format(atom.GetSymbol(), x, y, z) return xyz # 入力する分子(thiacloprid) smiles = 'C1CSC(=NC#N)N1CC2=CN=C(C=C2)Cl' psi4.set_output_file('04_thiacloprid.txt') dinotefuran = psi4.geometry(smi2xyz(smiles)) _, wfn_dtf = psi4.optimize('B3LYP/6-31G*', molecule=dinotefuran, return_wfn=True) rdkit_dinotefuran = Chem.AddHs(Chem.MolFromSmiles(smiles)) ## 双極子モーメントの計算 psi4.oeprop(wfn_dtf, 'DIPOLE', titile='dipole') dipole_x, dipole_y, dipole_z = psi4.variable('SCF DIPOLE X'), psi4.variable( 'SCF DIPOLE Y'), psi4.variable('SCF DIPOLE Z') dipole_moment = np.sqrt(dipole_x**2 + dipole_y**2 + dipole_z**2) #print(round(dipole_moment,3),'D')
# 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} units angstrom """.format(charge=charge, multiplicity=multiplicity, atomic_coords=atomic_coords)) final_energy, wfn = psi4.optimize('hf/{}'.format(basis_set), molecule=molecule, return_wfn=True) final_geometry = wfn.molecule() def get_xyz(geometry): xyz = "" atom_count = geometry.natom() for iat in range(atom_count): xyz += "{} {:.6f} {:.6f} {:.6f}".format( geometry.symbol(iat), # element symbol geometry.x(iat) * psi4.constants.bohr2angstroms, # x-coordinate geometry.y(iat) * psi4.constants.bohr2angstroms, # y-coordinate geometry.z(iat) * psi4.constants.bohr2angstroms, # z-coordinate ) if iat is not atom_count - 1:
def __init__(self, geometry, basis, **kwargs): import psi4 psi4.set_memory('10 GB') psi4.core.clean() self.uns = False self.reference = 'rhf' self.shift = 'cepa(0)' self.optimize = False self.verbose = False self.c3epa = False for key, value in kwargs.items(): setattr(self, key, value) if self.reference == 'rhf': self.rhf = True else: self.rhf = False molecule = psi4.geometry(geometry) psi4.core.be_quiet() if self.optimize: psi4.set_options({ 'reference': self.reference, 'scf_type': 'pk', 'g_convergence': 'GAU_TIGHT', 'd_convergence': 1e-12 }) try: psi4.set_options({'geom_maxiter': 300}) psi4.optimize('b3lyp/6-311G(d,p)') except: psi4.set_options({ 'opt_coordinates': 'both', 'geom_maxiter': 300 }) psi4.optimize('b3lyp/6-311G(d,p)') psi4.set_options({ 'basis': basis, 'd_convergence': 1e-12, 'scf_type': 'pk' }) self.hf_energy, wfn = psi4.energy('scf', return_wfn=True) print("HF energy:".ljust(30) + ("{0:20.16f}".format(self.hf_energy))) print("MP2 energy:".ljust(30) + ("{0:20.16f}".format(psi4.energy('mp2')))) print("CCSD energy:".ljust(30) + ("{0:20.16f}".format(psi4.energy('ccsd')))) print("CEPA(0) energy:".ljust(30) + ("{0:20.16f}".format(psi4.energy('cepa(0)')))) print("CEPA(1) energy:".ljust(30) + ("{0:20.16f}".format(psi4.energy('cepa(1)')))) print("CCSD(T) energy:".ljust(30) + ("{0:20.16f}".format(psi4.energy('ccsd(t)')))) print("ACPF energy:".ljust(30) + ("{0:20.16f}".format(psi4.energy('acpf')))) print("AQCC energy:".ljust(30) + ("{0:20.16f}".format(psi4.energy('aqcc')))) print("CEPA(0)(D) energy:".ljust(30) + ("{0:20.16f}".format(psi4.energy('lccd')))) mints = psi4.core.MintsHelper(wfn.basisset()) ca = wfn.Ca() cb = wfn.Cb() self.fa = wfn.Fa() self.fb = wfn.Fb() self.j_aaaa = np.array(mints.mo_eri(ca, ca, ca, ca)) self.j_abab = np.array(mints.mo_eri(ca, ca, cb, cb)) self.j_baba = np.array(mints.mo_eri(cb, cb, ca, ca)) self.j_bbbb = np.array(mints.mo_eri(cb, cb, cb, cb)) self.fa.transform(ca) if self.rhf == False: self.fb.transform(cb) self.fa = np.array(self.fa) self.fb = np.array(self.fb) self.j_aaaa = self.j_aaaa.swapaxes(1, 2) self.j_abab = self.j_abab.swapaxes(1, 2) self.j_baba = self.j_baba.swapaxes(1, 2) self.j_bbbb = self.j_bbbb.swapaxes(1, 2) k_aaaa = copy.copy(self.j_aaaa) k_bbbb = copy.copy(self.j_bbbb) k_aaaa = k_aaaa.swapaxes(2, 3) k_bbbb = k_bbbb.swapaxes(2, 3) self.l_aaaa = self.j_aaaa - k_aaaa self.l_bbbb = self.j_bbbb - k_bbbb self.noa = wfn.Ca_subset("AO", "ACTIVE_OCC").shape[1] self.nob = wfn.Cb_subset("AO", "ACTIVE_OCC").shape[1] self.nva = wfn.Ca_subset("AO", "ACTIVE_VIR").shape[1] self.nvb = wfn.Cb_subset("AO", "ACTIVE_VIR").shape[1] self.build_trial() self.build_gradient() self.r_aa = self.taa self.r_aaaa = self.taaaa self.r_abab = self.tabab self.r_bb = self.tbb self.r_bbbb = self.tbbbb
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)) final_energy, wfn = psi4.optimize( '{}/{}'.format(functional, basis_set), molecule=molecule, return_wfn=True) final_geometry = wfn.molecule() def get_xyz(geometry): xyz = "" atom_count = geometry.natom() for iat in range(atom_count): xyz += "{} {:.6f} {:.6f} {:.6f}".format( geometry.symbol(iat), # element symbol geometry.x(iat) * psi4.constants.bohr2angstroms, # x-coordinate geometry.y(iat) * psi4.constants.bohr2angstroms, # y-coordinate geometry.z(iat) * psi4.constants.bohr2angstroms, # z-coordinate ) if iat is not atom_count - 1: xyz += '\n'