def _initialize_resp(resp_path): # Change to resp dir os.chdir(resp_path) # Setup the logging psi4.set_output_file("psi4.log") log = Logger(Path("resp.log")) # Read the input input_path = Path("resp.yaml") with input_path.open() as f: log.log(f"\n\nLoaded YAML file: resp.yaml") log.log("-" * 100) log.log(f.read()) log.log("-" * 100 + "\n\n") f.seek(0) inp = yaml.load(f, Loader=yaml.FullLoader) # TODO: Add YAML validation (https://docs.python-cerberus.org/en/stable/) # Make the directories _try_mkdir(Path("structures")) _try_mkdir(Path("esp_grids")) _try_mkdir(Path("results")) return inp, log
def _build_psi4_basis(mol, basis, puream=False): """ Builds a Psi4 basis and its Python interpretation from a molecule string and basis string. """ import psi4 psi4.set_output_file("output.dat") # Can only handle cartesian data psi4.set_options({"PUREAM": puream}) mol = psi4.geometry(mol) mol.update_geometry() geom = np.array(mol.geometry()) # Convert the basis to a dictionary basis = psi4.core.BasisSet.build(mol, "orbital", basis, puream=puream) py_basis = [] for x in range(basis.nshell()): shell = basis.shell(x) tmp = {} tmp["center"] = geom[shell.ncenter] tmp["exp"] = [shell.exp(n) for n in range(shell.nprimitive)] tmp["coef"] = [shell.coef(n) for n in range(shell.nprimitive)] tmp["am"] = shell.am py_basis.append(tmp) return basis, py_basis
def set_up(): import psi4 psi4.core.clean() psi4.core.clean_timers() psi4.core.clean_options() psi4.set_output_file("pytest_output.dat", True)
def __init__(self, method='pbe', basis='aug-cc-pvtz', psi4_output='output.dat', memory=20e+09, cores=12, scratch_dir='scratch'): self.basis = basis self.method = method if not os.path.exists(scratch_dir): os.mkdir(scratch_dir) else: shutil.rmtree(scratch_dir) os.mkdir(scratch_dir) self.scratch_dir = scratch_dir # optional psi4.core.IOManager.shared_object().set_default_path(scratch_dir) psi4.set_memory(int(memory)) psi4.set_num_threads(cores) # Overwrites the output.dat psi4.set_output_file(psi4_output, False) print('Psi4 Model initiated with method %s and basis set %s' % (self.method, self.basis))
def set_up(): import psi4 psi4.core.clean() psi4.core.clean_options() import forte from forte import PLUGIN_SOFILE psi4.core.plugin_load(PLUGIN_SOFILE) # reloads plugin options psi4.set_output_file("pytest_output.dat", True)
def get_HF_wfn(molstring, basis, **options): psi4.core.clean() psi4.set_memory("8 GB") psi4.set_num_threads(8) psi4.set_output_file("psilog.dat") mol = psi4.geometry(molstring) psi4.set_options(options) e, wfn = psi4.energy("HF/{}".format(basis), return_wfn=True, molecule=mol) return wfn
def set_up(): import qcdb qcdb.driver.pe.clean_options() try: import psi4 except ImportError: pass else: psi4.core.clean() psi4.core.clean_timers() psi4.core.clean_options() psi4.set_output_file("pytest_output.dat", True)
def main(): psi4.set_output_file("pbeh3c_mol.dat", True) #psi4.set_memory('500 MB') numpy_memory = 2 mol = psi4.geometry(""" 1 1 C 3.533276577335 0.297516950079 -0.033740208753 C 2.574760938246 1.278066479179 -0.069835787116 C 1.253218752224 0.849739147834 -0.039258570370 C 0.899019257306 -0.495860874701 0.032550031024 C 1.888860870465 -1.490197119704 0.067078565308 C 3.204596438039 -1.081456560919 0.033430560670 O 4.250570460820 -1.915645303151 0.060360861113 C -0.521891091036 -0.526599835195 0.052806016194 C -0.907216553266 0.796770182506 -0.010855959829 O 0.163856617883 1.625333309480 -0.070535693831 C -2.142468145732 1.509067711325 -0.077871153394 O -2.328114248487 2.665835310257 -0.269517118360 N -3.421527194392 0.695313957156 0.191159341639 C -3.581807216427 -0.692769910170 -0.352292538279 C -2.772392782598 -1.705499205563 0.431794190569 C -1.307831296645 -1.790976049117 0.040569332872 H 4.581064582865 0.566654620917 -0.057341951344 H 2.837749742920 2.324943817097 -0.122662938228 H 1.625749586779 -2.540289226583 0.117596634162 H 3.972628181395 -2.834781214964 0.105049915868 H -3.557445242160 0.671475310656 1.206814356133 H -4.167512313144 1.297833117167 -0.169560281990 H -4.646108631113 -0.913660797798 -0.283335352767 H -3.313356183445 -0.663729781207 -1.408465575248 H -2.877036964703 -1.518274278002 1.505474270168 H -3.228135005269 -2.682198217407 0.265368459879 H -1.225392070756 -2.220062054576 -0.963992292922 H -0.817581075574 -2.508114264473 0.702369958893 """) #psi4.energy('mp2/cc-pvdz', molecule=mol) #psi4.energy('scf/cc-pvdz', molecule=mol) psi4.energy('pbeh3c/', molecule=mol) # default is def2-mSVP #psi4.optimize('pbeh3c/', molecule=mol) # default is def2-mSVP psi4.frequency('pbeh3c/', molecule=mol) # default is def2-mSVP
def __init__(self, mol, basis, convergence=6, maxiter=50): self.basis = basis self.convergence = convergence self.maxiter = maxiter psi4.set_memory('500 MB') psi4.set_output_file('output_scf.dat', False) self.mol = psi4.geometry(mol.xyz_string(option=1)) psi4.set_options({'basis': self.basis, 'scf_type': 'pk'}) #psi4.energy('scf') self.wfn = psi4.core.Wavefunction.build( self.mol, psi4.core.get_global_option('BASIS')) self.mints = psi4.core.MintsHelper(self.wfn.basisset()) #Init integrals self.S = np.matrix(self.mints.ao_overlap()) self.T = np.matrix(self.mints.ao_kinetic()) self.V = np.matrix(self.mints.ao_potential()) self.g_chem = np.array(self.mints.ao_eri()) self.g = self.g_chem.transpose((0, 2, 1, 3)) self.gt = self.g.transpose((0, 1, 3, 2)) self.X = np.matrix(inv(sqrtm(self.S))) #Init Nuclear Repulsion Energy self.E_nuc = self.mol.nuclear_repulsion_energy() self.natom = self.mol.natom() self.charge = self.mol.molecular_charge() self.norbitals = self.mints.basisset().nbf() self.n_e = sum(mol.charges) - self.charge try: self.n_occ = int(self.n_e / 2) except: print( 'Error: Not all orbitals fully occupied, try using UHF instead' ) pass self.D = np.zeros((self.norbitals, self.norbitals)) #Might be wrong???
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)
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) # 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
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 # 入力する分子(dinotefuran) smiles = 'CNC(=N[N+](=O)[O-])NCC1CCOC1' psi4.set_output_file('01_dinotefuran1.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')
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 # 入力する分子(flonicamid) smiles = 'C1=CN=CC(=C1C(F)(F)F)C(=O)NCC#N' psi4.set_output_file('02_flonicamid.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')
#! Tests out the CG solver with CPHF Polarizabilities import time import numpy as np import psi4 psi4.set_output_file("output.dat") # Benzene mol = psi4.geometry(""" 0 1 O 0.000000000000 0.000000000000 -0.075791843589 H 0.000000000000 -0.866811828967 0.601435779270 H 0.000000000000 0.866811828967 0.601435779270 symmetry c1 """) psi4.set_options({ "basis": "aug-cc-pVDZ", "scf_type": "df", "e_convergence": 1e-8, "save_jk": True, }) scf_e, scf_wfn = psi4.energy("SCF", return_wfn=True) # Orbitals Co = scf_wfn.Ca_subset("AO", "OCC") Cv = scf_wfn.Ca_subset("AO", "VIR") # Mints object
def set_up_overall(request): import psi4 psi4.set_output_file("pytest_output.dat", False) request.addfinalizer(tear_down)
#! PsiAPI energy example import psi4 psi4.set_output_file("output.dat", False) geom = psi4.geometry(""" C # testing escaping comments """) psi4.set_options({"SCF_TYPE": "DF", "BASIS": "cc-pVDZ"}) scf_e, scf_wfn = psi4.energy('SCF', return_wfn=True) psi4.compare_values(-37.5959861862713893, scf_e, 6, 'SCF DF Energy') psi4.core.set_local_option("SCF", "SCF_TYPE", "PK") psi4.compare_values(-37.5959861862713893, scf_e, 6, 'SCF PK Energy')
## SMILESをxyz形式に変換 def smi2xyz(smiles): mol = Chem.AddHs(Chem.MolFromSmiles(smiles)) 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 # 入力する分子(clothianidine) smiles = 'CNC(=N[N+](=O)[O-])NCC1=CN=C(S1)Cl' psi4.set_output_file('03_clothianidin.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')
extras = ['-n', str(nthread)] retcode = psi4.test(args["test"], extras=extras) sys.exit(retcode) if not os.path.isfile(args["input"]): raise KeyError("The file %s does not exist." % args["input"]) args["input"] = os.path.normpath(args["input"]) # Setup scratch_messy _clean_functions = [psi4.core.clean, psi4.extras.clean_numpy_files] # Setup outfile if args["append"] is None: args["append"] = False if (args["output"] != "stdout") and (args["qcschema"] is False): psi4.set_output_file(args["output"], args["append"], loglevel=int(args["loglevel"])) # Set a few options psi4.core.set_num_threads(int(args["nthread"]), quiet=True) psi4.set_memory(args["memory"], quiet=True) psi4.extras._input_dir_ = os.path.dirname(os.path.abspath(args["input"])) if args["qcschema"] is False: psi4.print_header() start_time = datetime.datetime.now() # Initialize MDI if args["mdi"] is not None: psi4.mdi_engine.mdi_init(args["mdi"]) # Prepare scratch for inputparser if args["scratch"] is not None:
from sys import argv import json import psi4 from psi4.driver.frac import ip_fitting from psi4.core.Molecule import from_string mol_file = argv[1] molecule_name = (mol_file.split('/')[-1]).split('.')[0] with open(mol_file, 'r') as f: mol = from_string(f.read(), dtype='xyz') mol.set_molecular_charge(0) mol.set_multiplicity(1) psi4.set_memory('2 GB') psi4.set_num_threads(2) psi4.set_output_file(molecule_name + '_ip_fitting.dat', False) psi4.set_options({'basis': 'def2-TZVP'}) omega = ip_fitting('LRC-wPBEH', 0.1, 2.0, molecule=mol) json_data = {"molecule_name": molecule_name, "omega": omega} json_file = ("omega_{}.txt".format(molecule_name)) with open(json_file, 'w') as f: json.dump(json_data, f, indent=2)
""" This file tests the JK file in the quest. """ import quest import pytest import psi4 import numpy as np psi4.set_output_file("output.dat", True) def test_PKJK(): for mol_str in quest.mollib: molecule = psi4.geometry(mol_str) basis = psi4.core.BasisSet.build(molecule, "ORBITAL", "STO-3G") mints = psi4.core.MintsHelper(basis) jk = quest.jk.build_JK(mints, "PK") Cocc = np.random.rand(mints.nbf(), 5) D = np.dot(Cocc, Cocc.T) I = np.asarray(mints.ao_eri()) J_ref = np.einsum("pqrs,rs->pq", I, D) K_ref = np.einsum("prqs,rs->pq", I, D) J, K = jk.compute_JK(Cocc) assert np.allclose(J_ref, J) assert np.allclose(K_ref, K)
import psi4, gefp, sys """ DDS interaction energies. Benchmark for CEX - run in MCBS mode. Usage: [basis] [xyz.psi] """ psi4.set_options({"scf_type" : "direct" , "guess" : "auto" , "df_scf_guess" : True , "e_convergence" : 1e-10 , "d_convergence" : 1e-10 , "basis" : sys.argv[1], "puream" : False , "print" : 1 ,}) psi4.set_output_file("dds.log", False) mol = gefp.core.utilities.psi_molecule_from_file(sys.argv[2]) gefp.math.matrix.move_atom_rotate_molecule(mol, [-30., -83., 43.1]) dds = gefp.density.partitioning.DensityDecomposition(mol, method='hf', acbs=False, jk_type='direct', no_cutoff=0.000, xc_scale=1.0, l_dds=False, cc_relax=False, verbose=False, n_eps=5.0E-5) dds.compute(polar_approx=False) v = dds.vars print(dds) conv = psi4.constants.hartree2kcalmol CEX = v["e_cou_t"] + v["e_exr_t"] print(" CEX = %16.6f [kcal/mol]" % (CEX*conv))
import psi4 import datetime import time 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
def ks_solver(alias, mol, options, V_builder, jk_type="DF", output="output.dat", restricted=True): # Build our molecule mol = mol.clone() mol.reset_point_group('c1') mol.fix_orientation(True) mol.fix_com(True) mol.update_geometry() # Set options psi4.set_output_file(output) psi4.core.prepare_options_for_module("SCF") psi4.set_options(options) psi4.core.set_global_option("SCF_TYPE", jk_type) maxiter = 20 E_conv = psi4.core.get_option("SCF", "E_CONVERGENCE") D_conv = psi4.core.get_option("SCF", "D_CONVERGENCE") # Integral generation from Psi4's MintsHelper wfn = psi4.core.Wavefunction.build(mol, psi4.core.get_global_option("BASIS")) mints = psi4.core.MintsHelper(wfn.basisset()) S = mints.ao_overlap() # Build the V Potential sup = psi4.driver.dft_funcs.build_superfunctional(alias, restricted)[0] sup.set_deriv(2) sup.allocate() vname = "RV" if not restricted: vname = "UV" Vpot = psi4.core.VBase.build(wfn.basisset(), sup, vname) Vpot.initialize() # Get nbf and ndocc for closed shell molecules nbf = wfn.nso() ndocc = wfn.nalpha() if wfn.nalpha() != wfn.nbeta(): raise PsiException("Only valid for RHF wavefunctions!") print('\nNumber of occupied orbitals: %d' % ndocc) print('Number of basis functions: %d' % nbf) # Build H_core V = mints.ao_potential() T = mints.ao_kinetic() H = T.clone() H.add(V) # Orthogonalizer A = S^(-1/2) A = mints.ao_overlap() A.power(-0.5, 1.e-14) # Build core orbitals C, Cocc, D, eigs = build_orbitals(H, A, ndocc) # Setup data for DIIS t = time.time() E = 0.0 Enuc = mol.nuclear_repulsion_energy() Eold = 0.0 # Initialize the JK object jk = psi4.core.JK.build(wfn.basisset()) jk.set_memory(int(1.25e8)) # 1GB jk.initialize() jk.print_header() diis_obj = psi4.p4util.solvers.DIIS(max_vec=3, removal_policy="largest") print('\nTotal time taken for setup: %.3f seconds' % (time.time() - t)) print('\nStarting SCF iterations:') t = time.time() print("\n Iter Energy XC E Delta E D RMS\n") for SCF_ITER in range(1, maxiter + 1): # Compute JK jk.C_left_add(Cocc) jk.compute() jk.C_clear() # Build Fock matrix F = H.clone() F.axpy(2.0, jk.J()[0]) F.axpy(-Vpot.functional().x_alpha(), jk.K()[0]) # Build V ks_e = 0.0 Vpot.set_D([D]) Vpot.properties()[0].set_pointers(D) V = V_builder(D, Vpot) if V is None: ks_e = 0.0 else: ks_e, V = V V = psi4.core.Matrix.from_array(V) F.axpy(1.0, V) # DIIS error build and update diis_e = psi4.core.Matrix.triplet(F, D, S, False, False, False) diis_e.subtract(psi4.core.Matrix.triplet(S, D, F, False, False, False)) diis_e = psi4.core.Matrix.triplet(A, diis_e, A, False, False, False) diis_obj.add(F, diis_e) dRMS = diis_e.rms() # SCF energy and update SCF_E = 2.0 * H.vector_dot(D) SCF_E += 2.0 * jk.J()[0].vector_dot(D) SCF_E -= Vpot.functional().x_alpha() * jk.K()[0].vector_dot(D) SCF_E += ks_e SCF_E += Enuc print('SCF Iter%3d: % 18.14f % 11.7f % 1.5E %1.5E' % (SCF_ITER, SCF_E, ks_e, (SCF_E - Eold), dRMS)) if (abs(SCF_E - Eold) < E_conv) and (dRMS < D_conv): break Eold = SCF_E # DIIS extrapolate F = diis_obj.extrapolate() # Diagonalize Fock matrix C, Cocc, D, eigs = build_orbitals(F, A, ndocc) if SCF_ITER == maxiter: raise Exception("Maximum number of SCF cycles exceeded.") print('\nTotal time for SCF iterations: %.3f seconds ' % (time.time() - t)) print('\nFinal SCF energy: %.8f hartree' % SCF_E) data = {} data["Da"] = D data["Ca"] = C data["eigenvalues"] = eigs return(SCF_E, data)
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 # 入力する分子(nitenpyram) smiles = 'CCN(CC1=CN=C(C=C1)Cl)C(=C[N+](=O)[O-])NC' psi4.set_output_file('05_nitenpyram.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')
def ks_solver(alias, mol, options, V_builder, jk_type="DF", output="output.dat", restricted=True): # Build our molecule mol = mol.clone() mol.reset_point_group('c1') mol.fix_orientation(True) mol.fix_com(True) mol.update_geometry() # Set options psi4.set_output_file(output) psi4.core.prepare_options_for_module("SCF") psi4.set_options(options) psi4.core.set_global_option("SCF_TYPE", jk_type) maxiter = 20 E_conv = psi4.core.get_option("SCF", "E_CONVERGENCE") D_conv = psi4.core.get_option("SCF", "D_CONVERGENCE") # Integral generation from Psi4's MintsHelper wfn = psi4.core.Wavefunction.build(mol, psi4.core.get_global_option("BASIS")) mints = psi4.core.MintsHelper(wfn.basisset()) S = mints.ao_overlap() # Build the V Potential sup = psi4.driver.dft_funcs.build_superfunctional(alias, restricted)[0] sup.set_deriv(2) sup.allocate() vname = "RV" if not restricted: vname = "UV" Vpot = psi4.core.VBase.build(wfn.basisset(), sup, vname) Vpot.initialize() # Get nbf and ndocc for closed shell molecules nbf = wfn.nso() ndocc = wfn.nalpha() if wfn.nalpha() != wfn.nbeta(): raise PsiException("Only valid for RHF wavefunctions!") print('\nNumber of occupied orbitals: %d' % ndocc) print('Number of basis functions: %d' % nbf) # Build H_core V = mints.ao_potential() T = mints.ao_kinetic() H = T.clone() H.add(V) # Orthogonalizer A = S^(-1/2) A = mints.ao_overlap() A.power(-0.5, 1.e-14) # Build core orbitals C, Cocc, D, eigs = build_orbitals(H, A, ndocc) # Setup data for DIIS t = time.time() E = 0.0 Enuc = mol.nuclear_repulsion_energy() Eold = 0.0 # Initialize the JK object jk = psi4.core.JK.build(wfn.basisset()) jk.set_memory(int(1.25e8)) # 1GB jk.initialize() jk.print_header() diis_obj = psi4.p4util.solvers.DIIS(max_vec=3, removal_policy="largest") print('\nTotal time taken for setup: %.3f seconds' % (time.time() - t)) print('\nStarting SCF iterations:') t = time.time() print( "\n Iter Energy XC E Delta E D RMS\n" ) for SCF_ITER in range(1, maxiter + 1): # Compute JK jk.C_left_add(Cocc) jk.compute() jk.C_clear() # Build Fock matrix F = H.clone() F.axpy(2.0, jk.J()[0]) F.axpy(-Vpot.functional().x_alpha(), jk.K()[0]) # Build V ks_e = 0.0 Vpot.set_D([D]) Vpot.properties()[0].set_pointers(D) V = V_builder(D, Vpot) if V is None: ks_e = 0.0 else: ks_e, V = V V = psi4.core.Matrix.from_array(V) F.axpy(1.0, V) # DIIS error build and update diis_e = psi4.core.Matrix.triplet(F, D, S, False, False, False) diis_e.subtract(psi4.core.Matrix.triplet(S, D, F, False, False, False)) diis_e = psi4.core.Matrix.triplet(A, diis_e, A, False, False, False) diis_obj.add(F, diis_e) dRMS = diis_e.rms() # SCF energy and update SCF_E = 2.0 * H.vector_dot(D) SCF_E += 2.0 * jk.J()[0].vector_dot(D) SCF_E -= Vpot.functional().x_alpha() * jk.K()[0].vector_dot(D) SCF_E += ks_e SCF_E += Enuc print('SCF Iter%3d: % 18.14f % 11.7f % 1.5E %1.5E' % (SCF_ITER, SCF_E, ks_e, (SCF_E - Eold), dRMS)) if (abs(SCF_E - Eold) < E_conv) and (dRMS < D_conv): break Eold = SCF_E # DIIS extrapolate F = diis_obj.extrapolate() # Diagonalize Fock matrix C, Cocc, D, eigs = build_orbitals(F, A, ndocc) if SCF_ITER == maxiter: raise Exception("Maximum number of SCF cycles exceeded.") print('\nTotal time for SCF iterations: %.3f seconds ' % (time.time() - t)) print('\nFinal SCF energy: %.8f hartree' % SCF_E) data = {} data["Da"] = D data["Ca"] = C data["eigenvalues"] = eigs return (SCF_E, data)
import time time #計算時間を見てみる # ハードウェア側の設定(計算に用いるCPUのスレッド数とメモリ設定) psi4.set_num_threads(nthread=3) psi4.set_memory("3GB") # 入力する分子(thiametoxam) smiles = 'CN1COCN(C1=N[N+](=O)[O-])CC2=CN=C(S2)Cl' # ファイル名を決める t = datetime.datetime.fromtimestamp(time.time()) psi4.set_output_file("{}_{}{}{}_{}{}.log".format(smiles, t.year, t.month, t.day, t.hour, t.minute)) # SMILES から三次元構造を発生させて、粗3D構造最適化 mol = Chem.MolFromSmiles(smiles) mol = Chem.AddHs(mol) params = ETKDGv3() params.randomSeed = 1 EmbedMolecule(mol, params) # MMFF(Merck Molecular Force Field) で構造最適化する MMFFOptimizeMolecule(mol) #UFF(Universal Force Field)普遍力場で構造最適化したい場合は #UFFOptimizeMolecule(mol) conf = mol.GetConformer()
#! PsiAPI pubchem access 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')
def set_up(): import psi4 psi4.core.clean() psi4.core.clean_options() psi4.set_output_file("pytest_output.dat", True)
# phi_B : Dihedral angle, A1-B1-B2-B3 # Coords are 1-indexed without dummies here dimer = { "Natoms per frag": [14, 3], "A Frag": 1, "A Ref Atoms": [[1], [2], [3]], "A Label": "PRLD", "B Frag": 2, "B Ref Atoms": [[15], [17], [16]], "B Label": "Water", "Frozen": ["theta_A", "theta_B", "phi_A", "phi_B"], } psi4.set_memory("1.0 GB") psi4.set_output_file('PRLD-ACC-H1.out', False) psi4.core.clean_options() psi4_options = { "basis": "6-31G*", "d_convergence": 9, "frag_mode": "multi", "freeze_intrafrag": 'true', } psi4.set_options(psi4_options) result = optking.optimize_psi4("hf", **{"interfrag_coords": str(dimer)}) # Can use qcel to output final rAH and dih values xyzs = result["final_molecule"]["geometry"] xyzs = np.array(xyzs) xyzs = np.reshape(xyzs, (-1, 3)) # coords are zero-indexed here:
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')
""" The primary init for the project. """ from . import molecule from . import scf_module from . import jk from . import solvers from . import core from . import mp2 from . import lj from . import driver from .mollib import mollib from .molecule import Molecule from .wavefunction import Wavefunction # Make sure Psi4 respects the global OMP_NUM_THREADS import psi4 import os if "OMP_NUM_THREADS" in list(os.environ): psi4.set_num_threads(int(os.environ["OMP_NUM_THREADS"])) psi4.set_output_file("psi_output.out") # Import default params default_params = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'default_params.yml')
import psi4 import numpy as np import scipy.linalg as sp psi4.set_output_file("output.dat", True) # setting output file psi4.set_memory(int(5e8)) numpy_memory = 2 from hf_backbone import Molecule class CUHFMolecule(Molecule): """ Will extend the backbone to work for cuhf input: geometry: the geometry you want to make a molecule out of """ def __init__(self, geometry): super().__init__(geometry) self.itercounter = 0 self.mode="cuhf" def getEigenStuff(self, spin): """ calculates the eigenvectors and eigenvalues of the hamiltonian input: spin: a string, either "alpha" or "beta" """ if spin == "alpha": F = self.guessMatrix_a else: F = self.guessMatrix_b return sp.eigh(F, b=self.displayOverlap())
def set_up_overall(request): import psi4 psi4.set_output_file("pytest_output.dat", False) request.addfinalizer(tear_down)
#! Tests out the CG solver with CPHF Polarizabilities import time import numpy as np import psi4 psi4.set_output_file("output.dat") # Benzene mol = psi4.geometry(""" 0 1 O 0.000000000000 0.000000000000 -0.075791843589 H 0.000000000000 -0.866811828967 0.601435779270 H 0.000000000000 0.866811828967 0.601435779270 symmetry c1 """) psi4.set_options({"basis": "aug-cc-pVDZ", "scf_type": "df", "e_convergence": 1e-8, "save_jk": True, }) scf_e, scf_wfn = psi4.energy("SCF", return_wfn=True) # Orbitals Co = scf_wfn.Ca_subset("AO", "OCC") Cv = scf_wfn.Ca_subset("AO", "VIR") # Mints object
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)