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 run_json(json_data, clean=True): # Set scratch if "scratch_location" in json_data: psi4_io = core.IOManager.shared_object() psi4_io.set_default_path(json_data["scratch_location"]) # Direct output outfile = os.path.join(core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out") core.set_output_file(outfile, False) # Set memory if "memory" in json_data: psi4.set_memory(json_data["memory"]) # Do we return the output? return_output = json_data.pop("return_output", False) if return_output: json_data["raw_output"] = "Not yet run." # Set a few flags json_data["raw_output"] = None json_data["success"] = False # Attempt to run the computer try: # qcschema should be copied json_data = run_json_qcschema(copy.deepcopy(json_data), clean) except Exception as exc: json_data["error"] = { 'error_type': type(exc).__name__, 'error_message': ''.join(traceback.format_exception(*sys.exc_info())), } json_data["success"] = False json_data["raw_output"] = _read_output(outfile) if return_output: json_data["raw_output"] = _read_output(outfile) # Destroy the created file at exit def _quiet_remove(filename): try: os.unlink(filename) except OSError: pass atexit.register(_quiet_remove, outfile) return json_data
def test_psi4(): assert "psi4" in sys.modules psi4.set_memory('500 MB') h2o = psi4.geometry(""" O H 1 0.96 H 1 0.96 2 104.5 """) res = psi4.energy('scf/cc-pvdz') assert res != 0
def run_json(json_data, clean=True): # Set scratch if "scratch_location" in json_data: psi4_io = core.IOManager.shared_object() psi4_io.set_default_path(json_data["scratch_location"]) # Direct output outfile = os.path.join(core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out") core.set_output_file(outfile, False) # Set memory if "memory" in json_data: psi4.set_memory(json_data["memory"]) # Do we return the output? return_output = json_data.pop("return_output", False) if return_output: json_data["raw_output"] = "Not yet run." # Set a few flags json_data["raw_output"] = None json_data["success"] = False # Attempt to run the computer try: # qcschema should be copied json_data = run_json_qcschema(copy.deepcopy(json_data), clean) except Exception as exc: json_data["error"] = { 'error_type': type(exc).__name__, 'error_message': ''.join(traceback.format_exception(*sys.exc_info())), } json_data["success"] = False json_data["raw_output"] = _read_output(outfile) if return_output: json_data["raw_output"] = _read_output(outfile) # Destroy the created file at exit def _quiet_remove(filename): try: os.unlink(filename) except OSError: pass atexit.register(_quiet_remove, outfile) return json_data
def calc_homo_lumo(smiles): mol = Chem.MolFromSmiles(smiles) xyz, mol = mol_to_xyz(mol) psi4.set_memory('4 GB') psi4.set_num_threads(4) geom = psi4.geometry(xyz) method_basis = args.method + '/' + args.basis e, wfn = psi4.energy(method_basis, return_wfn=True) h**o = wfn.epsilon_a_subset('AO', 'ALL').np[wfn.nalpha() - 1] lumo = wfn.epsilon_a_subset('AO', 'ALL').np[wfn.nalpha()] print("SMILES: " + smiles + ", Energy: " + str(e) + " H, H**O: " + str(h**o) + " H, LUMO: " + str(lumo) + " H") return h**o, lumo, e
def test_dipole_h2_2_cc_pvdz(): """He cc-pVDZ""" psi4.set_memory('2 GiB') psi4.core.set_output_file('output.dat', False) psi4.set_options({ 'basis': 'cc-pVDZ', 'scf_type': 'pk', 'mp2_type': 'conv', 'freeze_core': 'false', 'e_convergence': 1e-13, 'd_convergence': 1e-13, 'r_convergence': 1e-13, 'diis': 1 }) mol = psi4.geometry(moldict["(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) # no laser rtcc = pycc.rtcc(cc, cclambda, ccdensity, None, magnetic=True) y0 = rtcc.collect_amps(cc.t1, cc.t2, cclambda.l1, cclambda.l2).astype('complex128') t1, t2, l1, l2 = rtcc.extract_amps(y0) ref = [0, 0, 0.005371586416860086] # au mu_x, mu_y, mu_z = rtcc.dipole(t1, t2, l1, l2) opdm = rtcc.ccdensity.compute_onepdm(t1, t2, l1, l2, withref=True) assert (abs(ref[0] - mu_x) < 1E-10) assert (abs(ref[1] - mu_y) < 1E-10) assert (abs(ref[2] - mu_z) < 1E-10) ref = [0, 0, -2.3037968376087573E-5] m_x, m_y, m_z = rtcc.dipole(t1, t2, l1, l2, magnetic=True) assert (abs(ref[0] * 1.0j - m_x) < 1E-10) assert (abs(ref[1] * 1.0j - m_y) < 1E-10) assert (abs(ref[2] * 1.0j - m_z) < 1E-10)
def process_molecule(filenum, thermochemical=False): psi4.core.set_output_file(generate_output_file_path(filenum), False) psi4.set_memory("2 GB") molecule = get_molecule_from_file(filenum) computational_method = FUNCTIONAL + '/' + BASIS_SET if thermochemical: e, wfn = psi4.freq(computational_method, molecule=molecule, return_wfn=True) else: e, wfn = psi4.energy(computational_method, molecule=molecule, return_wfn=True) return wfn
def test_density_ccsd_h2o(): """H2O""" # Psi4 Setup psi4.set_memory('2 GB') psi4.core.set_output_file('output.dat', False) psi4.set_options({ 'basis': 'STO-3G', 'scf_type': 'pk', 'mp2_type': 'conv', 'freeze_core': 'true', 'e_convergence': 1e-12, 'd_convergence': 1e-12, 'r_convergence': 1e-12, 'diis': 1 }) mol = psi4.geometry(moldict["H2O"]) rhf_e, rhf_wfn = psi4.energy('SCF', return_wfn=True) maxiter = 75 e_conv = 1e-12 r_conv = 1e-12 ccsd = pycc.ccwfn(rhf_wfn) eccsd = ccsd.solve_cc(e_conv, r_conv) hbar = pycc.cchbar(ccsd) cclambda = pycc.cclambda(ccsd, hbar) lccsd = cclambda.solve_lambda(e_conv, r_conv) epsi4 = -0.070616830152761 lpsi4 = -0.068826452648939 ccdensity = pycc.ccdensity(ccsd, cclambda) ecc_density = ccdensity.compute_energy() assert (abs(epsi4 - eccsd) < 1e-11) assert (abs(lpsi4 - lccsd) < 1e-11) assert (abs(epsi4 - ecc_density) < 1e-11) psi4.set_options({'basis': 'cc-pVDZ'}) rhf_e, rhf_wfn = psi4.energy('SCF', return_wfn=True) ccsd = pycc.ccwfn(rhf_wfn) eccsd = ccsd.solve_cc(e_conv, r_conv) hbar = pycc.cchbar(ccsd) cclambda = pycc.cclambda(ccsd, hbar) lccsd = cclambda.solve_lambda(e_conv, r_conv) epsi4 = -0.222029814166783 lpsi4 = -0.217838951550509 ccdensity = pycc.ccdensity(ccsd, cclambda) ecc_density = ccdensity.compute_energy() assert (abs(epsi4 - eccsd) < 1e-11) assert (abs(lpsi4 - lccsd) < 1e-11) assert (abs(epsi4 - ecc_density) < 1e-11)
def calculate(inp, calc, save): '''Run nwchem on input, return data in results dict Args inp: Psi4 input object (geometry, bq_pos, bq_charges) calc: calculation type save: save calculation results Returns results: dictionary ''' options = params.options mol, bqfield, bqs = inp psi4.core.set_global_option_python('EXTERN', bqfield.extern) psi4.core.set_global_option('BASIS', options['basis']) psi4.set_memory(int(options['mem_mb'] * 1e6)) if options['correlation'] and calc not in ['esp', 'energy_hf']: theory = options['correlation'] psi4.core.set_global_option('freeze_core', 'True') else: theory = 'scf' method_str = theory + '/' + options['basis'] results = {} if calc == 'energy' or calc == 'energy_hf': results['E_tot'] = psi4.energy(method_str) elif calc == 'esp': raise RuntimeError("Not implemented") elif calc == 'gradient': grad, wfn = psi4.gradient(method_str, return_wfn=True) E = psi4.core.get_variable('CURRENT ENERGY') results['E'] = E results['gradient'] = psi4.p4util.mat2arr(grad) with open('grid.dat', 'w') as fp: for bq in bqs: fp.write('%16.10f%16.10f%16.10f\n' % (bq[0], bq[1], bq[2])) psi4.oeprop(wfn, 'GRID_FIELD') bq_field = np.loadtxt('grid_field.dat') assert bq_field.shape == (len(bqs), 3) bqgrad = [] for chg, field_vec in zip(bqs, bq_field): bqgrad.append(-1.0 * chg[3] * field_vec) results['bq_gradient'] = np.array(bqgrad) elif calc == 'hessian': hess = psi4.hessian(theory) hessarr = np.array(psi4.p4util.mat2arr(hess)) results['hess'] = hessarr return results
def calcE(conn, sys1, crd1, sys2, crd2, theory, basis): import psi4 olddir = os.getcwd() tmpdir = TemporaryDirectory(dir='/dev/shm') os.chdir(tmpdir.name) psi4.core.set_output_file('output.dat', False) psi4.set_memory('100 GB') #psi4.set_num_threads(18) psi4.set_num_threads(1) psi4.set_options({'freeze_core': 'true'}) cplx = psi4.geometry("{sys1}\n--\n{sys2}\nunits angstrom".format( sys1=sys1.fmt_psi4(crd1), sys2=sys2.fmt_psi4(crd2))) de = psi4.energy('%s/%s' % (theory, basis), bsse_type='cp', molecule=cplx) conn.send(de * psi4.constants.hartree2kcalmol) os.chdir(olddir) conn.close()
def execute_job(): job_id = {job_id} molecule = "{molecule}" method = "{method}" basis = "{basis}" number_of_threads = {num_threads} memory = "{memory}" try: max_threads = int(subprocess.check_output(["grep", "-c", "cores", "/proc/cpuinfo"])) print("Maximum threads: {format}".format(max_threads)) except: print("Error detecting number of cores. \n Maxium threads: 1") max_threads = 1 if number_of_threads > max_threads: print("Input number of threads ({format}) greater than max threads ({format}), limiting number of threads to max threads".format(number_of_threads, max_threads)) number_of_threads = max_threads print("Running Job") print("Molcule: {format}".format(molecule)) print("Method: {format}".format(method)) print("Basis: {format}".format(basis)) print("Threads {format}".format(number_of_threads)) print("Memory: {format}".format(memory)) psi4.core.set_output_file("job_{format}.log".format(job_id), False) psi4.set_memory(memory) psi4.geometry(molecule) psi4.set_num_threads(number_of_threads) try: energy = psi4.energy("{format}/{format}".format(method, basis)) print("Energy: {format}".format(energy)) success = True except ValueError: success = False print("Iterations failed to Converge") with open("job_{format}.out".format(job_id), "w") as out_file: out_file.write("Job: {format}\n".format(job_id)) if success: out_file.write("Energy: {format}".format(energy)) else: out_file.write("Failure")
def test_ccsd_t_h2o(): """H2O cc-pVDZ""" # Psi4 Setup psi4.set_memory('2 GB') psi4.core.set_output_file('output.dat', False) psi4.set_options({ 'basis': 'STO-3G', 'scf_type': 'pk', 'mp2_type': 'conv', 'freeze_core': 'true', 'e_convergence': 1e-12, 'd_convergence': 1e-12, 'r_convergence': 1e-12, 'diis': 1 }) mol = psi4.geometry(moldict["H2O"]) rhf_e, rhf_wfn = psi4.energy('SCF', return_wfn=True) maxiter = 75 e_conv = 1e-12 r_conv = 1e-12 cc = pycc.ccwfn(rhf_wfn) eccsd = cc.solve_cc(e_conv, r_conv, maxiter) tcorr = pycc.cctriples(cc) et_vik_ijk = tcorr.t_vikings() et_vik_abc = tcorr.t_vikings_inverted() et_tjl = tcorr.t_tjl() epsi4 = -0.000099957499645 assert (abs(epsi4 - et_vik_ijk) < 1e-11) assert (abs(epsi4 - et_vik_abc) < 1e-11) assert (abs(epsi4 - et_tjl) < 1e-11) psi4.set_options({'basis': 'cc-pVDZ'}) rhf_e, rhf_wfn = psi4.energy('SCF', return_wfn=True) cc = pycc.ccwfn(rhf_wfn) eccsd = cc.solve_cc(e_conv, r_conv, maxiter) tcorr = pycc.cctriples(cc) et_vik_ijk = tcorr.t_vikings() et_vik_abc = tcorr.t_vikings_inverted() et_tjl = tcorr.t_tjl() epsi4 = -0.003861236558801 assert (abs(epsi4 - et_vik_ijk) < 1e-11) assert (abs(epsi4 - et_vik_abc) < 1e-11) assert (abs(epsi4 - et_tjl) < 1e-11)
def run_json(json_data, clean=True): # Set scratch if "scratch_location" in json_data: psi4_io = core.IOManager.shared_object() psi4_io.set_default_path(json_data["scratch_location"]) # Direct output outfile = os.path.join(core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out") core.set_output_file(outfile, False) # Set memory if "memory" in json_data: psi4.set_memory(json_data["memory"]) # Do we return the output? return_output = json_data.pop("return_output", False) if return_output: json_data["raw_output"] = "Not yet run." # Set a few flags json_data["raw_output"] = None json_data["success"] = False # Attempt to run the computer try: if json_data.get("schema_name", "").startswith("qc_schema"): # qc_schema should be copied json_data = run_json_qc_schema(copy.deepcopy(json_data), clean) else: # Original run updates inplace run_json_original_v1_1(json_data, clean) except Exception as error: json_data["error"] = repr(error) json_data["success"] = False if return_output: with open(outfile, 'r') as f: json_data["raw_output"] = f.read() os.unlink(outfile) return json_data
def run_json(json_data, clean=True): # Set scratch if "scratch_location" in json_data: psi4_io = core.IOManager.shared_object() psi4_io.set_default_path(json_data["scratch_location"]) # Direct output outfile = os.path.join(core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out") core.set_output_file(outfile, False) # Set memory if "memory" in json_data: psi4.set_memory(json_data["memory"]) # Do we return the output? return_output = json_data.pop("return_output", False) if return_output: json_data["raw_output"] = "Not yet run." # Set a few flags json_data["raw_output"] = None json_data["success"] = False # Attempt to run the computer try: # qc_schema should be copied json_data = run_json_qc_schema(copy.deepcopy(json_data), clean) except Exception as error: exc_type, exc_value, exc_traceback = sys.exc_info() json_data["error"] = repr(traceback.format_exception(exc_type, exc_value, exc_traceback)) json_data["success"] = False with open(outfile, 'r') as f: json_data["raw_output"] = f.read() if return_output: with open(outfile, 'r') as f: json_data["raw_output"] = f.read() atexit.register(os.unlink, outfile) return json_data
def run_json(json_data, clean=True): # Set scratch if "scratch_location" in json_data: psi4_io = core.IOManager.shared_object() psi4_io.set_default_path(json_data["scratch_location"]) # Direct output outfile = os.path.join(core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out") core.set_output_file(outfile, False) # Set memory if "memory" in json_data: psi4.set_memory(json_data["memory"]) # Do we return the output? return_output = json_data.pop("return_output", False) if return_output: json_data["raw_output"] = "Not yet run." # Set a few flags json_data["raw_output"] = None json_data["success"] = False # Attempt to run the computer try: if json_data.get("schema_name", "").startswith("qc_schema"): # qc_schema should be copied json_data = run_json_qc_schema(copy.deepcopy(json_data), clean) else: # Original run updates inplace run_json_original_v1_1(json_data, clean) except Exception as error: json_data["error"] = repr(error) json_data["success"] = False if return_output: with open(outfile, 'r') as f: json_data["raw_output"] = f.read() atexit.register(os.unlink, outfile) return json_data
def G_Thread(cml_file): np.set_printoptions(threshold = 10000000000000) tree = ET.parse(cml_file) root = tree.getroot() method = root[2].attrib['name'] basis = root[3].attrib['name'] sign = int(root[4].attrib['name']) import psi4 order = Get_Order(cml_file) geom = Get_Geom_String(cml_file) psi4.set_options({'FAIL_ON_MAXITER': False}) psi4.geometry(geom) psi4.core.be_quiet() psi4.set_memory('1 GB') grad, wfn = psi4.gradient(method+'/'+basis, return_wfn=True) energy = wfn.energy()*order grad = np.asarray(grad) true_grad = Interpret(grad, cml_file)*order return tuple([sign*true_grad, sign*energy])
def HFenergy(row): psi4.set_memory('500 MB') #charge = +1, spin multipicity = 2 h2o = psi4.geometry(""" 1 2 O {} {} {} C {} {} {} H {} {} {} H {} {} {} """.format(*row)) psi4.set_options({'reference': 'uhf'}) #Energy calculated using UHF/cc-pVDZ try: return psi4.energy('scf/cc-pvdz') except: #In case there's a convergence error or alike return 0.0
def run_json(json_data, clean=True): # Set scratch if "scratch_location" in json_data: psi4_io = core.IOManager.shared_object() psi4_io.set_default_path(json_data["scratch_location"]) # Set memory if "memory" in json_data: psi4.set_memory(json_data["memory"]) # Do we return the output? return_output = json_data.pop("return_output", False) if return_output: outfile = os.path.join( core.IOManager.shared_object().get_default_path(), str(uuid.uuid4()) + ".json_out") core.set_output_file(outfile, False) json_data["raw_output"] = "Not yet run." # Set a few flags json_data["raw_output"] = None json_data["success"] = False # Attempt to run the computer try: if ("schema_name" in json_data) and (json_data["schema_name"] == "QC_JSON"): run_json_qc_schema(json_data, clean) else: run_json_original_v1_1(json_data, clean) except Exception as error: json_data["error"] = repr(error) json_data["success"] = False if return_output: with open(outfile, 'r') as f: json_data["raw_output"] = f.read() os.unlink(outfile) return json_data
def test_pao_H8(): """PAO-CCSD Test""" # Psi4 Setup psi4.set_memory('1 GB') psi4.core.set_output_file('output.dat', False) psi4.set_options({'basis': 'DZ', 'scf_type': 'pk', 'guess': 'core', 'mp2_type': 'conv', 'freeze_core': 'False', 'e_convergence': 1e-12, 'd_convergence': 1e-12, 'r_convergence': 1e-12, 'diis': 8}) mol = psi4.geometry(""" H 0.000000 0.000000 0.000000 H 0.750000 0.000000 0.000000 H 0.000000 1.500000 0.000000 H 0.375000 1.500000 -0.649520 H 0.000000 3.000000 0.000000 H -0.375000 3.000000 -0.649520 H 0.000000 4.500000 -0.000000 H -0.750000 4.500000 -0.000000 symmetry c1 noreorient nocom """) rhf_e, rhf_wfn = psi4.energy('SCF', return_wfn=True) maxiter = 75 e_conv = 1e-12 r_conv = 1e-12 max_diis = 8 ccsd = pycc.ccwfn(rhf_wfn, local='PAO', local_cutoff=2e-2) eccsd = ccsd.solve_cc(e_conv, r_conv, maxiter, max_diis) # (H2)_4 REFERENCE: psi3_ref = -0.108914240219735 assert (abs(psi3_ref - eccsd) < 1e-7)
def get_ao_integrals(molecule: of.MolecularData, e_convergence: Optional[float] = 1e-8): """Use psi4numpy to grab the atomic orbital integrals Modified from https://github.com/psi4/psi4numpy/blob/master/Tutorials/01_Psi4NumPy-Basics/1e_mints-helper.ipynb Args: molecule: The molecule for which to get the integrals. """ if NO_PSI4: raise NOPsi4Error("Psi4 is not installed") psi4.core.be_quiet() allocated_ram_gb = 0.5 psi4.set_memory(f"{allocated_ram_gb} GB") psi4.core.be_quiet() mol = psi4.geometry(""" {} {} {} symmetry c1 """.format(molecule.charge, molecule.multiplicity, create_geometry_string(molecule.geometry))) psi4.set_options({ 'basis': molecule.basis, 'scf_type': 'pk', 'e_convergence': e_convergence }) wfn = psi4.core.Wavefunction.build(mol, psi4.core.get_global_option('basis')) mints = psi4.core.MintsHelper(wfn.basisset()) ao_overlap = np.asarray(mints.ao_overlap()) ao_eri = np.asarray( mints.ao_eri()) # [Gives integrals in Chemist form [(𝜇𝜈∣𝜆𝜎)] ao_kinetic = np.asarray(mints.ao_kinetic()) ao_potential = np.asarray(mints.ao_potential()) ao_core_hamiltonian = ao_kinetic + ao_potential return ao_overlap, ao_core_hamiltonian, ao_eri
def psi4_scf(params, geometries): """ Function to run SCF along IRC using PSI4, returns array of energies at each geometry. """ print_header(params.outfile) energies = [] wavefunctions = [] count = 0 start = time.time() level_of_theory = "%s/%s" % (params.method, params.basis) if (params.do_solvent): set_solvent_parameters(params) for geometry in geometries: output = open(params.outfile, "a") psi4.core.set_output_file("psi4_output/irc_%d.out" % count, False) geom = geometry geom += "\nsymmetry c1" mol = psi4.geometry(geom) psi4.set_options(params.keywords) #print("pyREX:Single Point Calculation on IRC Point %d" %(count)) psi4.set_num_threads(params.nthreads) if (params.set_memory): psi4.set_memory(params.memory_allocation) energy, wfn = psi4.energy(level_of_theory, return_wfn=True) #wfn = psi4.core.Wavefunction.build(mol, self.basis) ndocc = wfn.doccpi()[0] #print(ndocc) eps = np.array(wfn.epsilon_a()) #print(eps) homo_energy = eps[ndocc - 1] lumo_energy = eps[ndocc] energies.append(energy) wavefunctions.append(wfn) output.write('{:>20.2f} {:>20.4f} {:>20.4f} {:>20.4f}\n'.format( params.coordinates[count], energy, homo_energy, lumo_energy)) count = count + 1 output.close() print_footer(params.outfile) end = time.time() print("psi4 Time = %f" % (end - start)) return energies, wavefunctions
def load_atomic_orbitals_integrals(self, ): """To load overlap, kinetic, couloumb, exchange integrals from psi4.""" # Use the Psi4 to load the atomic basis set used for its SCF Calculation opts = { 'basis': self.ao_basis, 'reference': 'rhf', 'scf_type': 'direct', 'guess': 'core' } psi4.set_memory("263 MB") psi4.core.clean() psi4_mol = psi4.geometry(self.geometry_text) psi4.set_options(opts) psi4_mol_wf = psi4.core.Wavefunction.build( psi4_mol, psi4.core.get_global_option('BASIS')) mints = psi4.core.MintsHelper(psi4_mol_wf.basisset( )) # Call The MintsHelper function to get the integrals. # Get the various integrals self.molecule["integrals"]["no_of_AO"] = mints.ao_overlap().rows( 0) # Number of atomic basis function self.molecule["integrals"]["S"] = np.asarray(mints.ao_overlap( )) # AO basis overlap integral # Col: AO, Row: AO self.molecule["integrals"]["T"] = np.asarray(mints.ao_kinetic( )) # AO basis kinetic integrals # Col: AO, Row: AO self.molecule["integrals"]["V"] = np.asarray(mints.ao_potential( )) # AO basis potential integrals # Col: AO, Row: AO self.molecule["integrals"]["Hcore"] = self.molecule["integrals"][ "T"] + self.molecule["integrals"]["V"] self.molecule["integrals"]["II"] = np.asarray( mints.ao_eri() ) # AO ERI integrals # Axes0: AO, Axes1: AO, Axes2: AO, Axes3: AO, self.molecule["reference"][ "nuclear_replusion"] = psi4.core.Molecule.nuclear_repulsion_energy( psi4_mol) return
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 begin(self): psi_path = which("psi4") psi_path, tail = os.path.split(psi_path) psi_path, tail = os.path.split(psi_path) os.environ["PSI"] = psi_path conda_path = "/".join(psi_path.split("/")[:-1]) os.environ["PSIPATH"] = psi_path os.environ["PSI_SCRATCH"] = tempfile.gettempdir() os.environ["PSI_SCRATCH_LOCAL"] = tempfile.mkdtemp() psi4.set_memory("1 GB") self.basis_guess_str = "false" if (self.args.guess_basis and self.args.spe_basis not in ["sto-3g", "3-21G", "minix"] and self.args.opt_basis not in ["3-21G", "sto-3g", "minix"]): self.basis_guess_str = "true" self.use_soscf_str = "false" if (self.args.use_soscf and self.args.spe_basis not in ["sto-3g", "3-21G", "minix"] and self.args.opt_basis not in ["3-21G", "sto-3g", "minix"]): self.use_soscf_str = "true" self.psi4opts = { "scf_type": self.args.scf_type, "fail_on_maxiter": "false", "guess_basis": self.basis_guess_str, "use_soscf": self.use_soscf_str, "dft_radial_points": self.args.dft_radial_points, "dft_spherical_points": self.args.dft_spherical_points, "num_processors": self.args.num_processors, "g_convergence": self.args.g_convergence, "max_disp_g_convergence": self.args.max_disp_g_convergence, }
def test_dimers_mt_tyr_frozen_orientation(): # Starting at R ~ 5 Angstroms init_xyz = """ C -1.258686 0.546935 0.436840 H -0.683650 1.200389 1.102833 C -0.699036 -0.349093 -0.396608 C -2.693370 0.550414 0.355311 H -3.336987 1.206824 0.952052 C -3.159324 -0.343127 -0.536418 H -4.199699 -0.558111 -0.805894 S -1.883829 -1.212288 -1.301525 C 0.786082 -0.656530 -0.606057 H 1.387673 -0.016033 0.048976 H 1.054892 -0.465272 -1.651226 H 0.978834 -1.708370 -0.365860 -- C -6.955593 -0.119764 -1.395442 C -6.977905 -0.135060 1.376787 C -7.111625 1.067403 -0.697024 C -6.810717 -1.314577 -0.707746 C -6.821873 -1.322226 0.678369 C -7.122781 1.059754 0.689090 H -7.226173 2.012097 -1.240759 H -6.687348 -2.253224 -1.259958 H -6.707325 -2.266920 1.222105 H -7.246150 1.998400 1.241304 O -6.944245 -0.111984 -2.805375 H -7.058224 0.807436 -3.049180 C -6.990227 -0.143507 2.907714 H -8.018305 -0.274985 3.264065 H -6.592753 0.807024 3.281508 H -6.368443 -0.968607 3.273516 nocom unit angstrom """ # Note that nocom is needed so psi4 does not move the fragment COM's. # Define the reference atoms for each fragment, as a linear combination # of the positions of one or more atoms of the fragment. # If no weights are given, then the atoms are equally weighted. MTdimer = { "Natoms per frag": [12, 16], "A Frag": 1, "A Ref Atoms": [[1, 3, 4, 6, 8], [8], [11]], "A Label": "methylthiophene", "B Frag": 2, "B Ref Atoms": [[13, 14, 15, 16, 17, 18], [13], [15]], "B Label": "tyrosine", "Frozen": ["theta_A", "theta_B", "tau", "phi_A", "phi_B"], } # Here are the dimer coordinates that are used with their definitions. # R : Distance A1 to B1 # theta_A : Angle, A2-A1-B1 # theta_B : Angle, A1-B1-B2 # tau : Dihedral angle, A2-A1-B1-B2 # phi_A : Dihedral angle, A3-A2-A1-B1 # phi_B : Dihedral angle, A1-B1-B2-B3 # Build the psi4 molecule. MTmol = psi4.geometry(init_xyz) # To see the values of the interfragment coordinates, do this: # MTdimerCoord = optking.dimerfrag.DimerFrag.fromUserDict(MTdimer) # Axyz = MTmol.geometry().np[0:12,] # Bxyz = MTmol.geometry().np[12:,] # MTdimerCoord.update_reference_geometry(Axyz, Bxyz) # print( MTdimerCoord ) # quit() # Choose a theory psi4.set_memory("4000.0 MB") psi4.core.clean_options() psi4_options = { "basis": "6-31G(d)", "d_convergence": 9, "frag_mode": "multi", } psi4.set_options(psi4_options) # For the moment, 'interfrag_coords' is a non-standard keyword and so # must be passed like this. # Optimize fragments and R but not interfragment angular coordinates. result = optking.optimize_psi4("b3lyp-d3mbj", **{"interfrag_coords": str(MTdimer)}) E = result["energies"][-1] REF_631Gd_Energy = -939.169521 REF_321G_Energy = -934.237170 assert psi4.compare_values(REF_631Gd_Energy, E, 4, "B3LYP-D3MBJ energy") # TEST
__authors__ = "Daniel G. A. Smith" __credits__ = ["Daniel G. A. Smith"] __copyright__ = "(c) 2014-2018, The Psi4NumPy Developers" __license__ = "BSD-3-Clause" __date__ = "2017-9-30" import time import numpy as np from helper_HF import * np.set_printoptions(precision=5, linewidth=200, suppress=True) import psi4 # Memory for Psi4 in GB psi4.set_memory('2 GB') psi4.core.set_output_file('output.dat', False) # Memory for numpy in GB numpy_memory = 2 # Triplet O2 mol = psi4.geometry(""" 0 3 O O 1 1.2 symmetry c1 """) psi4.set_options({'guess': 'core', 'basis': 'aug-cc-pvdz',
def compute(self, input_model: "AtomicInput", config: "TaskConfig") -> "AtomicResult": """ Runs Psi4 in API mode """ self.found(raise_error=True) pversion = parse_version(self.get_version()) if pversion < parse_version("1.2"): raise ResourceError("Psi4 version '{}' not understood.".format( self.get_version())) # Location resolution order config.scratch_dir, $PSI_SCRATCH, /tmp parent = config.scratch_directory if parent is None: parent = os.environ.get("PSI_SCRATCH", None) error_type = None error_message = None compute_success = False if isinstance(input_model.model.basis, BasisSet): raise InputError( "QCSchema BasisSet for model.basis not implemented. Use string basis name." ) # Basis must not be None for HF3c old_basis = input_model.model.basis input_model.model.__dict__["basis"] = old_basis or "" with temporary_directory(parent=parent, suffix="_psi_scratch") as tmpdir: caseless_keywords = { k.lower(): v for k, v in input_model.keywords.items() } if (input_model.molecule.molecular_multiplicity != 1) and ("reference" not in caseless_keywords): input_model.keywords["reference"] = "uhf" # Old-style JSON-based command line if pversion < parse_version("1.4a2.dev160"): # Setup the job input_data = input_model.dict(encoding="json") input_data["nthreads"] = config.ncores input_data["memory"] = int(config.memory * 1024 * 1024 * 1024 * 0.95) # Memory in bytes input_data["success"] = False input_data["return_output"] = True if input_data["schema_name"] == "qcschema_input": input_data["schema_name"] = "qc_schema_input" # Execute the program success, output = execute( [ which("psi4"), "--scratch", tmpdir, "--json", "data.json" ], {"data.json": json.dumps(input_data)}, ["data.json"], scratch_directory=tmpdir, ) output_data = input_data.copy() if success: output_data = json.loads(output["outfiles"]["data.json"]) if "extras" not in output_data: output_data["extras"] = {} # Check QCVars local_qcvars = output_data.pop("psi4:qcvars", None) if local_qcvars: # Edge case where we might already have qcvars, should not happen if "qcvars" in output_data["extras"]: output_data["extras"][ "local_qcvars"] = local_qcvars else: output_data["extras"]["qcvars"] = local_qcvars if output_data.get("success", False) is False: error_message, error_type = self._handle_errors( output_data) else: compute_success = True else: error_message = output.get("stderr", "No STDERR output") error_type = "execution_error" # Reset the schema if required output_data["schema_name"] = "qcschema_output" output_data.pop("memory", None) output_data.pop("nthreads", None) output_data["stdout"] = output_data.pop("raw_output", None) else: if input_model.extras.get("psiapi", False): import psi4 orig_scr = psi4.core.IOManager.shared_object( ).get_default_path() psi4.core.set_num_threads(config.ncores, quiet=True) psi4.set_memory(f"{config.memory}GB", quiet=True) # psi4.core.IOManager.shared_object().set_default_path(str(tmpdir)) if pversion < parse_version( "1.4"): # adjust to where DDD merged # slightly dangerous in that if `qcng.compute({..., psiapi=True}, "psi4")` called *from psi4 # session*, session could unexpectedly get its own files cleaned away. output_data = psi4.schema_wrapper.run_qcschema( input_model).dict() else: output_data = psi4.schema_wrapper.run_qcschema( input_model, postclean=False).dict() # success here means execution returned. output_data may yet be qcel.models.AtomicResult or qcel.models.FailedOperation success = True if output_data.get("success", False): output_data["extras"]["psiapi_evaluated"] = True psi4.core.IOManager.shared_object().set_default_path( orig_scr) else: run_cmd = [ which("psi4"), "--scratch", str(tmpdir), "--nthread", str(config.ncores), "--memory", f"{config.memory}GB", "--qcschema", "data.msgpack", ] input_files = { "data.msgpack": input_model.serialize("msgpack-ext") } success, output = execute(run_cmd, input_files, ["data.msgpack"], as_binary=["data.msgpack"], scratch_directory=tmpdir) if success: output_data = deserialize( output["outfiles"]["data.msgpack"], "msgpack-ext") else: output_data = input_model.dict() if success: if output_data.get("success", False) is False: error_message, error_type = self._handle_errors( output_data) else: compute_success = True else: error_message = output.get("stderr", "No STDERR output") error_type = "execution_error" # Dispatch errors, PSIO Errors are not recoverable for future runs if compute_success is False: if "PSIO Error" in error_message: if "scratch directory" in error_message: # Psi4 cannot access the folder or file raise ResourceError(error_message) else: # Likely a random error, worth retrying raise RandomError(error_message) elif ("SIGSEV" in error_message) or ( "SIGSEGV" in error_message) or ("segmentation fault" in error_message): raise RandomError(error_message) elif ("TypeError: set_global_option" in error_message) or (error_type == "ValidationError"): raise InputError(error_message) elif "RHF reference is only for singlets" in error_message: raise InputError(error_message) else: raise UnknownError(error_message) # Reset basis output_data["model"]["basis"] = old_basis # Move several pieces up a level output_data["provenance"]["memory"] = round(config.memory, 3) output_data["provenance"]["nthreads"] = config.ncores # Delete keys output_data.pop("return_output", None) return AtomicResult(**output_data)
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())
DOI: 10.1002/qua.560160825 """ __authors__ = "Ashutosh Kumar" __credits__ = ["Ashutosh Kumar"] __copyright__ = "(c) 2014-2017, 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 1.1 H 1 1.1 2 104 symmetry c1 """) psi4.core.set_active_molecule(mol) options = { 'BASIS': 'STO-3G', 'SCF_TYPE': 'PK',
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.core.set_output_file(args["output"], args["append"]) # 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: if not os.path.isdir(args["scratch"]): raise Exception("Passed in scratch is not a directory (%s)." % args["scratch"]) psi4.core.IOManager.shared_object().set_default_path(
from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem.rdDistGeom import ETKDGv3, EmbedMolecule from rdkit.Chem.rdForceFieldHelpers import MMFFHasAllMoleculeParams, MMFFOptimizeMolecule from rdkit.Chem.Draw import IPythonConsole import psi4 import datetime import time time #計算時間を見てみる # ハードウェア側の設定(計算に用いるCPUのスレッド数とメモリ設定) psi4.set_num_threads(nthread=3) psi4.set_memory("3GB") ## 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
__copyright__ = "(c) 2014-2017, The Psi4NumPy Developers" __license__ = "BSD-3-Clause" __date__ = "2017-08-28" import time import numpy as np np.set_printoptions(precision=5, linewidth=200, suppress=True) import psi4 import pylibefp import os # Memory for Psi4 in GB psi4.set_memory('500 MB') psi4.core.set_output_file("output.dat", False) # Memory for numpy in GB numpy_memory = 2 def set_qm_atoms(mol, efpobj): """Provides list of coordinates of quantum mechanical atoms from psi4.core.Molecule `mol` to pylibefp.core.efp() `efpobj`. """ ptc = [] coords = [] for iat in range(mol.natom()): ptc.append(mol.charge(iat))
DOI: 10.1002/qua.560160825 """ __authors__ = "Ashutosh Kumar" __credits__ = ["Ashutosh Kumar"] __copyright__ = "(c) 2014-2017, 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 1.1 H 1 1.1 2 104 symmetry c1 """) psi4.core.set_active_molecule(mol) options = {'BASIS':'STO-3G', 'SCF_TYPE':'PK', 'E_CONVERGENCE':1e-10, 'D_CONVERGENCE':1e-10
""" __authors__ = "Daniel G. A. Smith" __credits__ = ["Daniel G. A. Smith"] __copyright__ = "(c) 2014-2018, The Psi4NumPy Developers" __license__ = "BSD-3-Clause" __date__ = "2017-9-30" import time import numpy as np np.set_printoptions(precision=5, linewidth=200, suppress=True) import psi4 # Memory for Psi4 in GB psi4.set_memory('500 MB') psi4.core.set_output_file("output.dat", False) # Memory for numpy in GB numpy_memory = 2 mol = psi4.geometry(""" O H 1 1.1 H 1 1.1 2 104 symmetry c1 """) psi4.set_options({'basis': 'cc-pvdz', 'scf_type': 'pk', 'e_convergence': 1e-8})
def test_rtcc_water_cc_pvdz(): """H2O cc-pVDZ""" psi4.set_memory('2 GiB') psi4.core.set_output_file('output.dat', False) psi4.set_options({ 'basis': 'cc-pVDZ', 'scf_type': 'pk', 'mp2_type': 'conv', 'freeze_core': 'false', 'e_convergence': 1e-13, 'd_convergence': 1e-13, 'r_convergence': 1e-13, 'diis': 1 }) mol = psi4.geometry(moldict["H2O"]) rhf_e, rhf_wfn = psi4.energy('SCF', return_wfn=True) e_conv = 1e-13 r_conv = 1e-13 cc = pycc.ccwfn(rhf_wfn) ecc = cc.solve_cc(e_conv, r_conv) hbar = pycc.cchbar(cc) cclambda = pycc.cclambda(cc, hbar) lecc = cclambda.solve_lambda(e_conv, r_conv) ccdensity = pycc.ccdensity(cc, cclambda) # Gaussian pulse (a.u.) F_str = 0.01 omega = 0 sigma = 0.01 center = 0.05 V = gaussian_laser(F_str, omega, sigma, center) # RT-CC Setup t0 = 0 tf = 0.1 h = 0.01 t = t0 rtcc = pycc.rtcc(cc, cclambda, ccdensity, V) y0 = rtcc.collect_amps(cc.t1, cc.t2, cclambda.l1, cclambda.l2).astype('complex128') y = y0 ODE = rk4(h) t1, t2, l1, l2 = rtcc.extract_amps(y0) mu0_x, mu0_y, mu0_z = rtcc.dipole(t1, t2, l1, l2) ecc0 = rtcc.lagrangian(t0, t1, t2, l1, l2) # For saving data at each time step. """ dip_x = [] dip_y = [] dip_z = [] time_points = [] dip_x.append(mu0_x) dip_y.append(mu0_y) dip_z.append(mu0_z) time_points.append(t) """ while t < tf: y = ODE(rtcc.f, t, y) t += h t1, t2, l1, l2 = rtcc.extract_amps(y) mu_x, mu_y, mu_z = rtcc.dipole(t1, t2, l1, l2) ecc = rtcc.lagrangian(t, t1, t2, l1, l2) """ dip_x.append(mu_x) dip_y.append(mu_y) dip_z.append(mu_z) time_points.append(t) """ print(mu_z) mu_z_ref = -0.34894577 assert (abs(mu_z_ref - mu_z.real) < 1e-4)
__authors__ = "Daniel R. Nascimento" __credits__ = ["Daniel R. Nascimento"] __copyright__ = "(c) 2014-2018, The Psi4NumPy Developers" __license__ = "BSD-3-Clause" __date__ = "2017-04-22" import time import numpy as np from helper_CC import * np.set_printoptions(precision=14, linewidth=200, suppress=True) import psi4 # Set memory psi4.set_memory(int(2e9), True) psi4.core.set_output_file('output.dat', True) numpy_memory = 2 mol = psi4.geometry(""" C 0.0 0.0 0.0 O 0.0 0.0 1.0 symmetry c1 no_reorient """) psi4.set_options({'basis': 'sto-3g', 'scf_type': 'pk', 'mp2_type': 'conv', 'freeze_core': 'false',
""" __authors__ = "Daniel G. A. Smith" __credits__ = ["Daniel G. A. Smith", "Dominic A. Sirianni"] __copyright__ = "(c) 2014-2017, The Psi4NumPy Developers" __license__ = "BSD-3-Clause" __date__ = "2017-05-23" import time import numpy as np np.set_printoptions(precision=5, linewidth=200, suppress=True) import psi4 # Memory for Psi4 in GB psi4.set_memory('2 GB') psi4.core.set_output_file('output.dat', False) # Memory for numpy in GB numpy_memory = 2 mol = psi4.geometry(""" O H 1 1.1 H 1 1.1 2 104 symmetry c1 """) psi4.set_options({ 'basis': 'aug-cc-pvdz', 'scf_type': 'pk',
def set_memory(bytes): """Function to reset the total memory allocation.""" psi4.set_memory(bytes)