Exemplo n.º 1
0
    def _run_psi4(self, options: dict, method=None, return_wfn=True, point_group=None, filename: str = None,
                  guess_wfn=None, ref_wfn=None, *args, **kwargs):
        psi4.core.clean()

        if self.active_space and not self.active_space.psi4_representable:
            print("Warning: Active space is not Psi4 representable")

        if "threads" in kwargs:
            psi4.set_num_threads(nthread=kwargs["threads"])

        if filename is None:
            filename = "{}_{}.out".format(self.parameters.filename, method)

        psi4.core.set_output_file(filename)

        # easier guess read in
        if guess_wfn is not None:
            if isinstance(guess_wfn, QuantumChemistryPsi4):
                guess_wfn = guess_wfn.logs["hf"].wfn
            if isinstance(guess_wfn, str):
                guess_wfn = psi4.core.Wavefunction.from_file(guess_wfn)
            guess_wfn.to_file(guess_wfn.get_scratch_filename(180))  # this is necessary
            options["guess"] = "read"

        # prevent known flaws
        if "guess" in options and options["guess"].lower() == "read":
            options["basis_guess"] = False
            # additionally the outputfile needs to be the same
            # as in the previous guess
            # this can not be determined here
            # better pass down a guess_wfn

        mol = psi4.geometry(self.parameters.get_geometry_string())
        mol.set_multiplicity(self.parameters.multiplicity)
        if self.parameters.multiplicity != 1:
            raise TequilaPsi4Exception("Multiplicity != 1 no yet supported")
        mol.set_molecular_charge(self.parameters.charge)

        if point_group is not None:
            mol.reset_point_group(point_group.lower())

        if ref_wfn is None and hasattr(self, "ref_wfn"):
            ref_wfn = self.ref_wfn

        if point_group is not None and point_group.lower() == "c1":
            ref_wfn = None  # ref_wfn.c1_deep_copy(ref_wfn.basisset())  # CC will not converge otherwise
            guess_wfn = None

        psi4.activate(mol)

        psi4.set_options(options)
        if ref_wfn is None or method.lower() == "hf":
            energy, wfn = psi4.energy(name=method.lower(), return_wfn=return_wfn, molecule=mol)
        else:
            energy, wfn = psi4.energy(name=method.lower(), ref_wfn=ref_wfn, return_wfn=return_wfn, molecule=mol,
                                      guess_wfn=guess_wfn)
        self.energies[method.lower()] = energy
        self.logs[method.lower()] = Psi4Results(filename=filename, variables=copy.deepcopy(psi4.core.variables()),
                                                wfn=wfn, mol=mol)
        return energy, wfn
Exemplo n.º 2
0
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")
Exemplo n.º 3
0
def setup_psi4(
    dft_radial_points=75,
    dft_spherical_points=302,
    num_processors=1,
    guess_basis="false",
    use_soscf="false",
    scf_type="DIRECT",
    fail_on_maxiter="false",
    g_convergence=None,
    max_disp_g_convergence=None,
):
    """Setup the control parameters for the psi4 job"""
    opts = dict()
    # opts['guess'] = 'sad'  # defaults to auto
    opts["scf_type"] = scf_type
    opts["fail_on_maxiter"] = fail_on_maxiter
    opts["basis_guess"] = guess_basis
    opts["soscf"] = use_soscf
    opts["dft_radial_points"] = dft_radial_points
    opts["dft_spherical_points"] = dft_spherical_points
    if g_convergence is not None:
        opts["g_convergence"] = g_convergence
    if max_disp_g_convergence is not None:
        opts["max_disp_g_convergence"] = max_disp_g_convergence

    psi4.set_options(opts)
    psi4.set_num_threads(num_processors)
Exemplo n.º 4
0
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")
Exemplo n.º 5
0
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")
Exemplo n.º 6
0
 def psi4_super(self):
     self.int_ = []
     all_atoms = self.frag_A + self.frag_B
     au_to_kcal = 627.51
     count = 0
     output = open(self.outfile, "a")
     output.write('\n\n--Supermolecular Interaction Energy--\n')
     output.write(
         '\n-------------------------------------------------------------------------------------------------'
     )
     output.write('\n{:>15} {:>15}\n'.format('IRC Point', 'E_int(kcal)'))
     output.write(
         '-------------------------------------------------------------------------------------------------\n'
     )
     output.close()
     for geometry in self.geometries:
         output = open(self.outfile, "a")
         psi4.core.set_output_file("psi4_output/irc_%d_sapt.out" % count,
                                   False)
         geometry += "symmetry c1"
         psi4.geometry(geometry)
         psi4.set_options({'reference': 'rhf', 'basis': self.basis})
         psi4.set_num_threads(self.nthreads)
         if (self.set_memory):
             psi4.set_memory(self.memory_allocation)
         #print("pyREX:SAPT Calculation on IRC Point %d" %(count))
         e_int = psi4.energy("%s/%s" % (self.method, self.basis),
                             bsse_type='cp')
         output.write('\n{:>15} {:>15.4f}\n'.format(count,
                                                    e_int * au_to_kcal))
         output.close()
         self.int_.append(e_int)
         count = count + 1
     return self.int_
Exemplo n.º 7
0
    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))
Exemplo n.º 8
0
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()
Exemplo n.º 9
0
def calc_vib_freq(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)
    e, wfn = psi4.frequency(method_basis, molecule=geom, return_wfn=True)
    print("SMILES: " + smiles + ", Vibrational Frequency Energy: " + str(e))
    return e
Exemplo n.º 10
0
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
Exemplo n.º 11
0
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
Exemplo n.º 12
0
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
Exemplo n.º 13
0
def test_threaded_blas(args):
    threads = int(args.nthread)

    times = {}

    size = [200, 500, 2000, 4000]
    threads = [1, threads]

    for th in threads:
        psi4.set_num_threads(th)

        for sz in size:
            nruns = max(1, int(1.e10 / (sz**3)))

            a = psi4.core.Matrix(sz, sz)
            b = psi4.core.Matrix(sz, sz)
            c = psi4.core.Matrix(sz, sz)

            tp4 = time.time()
            for n in range(nruns):
                c.gemm(False, False, 1.0, a, b, 0.0)

            retp4 = (time.time() - tp4) / nruns

            tnp = time.time()
            for n in range(nruns):
                np.dot(a, b, out=np.asarray(c))

            retnp = (time.time() - tnp) / nruns
            print(
                "Time for threads %2d, size %5d: Psi4: %12.6f  NumPy: %12.6f" %
                (th, sz, retp4, retnp))
            if sz == 4000:
                times["p4-n{}".format(th)] = retp4
                times["np-n{}".format(th)] = retnp
                assert psi4.get_num_threads() == th

    rat1 = times["np-n" + str(threads[-1])] / times["p4-n" + str(threads[-1])]
    rat2 = times["p4-n" + str(threads[0])] / times["p4-n" + str(threads[-1])]
    print("  NumPy@n%d : Psi4@n%d ratio (want ~1): %.2f" %
          (threads[-1], threads[-1], rat1))
    print("   Psi4@n%d : Psi4@n%d ratio (want ~%d): %.2f" %
          (threads[0], threads[-1], threads[-1], rat2))
    if args.passfail:
        assert math.isclose(
            rat1, 1.0,
            rel_tol=0.2), 'PsiAPI:NumPy speedup {} !~= 1.0'.format(rat1)
        assert math.isclose(rat2, threads[-1],
                            rel_tol=0.4), 'PsiAPI speedup {} !~= {}'.format(
                                rat2, threads[-1])
Exemplo n.º 14
0
def energy_calc(params, current_geom, mol):
    energy = 0.0
    if (params.qm_program == 'pyscf'):
        pymol = gto.Mole()
        pymol.verbose = 0
        geom_vec = []
        for i in range(params.natoms):
            atom = [
                params.symbols[i],
            ]
            atom_coords = []
            for j in range(3):
                atom_coords.append(current_geom[i][j])
            atom_coords = tuple(atom_coords)
            atom.append(atom_coords)
            geom_vec.append(atom)
        #print(geom_vec)
        pymol.atom = geom_vec
        pymol.unit = 'Bohr'
        pymol.basis = params.basis
        pymol.charge = params.charge
        pymol.spin = params.mult - 1
        pymol.build()
        if (params.method == "scf"):
            scf_obj = scf.RHF(pymol)
        #if(params.method == "mp2"): #TODO Doesn't work yet. Few things left to figure out.
        #    scf_obj = scf.RHF(pymol).run()
        #    scf_obj = mp.MP2(scf_obj).run()
        #if(params.method == "dft"):
        #    scf_obj = dft.RKS(mol)
        #    scf_obj.xc = params.xc_functional
        if (params.do_solvent):
            solv_obj = solvent.ddCOSMO(scf_obj)
            solv_obj.with_solvent.eps = params.eps
            solv_obj.run()
            energy = solv_obj.kernel()
            print(energy)
        else:
            energy = scf_obj.scf()

    if (params.qm_program == 'psi4'):
        mol.set_geometry(psi4.core.Matrix.from_array(current_geom))
        grad_method = "%s/%s" % (params.method, params.basis)
        psi4.core.set_output_file("psi4_out.dat", False)
        psi4.set_options(params.keywords)
        psi4.set_num_threads(params.nthreads)
        energy = psi4.energy(grad_method)
    return energy
Exemplo n.º 15
0
def disabled_test_threaded_blas():
    threads = multiprocessing.cpu_count()
    threads = int(threads / 2)

    times = {}

    size = [200, 500, 2000, 5000]
    threads = [1, threads]

    for th in threads:
        psi4.set_num_threads(th)

        for sz in size:
            nruns = max(1, int(1.e10 / (sz**3)))

            a = psi4.core.Matrix(sz, sz)
            b = psi4.core.Matrix(sz, sz)
            c = psi4.core.Matrix(sz, sz)

            tp4 = time.time()
            for n in range(nruns):
                c.gemm(False, False, 1.0, a, b, 0.0)

            retp4 = (time.time() - tp4) / nruns

            tnp = time.time()
            for n in range(nruns):
                np.dot(a, b, out=np.asarray(c))

            retnp = (time.time() - tnp) / nruns
            print(
                "Time for threads %2d, size %5d: Psi4: %12.6f  NumPy: %12.6f" %
                (th, sz, retp4, retnp))
            if sz == 5000:
                times["p4-n{}".format(th)] = retp4
                times["np-n{}".format(th)] = retnp
                assert psi4.get_num_threads() == th

    rat1 = times["np-n" + str(threads[-1])] / times["p4-n" + str(threads[-1])]
    rat2 = times["p4-n" + str(threads[0])] / times["p4-n" + str(threads[-1])]
    print("  NumPy@n%d : Psi4@n%d ratio (want ~1): %.2f" %
          (threads[-1], threads[-1], rat1))
    print("   Psi4@n%d : Psi4@n%d ratio (want ~%d): %.2f" %
          (threads[0], threads[-1], threads[-1], rat2))
    assert pytest.approx(rat1, 0.2) == 1.0
    assert pytest.approx(rat2, 0.8) == threads[-1]
Exemplo n.º 16
0
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()
Exemplo n.º 17
0
 def __init__(
     self,
     basis_set,
     functional,
     quadrature_spherical,
     quadrature_radial,
     qm_charge,
     qm_spin,
     scf_type="df",
     qmmm_pme=False,
     n_threads=1,
     read_guess=False,
     group_part_dict=None,
     element_symbols=None,
     charges=None,
     positions=None,
     box=None,
 ):
     System.__init__(self)
     self.basis_set = basis_set
     self.functional = functional
     self.quadrature_spherical = quadrature_spherical
     self.quadrature_radial = quadrature_radial
     self.qm_charge = qm_charge
     self.qm_spin = qm_spin
     self.scf_type = scf_type
     self.qmmm_pme = qmmm_pme
     psi4.set_num_threads(n_threads)
     options = {
         "basis": self.basis_set,
         "dft_spherical_points": self.quadrature_spherical,
         "dft_radial_points": self.quadrature_radial,
         "scf_type": self.scf_type,
         "qmmm": str(self.qmmm_pme).lower(),
     }
     psi4.set_options(options)
     self.read_guess = read_guess
     self.wfn = None
     self.group_part_dict = group_part_dict
     self.element_symbols = element_symbols
     self.charges = charges
     self.positions = positions
     if box:
         self.box = box
Exemplo n.º 18
0
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")
Exemplo n.º 19
0
def disabled_test_threaded_blas():
    threads = multiprocessing.cpu_count()
    threads = int(threads / 2)

    times = {}

    size = [200, 500, 2000, 5000]
    threads = [1, threads]

    for th in threads:
        psi4.set_num_threads(th)

        for sz in size:
            nruns = max(1, int(1.e10 / (sz ** 3)))

            a = psi4.core.Matrix(sz, sz)
            b = psi4.core.Matrix(sz, sz)
            c = psi4.core.Matrix(sz, sz)

            tp4 = time.time()
            for n in range(nruns):
                c.gemm(False, False, 1.0, a, b, 0.0)

            retp4 = (time.time() - tp4) / nruns

            tnp = time.time()
            for n in range(nruns):
                np.dot(a, b, out=np.asarray(c))

            retnp = (time.time() - tnp) / nruns
            print("Time for threads %2d, size %5d: Psi4: %12.6f  NumPy: %12.6f" % (th, sz, retp4, retnp))
            if sz == 5000:
                times["p4-n{}".format(th)] = retp4
                times["np-n{}".format(th)] = retnp
                assert psi4.get_num_threads() == th

    rat1 = times["np-n" + str(threads[-1])] / times["p4-n" + str(threads[-1])]
    rat2 = times["p4-n" + str(threads[0])] / times["p4-n" + str(threads[-1])]
    print("  NumPy@n%d : Psi4@n%d ratio (want ~1): %.2f" % (threads[-1], threads[-1], rat1))
    print("   Psi4@n%d : Psi4@n%d ratio (want ~%d): %.2f" % (threads[0], threads[-1], threads[-1], rat2))
    assert pytest.approx(rat1, 0.2) == 1.0
    assert pytest.approx(rat2, 0.8) == threads[-1]
Exemplo n.º 20
0
def test_threaded_blas(args):
    threads = int(args.nthread)

    times = {}

    size = [200, 500, 2000, 4000]
    threads = [1, threads]

    for th in threads:
        psi4.set_num_threads(th)

        for sz in size:
            nruns = max(1, int(1.e10 / (sz ** 3)))

            a = psi4.core.Matrix(sz, sz)
            b = psi4.core.Matrix(sz, sz)
            c = psi4.core.Matrix(sz, sz)

            tp4 = time.time()
            for n in range(nruns):
                c.gemm(False, False, 1.0, a, b, 0.0)

            retp4 = (time.time() - tp4) / nruns

            tnp = time.time()
            for n in range(nruns):
                np.dot(a, b, out=np.asarray(c))

            retnp = (time.time() - tnp) / nruns
            print("Time for threads %2d, size %5d: Psi4: %12.6f  NumPy: %12.6f" % (th, sz, retp4, retnp))
            if sz == 4000:
                times["p4-n{}".format(th)] = retp4
                times["np-n{}".format(th)] = retnp
                assert psi4.get_num_threads() == th

    rat1 = times["np-n" + str(threads[-1])] / times["p4-n" + str(threads[-1])]
    rat2 = times["p4-n" + str(threads[0])] / times["p4-n" + str(threads[-1])]
    print("  NumPy@n%d : Psi4@n%d ratio (want ~1): %.2f" % (threads[-1], threads[-1], rat1))
    print("   Psi4@n%d : Psi4@n%d ratio (want ~%d): %.2f" % (threads[0], threads[-1], threads[-1], rat2))
    if args.passfail:
        assert math.isclose(rat1, 1.0, rel_tol=0.2), 'PsiAPI:NumPy speedup {} !~= 1.0'.format(rat1)
        assert math.isclose(rat2, threads[-1], rel_tol=0.4), 'PsiAPI speedup {} !~= {}'.format(rat2, threads[-1])
Exemplo n.º 21
0
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
Exemplo n.º 22
0
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
Exemplo n.º 23
0
def compute_hessian(params, geom):
    # Use PSI4 to calculate Hessian matrix
    if (params.qm_program == "psi4"):
        psi4.core.set_output_file("hessian.out", False)
        mol = psi4.geometry(geom)
        psi4.set_options(params.keywords)
        psi4.set_num_threads(params.nthreads)
        H = psi4.hessian("%s/%s" % (params.method, params.basis))
        Hess = np.array(H)
    if (params.qm_program == "sparrow"):
        sparrow_struct = open("sparrow_inp.xyz", "w+")
        sparrow_struct.write("%d\n" % params.natoms)
        sparrow_struct.write("Sparrow Structure Generated by PYREX\n")
        sparrow_geom = geom[5:]
        sparrow_struct.write(sparrow_geom)
        sparrow_struct.close()
        sparrow_interface.run_sparrow(
            "sparrow_inp.xyz", params.molecular_charge,
            params.molecular_multiplicity, params.method, "output.dat",
            "--hessian --suppress_normal_modes --output_to_file")
        Hess = sparrow_interface.sparrow_hessian(params.natoms, "hessian.dat")
    return Hess
Exemplo n.º 24
0
import pandas as pd
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)
Exemplo n.º 25
0
def run_json_qc_schema(json_data, clean):
    """
    An implementation of the QC JSON Schema (molssi-qc-schema.readthedocs.io/en/latest/index.html#) implementation in Psi4.


    Parameters
    ----------
    json_data : JSON
        Please see molssi-qc-schema.readthedocs.io/en/latest/spec_components.html for further details.

    Notes
    -----
    !Warning! This function is experimental and likely to change in the future.
    Please report any suggestions or uses of this function on github.com/MolSSI/QC_JSON_Schema.

    Examples
    --------

    """

    # Clean a few things
    _clean_psi_environ(clean)

    # This is currently a forced override
    if json_data["schema_name"] != "qc_schema_input":
        raise KeyError("Schema name of '{}' not understood".format(json_data["schema_name"]))

    if json_data["schema_version"] != 1:
        raise KeyError("Schema version of '{}' not understood".format(json_data["schema_version"]))

    if json_data.get("nthreads", False) is not False:
        psi4.set_num_threads(json_data["nthreads"], quiet=True)

    json_data["provenance"] = {"creator": "Psi4", "version": psi4.__version__, "routine": "psi4.json.run_json"}

    # Build molecule
    mol = core.Molecule.from_schema(json_data)

    # Update molecule geometry as we orient and fix_com
    json_data["molecule"]["geometry"] = mol.geometry().np.ravel().tolist()


    # Set options
    for k, v in json_data["keywords"].items():
        core.set_global_option(k, v)

    # Setup the computation
    method = json_data["model"]["method"]
    core.set_global_option("BASIS", json_data["model"]["basis"])
    kwargs = {"return_wfn": True, "molecule": mol}

    # Handle special properties case
    if json_data["driver"] == "properties":
        if "properties" in json_data["model"]:
            kwargs["properties"] = [x.lower() for x in json_data["model"]["properties"]]

            extra = set(kwargs["properties"]) - can_do_properties_
            if len(extra):
                raise KeyError("Did not understand property key %s." % kwargs["properties"])
        else:
            kwargs["properties"] = list(can_do_properties_)


    # Actual driver run
    val, wfn = methods_dict_[json_data["driver"]](method, **kwargs)

    # Pull out a standard set of SCF properties
    psi_props = psi4.core.get_variables()
    json_data["psi4:qcvars"] = psi_props

    # Handle the return result
    if json_data["driver"] == "energy":
        json_data["return_result"] = val
    elif json_data["driver"] in ["gradient", "hessian"]:
        json_data["return_result"] = val.np.ravel().tolist()
    elif json_data["driver"] == "properties":
        ret = {}
        mtd = json_data["model"]["method"].upper()
        if "dipole" in kwargs["properties"]:
            ret["dipole"] = [psi_props[mtd + " DIPOLE " + x] for x in ["X", "Y", "Z"]]
        if "quadrupole" in kwargs["properties"]:
            ret["quadrupole"] = [psi_props[mtd + " QUADRUPOLE " + x] for x in ["XX", "XY", "XZ", "YY", "YZ", "ZZ"]]
        if "mulliken_charges" in kwargs["properties"]:
            ret["mulliken_charges"] = wfn.get_array("MULLIKEN_CHARGES").np.ravel().tolist()
        if "lowdin_charges" in kwargs["properties"]:
            ret["lowdin_charges"] = wfn.get_array("LOWDIN_CHARGES").np.ravel().tolist()
        if "wiberg_lowdin_indices" in kwargs["properties"]:
            ret["wiberg_lowdin_indices"] = wfn.get_array("WIBERG_LOWDIN_INDICES").np.ravel().tolist()
        if "mayer_indices" in kwargs["properties"]:
            ret["mayer_indices"] = wfn.get_array("MAYER_INDICES").np.ravel().tolist()

        json_data["return_result"] = ret
    else:
        raise KeyError("Did not understand Driver key %s." % json_data["driver"])


    props = {
        "calcinfo_nbasis": wfn.nso(),
        "calcinfo_nmo": wfn.nmo(),
        "calcinfo_nalpha": wfn.nalpha(),
        "calcinfo_nbeta": wfn.nbeta(),
        "calcinfo_natom": mol.geometry().shape[0],
        "scf_one_electron_energy": psi_props["ONE-ELECTRON ENERGY"],
        "scf_two_electron_energy": psi_props["TWO-ELECTRON ENERGY"],
        "nuclear_repulsion_energy": psi_props["NUCLEAR REPULSION ENERGY"],
        "scf_dipole_moment": [psi_props[x] for x in ["SCF DIPOLE X", "SCF DIPOLE Y", "SCF DIPOLE Z"]],
        "scf_iterations": int(psi_props["SCF ITERATIONS"]),
        "scf_total_energy": psi_props["SCF TOTAL ENERGY"],
        "return_energy": psi_props["CURRENT ENERGY"],
    }

    # Pull out optional SCF keywords
    other_scf = [("DFT VV10 ENERGY", "scf_vv10_energy"), ("DFT XC ENERGY", "scf_xc_energy"),
                 ("DISPERSION CORRECTION ENERGY", "scf_dispersion_correction_energy")]
    for pkey, skey in other_scf:
        if (pkey in psi_props) and (psi_props[pkey] != 0):
            props[skey] = psi_props[pkey]

    # Write out MP2 keywords
    if "MP2 CORRELATION ENERGY" in psi_props:
        props["mp2_same_spin_correlation_energy"] = psi_props["MP2 SAME-SPIN CORRELATION ENERGY"]
        props["mp2_opposite_spin_correlation_energy"] = psi_props["MP2 OPPOSITE-SPIN CORRELATION ENERGY"]
        props["mp2_singles_energy"] = 0.0
        props["mp2_doubles_energy"] = psi_props["MP2 CORRELATION ENERGY"]
        props["mp2_total_correlation_energy"] = psi_props["MP2 CORRELATION ENERGY"]
        props["mp2_total_energy"] = psi_props["MP2 TOTAL ENERGY"]

    json_data["properties"] = props
    json_data["success"] = True

    # Reset state
    _clean_psi_environ(clean)

    json_data["schema_name"] = "qc_schema_output"

    return json_data
import psi4
import numpy as np

# Initial setup
psi4.set_memory('2 GB')
psi4.set_num_threads(2)

file_prefix = 'methane_HF-DZ'

ch4 = psi4.geometry("""
symmetry c1
0 1
   C       -0.85972        2.41258        0.00000
   H        0.21028        2.41258        0.00000
   H       -1.21638        2.69390       -0.96879
   H       -1.21639        3.11091        0.72802
   H       -1.21639        1.43293        0.24076
""")


# Geometry optimization
psi4.set_output_file(file_prefix + '_geomopt.dat', False)
psi4.set_options({'g_convergence': 'gau_tight'})
psi4.optimize('scf/cc-pVDZ', molecule=ch4)


# 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
Exemplo n.º 27
0
def run_json_qcschema(json_data, clean):
    """
    An implementation of the QC JSON Schema (molssi-qc-schema.readthedocs.io/en/latest/index.html#) implementation in Psi4.


    Parameters
    ----------
    json_data : JSON
        Please see molssi-qc-schema.readthedocs.io/en/latest/spec_components.html for further details.

    Notes
    -----
    !Warning! This function is experimental and likely to change in the future.
    Please report any suggestions or uses of this function on github.com/MolSSI/QC_JSON_Schema.

    Examples
    --------

    """

    # Clean a few things
    _clean_psi_environ(clean)

    # This is currently a forced override
    if json_data["schema_name"] in ["qc_schema_input", "qcschema_input"]:
        json_data["schema_name"] = "qcschema_input"
    else:
        raise KeyError("Schema name of '{}' not understood".format(json_data["schema_name"]))

    if json_data["schema_version"] != 1:
        raise KeyError("Schema version of '{}' not understood".format(json_data["schema_version"]))

    if json_data.get("nthreads", False) is not False:
        psi4.set_num_threads(json_data["nthreads"], quiet=True)

    json_data["provenance"] = {"creator": "Psi4", "version": psi4.__version__, "routine": "psi4.json.run_json"}

    # Build molecule
    if "schema_name" in json_data["molecule"]:
        molschemus = json_data["molecule"]  # dtype >=2
    else:
        molschemus = json_data  # dtype =1
    mol = core.Molecule.from_schema(molschemus)

    # Update molecule geometry as we orient and fix_com
    json_data["molecule"]["geometry"] = mol.geometry().np.ravel().tolist()

    # Set options
    kwargs = json_data["keywords"].pop("function_kwargs", {})
    psi4.set_options(json_data["keywords"])

    # Setup the computation
    method = json_data["model"]["method"]
    core.set_global_option("BASIS", json_data["model"]["basis"])
    kwargs.update({"return_wfn": True, "molecule": mol})

    # Handle special properties case
    if json_data["driver"] == "properties":
        if "properties" in json_data["model"]:
            kwargs["properties"] = [x.lower() for x in json_data["model"]["properties"]]

            extra = set(kwargs["properties"]) - can_do_properties_
            if len(extra):
                raise KeyError("Did not understand property key %s." % kwargs["properties"])
        else:
            kwargs["properties"] = list(can_do_properties_)

    # Actual driver run
    val, wfn = methods_dict_[json_data["driver"]](method, **kwargs)

    # Pull out a standard set of SCF properties
    if "extras" not in json_data:
        json_data["extras"] = {}
    json_data["extras"]["qcvars"] = {}

    if json_data["extras"].get("wfn_qcvars_only", False):
        psi_props = wfn.variables()
    else:
        psi_props = psi4.core.variables()
        for k, v in psi_props.items():
            if k not in json_data["extras"]["qcvars"]:
                json_data["extras"]["qcvars"][k] = _json_translation(v)

    # Still a bit of a mess at the moment add in local vars as well.
    for k, v in wfn.variables().items():
        if k not in json_data["extras"]["qcvars"]:
            json_data["extras"]["qcvars"][k] = _json_translation(v)

    # Handle the return result
    if json_data["driver"] == "energy":
        json_data["return_result"] = val
    elif json_data["driver"] in ["gradient", "hessian"]:
        json_data["return_result"] = val.np.ravel().tolist()
    elif json_data["driver"] == "properties":
        ret = {}
        mtd = json_data["model"]["method"].upper()

        # Dipole/quadrupole still special case
        if "dipole" in kwargs["properties"]:
            ret["dipole"] = [psi_props[mtd + " DIPOLE " + x] for x in ["X", "Y", "Z"]]
        if "quadrupole" in kwargs["properties"]:
            ret["quadrupole"] = [psi_props[mtd + " QUADRUPOLE " + x] for x in ["XX", "XY", "XZ", "YY", "YZ", "ZZ"]]
        ret.update(_convert_variables(wfn.variables(), context="properties"))

        json_data["return_result"] = ret
    else:
        raise KeyError("Did not understand Driver key %s." % json_data["driver"])

    props = {
        "calcinfo_nbasis": wfn.nso(),
        "calcinfo_nmo": wfn.nmo(),
        "calcinfo_nalpha": wfn.nalpha(),
        "calcinfo_nbeta": wfn.nbeta(),
        "calcinfo_natom": mol.geometry().shape[0],
    }
    props.update(_convert_variables(psi_props, context="generics"))
    if not list(set(['CBS NUMBER', 'NBODY NUMBER', 'FINDIF NUMBER']) & set(json_data["extras"]["qcvars"].keys())):
        props.update(_convert_variables(psi_props, context="scf"))

    # Write out MP2 keywords
    if "MP2 CORRELATION ENERGY" in psi_props:
        props.update(_convert_variables(psi_props, context="mp2"))

    json_data["properties"] = props
    json_data["success"] = True

    # Reset state
    _clean_psi_environ(clean)

    json_data["schema_name"] = "qcschema_output"

    return json_data
Exemplo n.º 28
0
"""
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')
Exemplo n.º 29
0
## vi: tabstop=4 shiftwidth=4 softtabstop=4 expandtab
import adcc
import psi4

mol = psi4.geometry("""
    0 3
    O 0 0 0
    H 0 0 1.795239827225189
    H 1.693194615993441 0 -0.599043184453037
    symmetry c1
    units au
    """)

# set the number of cores equal to the auto-determined value from
# the adcc ThreadPool
psi4.set_num_threads(adcc.get_n_threads())
psi4.core.be_quiet()
psi4.set_options({
    'basis': "sto-3g",
    'scf_type': 'pk',
    'e_convergence': 1e-12,
    'reference': 'uhf',
    'd_convergence': 1e-8
})
scf_e, wfn = psi4.energy('SCF', return_wfn=True)

# Run an adc2 calculation:
state = adcc.adc2(wfn, n_states=5)

print(state.describe())
Exemplo n.º 30
0
def run_json_qc_schema(json_data, clean):
    """
    An implementation of the QC JSON Schema (molssi-qc-schema.readthedocs.io/en/latest/index.html#) implementation in Psi4.


    Parameters
    ----------
    json_data : JSON
        Please see molssi-qc-schema.readthedocs.io/en/latest/spec_components.html for further details.

    Notes
    -----
    !Warning! This function is experimental and likely to change in the future.
    Please report any suggestions or uses of this function on github.com/MolSSI/QC_JSON_Schema.

    Examples
    --------

    """

    # Clean a few things
    _clean_psi_environ(clean)

    # This is currently a forced override
    if json_data["schema_name"] in ["qc_schema_input", "qcschema_input"]:
        json_data["schema_name"] = "qc_schema_input"  # humor qcel 0.1.3
    else:
        raise KeyError("Schema name of '{}' not understood".format(json_data["schema_name"]))

    if json_data["schema_version"] != 1:
        raise KeyError("Schema version of '{}' not understood".format(json_data["schema_version"]))

    if json_data.get("nthreads", False) is not False:
        psi4.set_num_threads(json_data["nthreads"], quiet=True)

    json_data["provenance"] = {"creator": "Psi4", "version": psi4.__version__, "routine": "psi4.json.run_json"}

    # Build molecule
    mol = core.Molecule.from_schema(json_data)

    # Update molecule geometry as we orient and fix_com
    json_data["molecule"]["geometry"] = mol.geometry().np.ravel().tolist()

    # Set options
    for k, v in json_data["keywords"].items():
        core.set_global_option(k, v)

    # Setup the computation
    method = json_data["model"]["method"]
    core.set_global_option("BASIS", json_data["model"]["basis"])
    kwargs = {"return_wfn": True, "molecule": mol}

    # Handle special properties case
    if json_data["driver"] == "properties":
        if "properties" in json_data["model"]:
            kwargs["properties"] = [x.lower() for x in json_data["model"]["properties"]]

            extra = set(kwargs["properties"]) - can_do_properties_
            if len(extra):
                raise KeyError("Did not understand property key %s." % kwargs["properties"])
        else:
            kwargs["properties"] = list(can_do_properties_)

    # Actual driver run
    val, wfn = methods_dict_[json_data["driver"]](method, **kwargs)

    # Pull out a standard set of Psi variables
    psi_props = psi4.core.scalar_variables()
    json_data["psi4:qcvars"] = psi_props

    # Still a bit of a mess at the moment add in local vars as well.
    for k, v in wfn.variables().items():
        if k not in json_data["psi4:qcvars"]:
            json_data["psi4:qcvars"][k] = _json_translation(v)

    # Handle the return result
    if json_data["driver"] == "energy":
        json_data["return_result"] = val
    elif json_data["driver"] in ["gradient", "hessian"]:
        json_data["return_result"] = val.np.ravel().tolist()
    elif json_data["driver"] == "properties":
        ret = {}
        mtd = json_data["model"]["method"].upper()

        # Dipole/quadrupole still special case
        if "dipole" in kwargs["properties"]:
            ret["dipole"] = [psi_props[mtd + " DIPOLE " + x] for x in ["X", "Y", "Z"]]
        if "quadrupole" in kwargs["properties"]:
            ret["quadrupole"] = [psi_props[mtd + " QUADRUPOLE " + x] for x in ["XX", "XY", "XZ", "YY", "YZ", "ZZ"]]
        ret.update(_convert_variables(wfn.variables(), context="properties"))

        json_data["return_result"] = ret
    else:
        raise KeyError("Did not understand Driver key %s." % json_data["driver"])

    props = {
        "calcinfo_nbasis": wfn.nso(),
        "calcinfo_nmo": wfn.nmo(),
        "calcinfo_nalpha": wfn.nalpha(),
        "calcinfo_nbeta": wfn.nbeta(),
        "calcinfo_natom": mol.geometry().shape[0],
    }
    props.update(_convert_variables(psi_props, context="generics"))
    props.update(_convert_variables(psi_props, context="scf"))

    # Write out MP2 keywords
    if "MP2 CORRELATION ENERGY" in psi_props:
        props.update(_convert_variables(psi_props, context="mp2"))

    json_data["properties"] = props
    json_data["success"] = True

    # Reset state
    _clean_psi_environ(clean)

    json_data["schema_name"] = "qcschema_output"

    return json_data
Exemplo n.º 31
0
def init(config, log_name):
    psi4.core.set_output_file(log_name + ".log", False)
    psi4.set_memory(config['psi4']['memory'])
    psi4.set_num_threads(int(config['psi4']['num_threads']))
Exemplo n.º 32
0
def compute_ptss_corrections(ccwfn, nroots):
    ptss = []
    for i in range(nroots):
        ccdmat = ccwfn.variable("CC ROOT {} DA".format(i + 1))
        scfdmat = ccwfn.Da()
        ccdmat.subtract(scfdmat)
        ccdmat.scale(2.0)
        en, op = ccwfn.pe_state.get_pe_contribution(ccdmat, elec_only=True)
        psi4.core.print_out("ptSS {} {:.5f}\n".format(i, en))
        ptss.append(en)
    return ptss


# Set memory
psi4.set_memory("120 GiB")
psi4.set_num_threads(30)
psi4.core.set_output_file("nr_631gd_3roots_water.dat")

mol = psi4.geometry(
    """
C    28.793000    32.803000    28.486000
C    29.488000    32.299000    27.320000
N    30.182000    31.015000    27.451000
C    31.237000    31.117000    28.480000
C    30.762000    30.766000    29.900000
C    29.634000    29.842000    27.026000
C    30.269000    28.672000    27.439000
C    29.682000    27.474000    27.145000
C    28.414000    27.350000    26.510000
C    27.792000    28.529000    26.085000
C    28.350000    29.740000    26.403000
Exemplo n.º 33
0
def grad_calc(params, current_geom, mol):
    """
        Uses Psi4/pySCF to calculate the energy gradient and returns the
        gradient and energy. Here any of the keywords the user provides in the
        .json input are used to set the options for the energy calculation.

        Parameters:
        ----------
            params(self) -- contains initialized shared parameters.
            current_geom(np array) -- Matrix of size natoms x 3 containing the geometry.
            mol(psi4.Molecule) -- Psi4 molecule object containing the current molecule.
        Returns:
        -------
            grad_mw(np array) -- Mass weighted gradient matrix of size natoms x 3.
            E(float) -- single-point energy from Psi4 calculation.
    """
    if (params.qm_program == 'pyscf'):
        pymol = gto.Mole()
        pymol.verbose = 0
        geom_vec = []
        for i in range(params.natoms):
            atom = [
                params.symbols[i],
            ]
            atom_coords = []
            for j in range(3):
                atom_coords.append(current_geom[i][j])
            atom_coords = tuple(atom_coords)
            atom.append(atom_coords)
            geom_vec.append(atom)
        #print(geom_vec)
        pymol.atom = geom_vec
        pymol.unit = 'Bohr'
        pymol.basis = params.basis
        pymol.charge = params.molecular_charge
        pymol.spin = params.molecular_multiplicity - 1
        pymol.build()
        #TODO: PySCF 1.6.2 changes the way solvent is called for gradients, change this here
        #      they also added support for ddPCM, YAY! Let's add it in!
        if (params.method == "scf"):
            scf_obj = scf.RHF(pymol)
        if (params.method == "dft"):
            scf_obj = dft.RKS(pymol)
            scf_obj.xc = params.xc_functional
        if (params.do_solvent):
            solv_obj = scf_obj.DDCOSMO()
            solv_obj.with_solvent.eps = params.eps
            lib.num_threads(params.nthreads)
            E = solv_obj.scf()
            grad = solv_obj.nuc_grad_method().kernel()
        else:
            lib.num_threads(params.nthreads)
            E = scf_obj.scf()
            grad = scf_obj.nuc_grad_method().kernel()
    if (params.qm_program == 'psi4'):
        mol.set_geometry(psi4.core.Matrix.from_array(current_geom))
        mol.fix_orientation(True)
        mol.fix_com(True)
        mol.reset_point_group('c1')
        grad_method = "%s/%s" % (params.method, params.basis)
        psi4.core.set_output_file("psi4_out.dat", False)
        psi4.set_options(params.keywords)
        psi4.set_num_threads(params.nthreads)
        E, wfn = psi4.energy(grad_method, return_wfn=True)
        psi4.set_num_threads(params.nthreads)
        grad = np.asarray(psi4.gradient(grad_method, ref_wfn=wfn))
        #print(grad)
    return grad
Exemplo n.º 34
0
def run_json_qc_schema(json_data, clean):
    """
    An implementation of the QC JSON Schema (molssi-qc-schema.readthedocs.io/en/latest/index.html#) implementation in Psi4.


    Parameters
    ----------
    json_data : JSON
        Please see molssi-qc-schema.readthedocs.io/en/latest/spec_components.html for further details.

    Notes
    -----
    !Warning! This function is experimental and likely to change in the future.
    Please report any suggestions or uses of this function on github.com/MolSSI/QC_JSON_Schema.

    Examples
    --------

    """

    # Clean a few things
    _clean_psi_environ(clean)

    # This is currently a forced override
    if json_data["schema_name"] != "qc_schema_input":
        raise KeyError("Schema name of '{}' not understood".format(json_data["schema_name"]))

    if json_data["schema_version"] != 1:
        raise KeyError("Schema version of '{}' not understood".format(json_data["schema_version"]))

    if json_data.get("nthreads", False) is not False:
        psi4.set_num_threads(json_data["nthreads"], quiet=True)

    json_data["provenance"] = {"creator": "Psi4", "version": psi4.__version__, "routine": "psi4.json.run_json"}

    # Build molecule
    mol = core.Molecule.from_schema(json_data)

    # Update molecule geometry as we orient and fix_com
    json_data["molecule"]["geometry"] = mol.geometry().np.ravel().tolist()


    # Set options
    for k, v in json_data["keywords"].items():
        core.set_global_option(k, v)

    # Setup the computation
    method = json_data["model"]["method"]
    core.set_global_option("BASIS", json_data["model"]["basis"])
    kwargs = {"return_wfn": True, "molecule": mol}

    # Handle special properties case
    if json_data["driver"] == "properties":
        if "properties" in json_data["model"]:
            kwargs["properties"] = [x.lower() for x in json_data["model"]["properties"]]

            extra = set(kwargs["properties"]) - can_do_properties_
            if len(extra):
                raise KeyError("Did not understand property key %s." % kwargs["properties"])
        else:
            kwargs["properties"] = list(can_do_properties_)


    # Actual driver run
    val, wfn = methods_dict_[json_data["driver"]](method, **kwargs)

    # Pull out a standard set of SCF properties
    psi_props = psi4.core.get_variables()
    json_data["psi4:qcvars"] = psi_props

    # Handle the return result
    if json_data["driver"] == "energy":
        json_data["return_result"] = val
    elif json_data["driver"] in ["gradient", "hessian"]:
        json_data["return_result"] = val.np.ravel().tolist()
    elif json_data["driver"] == "properties":
        ret = {}
        mtd = json_data["model"]["method"].upper()
        if "dipole" in kwargs["properties"]:
            ret["dipole"] = [psi_props[mtd + " DIPOLE " + x] for x in ["X", "Y", "Z"]]
        if "quadrupole" in kwargs["properties"]:
            ret["quadrupole"] = [psi_props[mtd + " QUADRUPOLE " + x] for x in ["XX", "XY", "XZ", "YY", "YZ", "ZZ"]]
        if "mulliken_charges" in kwargs["properties"]:
            ret["mulliken_charges"] = wfn.get_array("MULLIKEN_CHARGES").np.ravel().tolist()
        if "lowdin_charges" in kwargs["properties"]:
            ret["lowdin_charges"] = wfn.get_array("LOWDIN_CHARGES").np.ravel().tolist()
        if "wiberg_lowdin_indices" in kwargs["properties"]:
            ret["wiberg_lowdin_indices"] = wfn.get_array("WIBERG_LOWDIN_INDICES").np.ravel().tolist()
        if "mayer_indices" in kwargs["properties"]:
            ret["mayer_indices"] = wfn.get_array("MAYER_INDICES").np.ravel().tolist()

        json_data["return_result"] = ret
    else:
        raise KeyError("Did not understand Driver key %s." % json_data["driver"])


    props = {
        "calcinfo_nbasis": wfn.nso(),
        "calcinfo_nmo": wfn.nmo(),
        "calcinfo_nalpha": wfn.nalpha(),
        "calcinfo_nbeta": wfn.nbeta(),
        "calcinfo_natom": mol.geometry().shape[0],
        "scf_one_electron_energy": psi_props["ONE-ELECTRON ENERGY"],
        "scf_two_electron_energy": psi_props["TWO-ELECTRON ENERGY"],
        "nuclear_repulsion_energy": psi_props["NUCLEAR REPULSION ENERGY"],
        "scf_dipole_moment": [psi_props[x] for x in ["SCF DIPOLE X", "SCF DIPOLE Y", "SCF DIPOLE Z"]],
        "scf_iterations": int(psi_props["SCF ITERATIONS"]),
        "scf_total_energy": psi_props["SCF TOTAL ENERGY"],
        "return_energy": psi_props["CURRENT ENERGY"],
    }

    # Pull out optional SCF keywords
    other_scf = [("DFT VV10 ENERGY", "scf_vv10_energy"), ("DFT XC ENERGY", "scf_xc_energy"),
                 ("DISPERSION CORRECTION ENERGY", "scf_dispersion_correction_energy")]
    for pkey, skey in other_scf:
        if (pkey in psi_props) and (psi_props[pkey] != 0):
            props[skey] = psi_props[pkey]

    # Write out MP2 keywords
    if "MP2 CORRELATION ENERGY" in psi_props:
        props["mp2_same_spin_correlation_energy"] = psi_props["MP2 SAME-SPIN CORRELATION ENERGY"]
        props["mp2_opposite_spin_correlation_energy"] = psi_props["MP2 OPPOSITE-SPIN CORRELATION ENERGY"]
        props["mp2_singles_energy"] = 0.0
        props["mp2_doubles_energy"] = psi_props["MP2 CORRELATION ENERGY"]
        props["mp2_total_correlation_energy"] = psi_props["MP2 CORRELATION ENERGY"]
        props["mp2_total_energy"] = psi_props["MP2 TOTAL ENERGY"]

    json_data["properties"] = props
    json_data["success"] = True

    # Reset state
    _clean_psi_environ(clean)

    json_data["schema_name"] = "qc_schema_output"

    return json_data
Exemplo n.º 35
0
#!/usr/bin/env python3
## vi: tabstop=4 shiftwidth=4 softtabstop=4 expandtab
import adcc
import psi4

# Run SCF in psi4
mol = psi4.geometry("""
    0 3
    H 0 0 0
    F 0 0 2.5
    symmetry c1
    units au
    no_reorient
    no_com
    """)

psi4.set_num_threads(adcc.thread_pool.n_cores)
psi4.core.be_quiet()
psi4.set_options({
    'basis': "6-31g",
    'e_convergence': 1e-14,
    'd_convergence': 1e-9,
    'reference': 'uhf'
})
scf_e, wfn = psi4.energy('SCF', return_wfn=True)

# Run solver and print results
states = adcc.adc2(wfn, n_spin_flip=5, conv_tol=1e-8)
print(states.describe())
print(states.describe_amplitudes())
Exemplo n.º 36
0
#! compare MemJK and DiskJK

import psi4
import numpy as np
import random

mol = psi4.geometry("""
O
H 1 1.00
H 1 1.00 2 103.1
""")

psi4.set_num_threads(6)
memory = 50000
primary = psi4.core.BasisSet.build(mol, "ORBITAL", "cc-pVDZ")
aux = psi4.core.BasisSet.build(mol, "ORBITAL", "cc-pVDZ-jkfit")

nbf = primary.nbf()
naux = aux.nbf()

# construct spaces
names = ['C1', 'C2', 'C3', 'C4', 'C5']
sizes = [16, 16, 20, 20, 30]
spaces = {names[ind]: psi4.core.Matrix.from_array(np.random.rand(nbf, size)) for ind, size in enumerate(sizes)}
space_pairs = [[0, 0], [0, 1], [1, 1], [2, 2], [3, 2], [3, 3], [4, 4]]

# space vectors
C_vectors  = [[spaces[names[left]], spaces[names[right]]] for left, right in space_pairs]

# now construct DiskJK and symm_JK objects