def restore(self): psi4.set_global_option(self.option, self.value_global) if not self.haschanged_global: psi4.revoke_global_option_changed(self.option) if self.module: psi4.set_local_option(self.module, self.option, self.value_local) if not self.haschanged_local: psi4.revoke_local_option_changed(self.module, self.option)
def run_dfdcft_gradient(name, **kwargs): """Function encoding sequence of PSI module calls for DCFT gradient calculation. """ optstash = p4util.OptionsState( ['GLOBALS', 'DERTYPE']) psi4.set_global_option('DERTYPE', 'FIRST') run_dfdcft(name, **kwargs) psi4.deriv() optstash.restore()
def run_dpd_unit_test(name, **kwargs): r"""Function encoding sequence of PSI module and plugin calls so that dpd_unit_test can be called via :py:func:`~driver.energy`. For post-scf plugins. >>> energy('dpd_unit_test') """ lowername = name.lower() kwargs = p4util.kwargs_lower(kwargs) # Your plugin's psi4 run sequence goes here psi4.set_global_option('BASIS', 'sto-3g') psi4.set_local_option('DPD_UNIT_TEST', 'PRINT', 1) scf_helper(name, **kwargs) returnvalue = psi4.plugin('dpd_unit_test.so') psi4.set_variable('CURRENT ENERGY', returnvalue)
def run_integral_trans(name, **kwargs): r"""Function encoding sequence of PSI module and plugin calls so that integral_trans can be called via :py:func:`~driver.energy`. For post-scf plugins. >>> energy('integral_trans') """ lowername = name.lower() kwargs = p4util.kwargs_lower(kwargs) # Your plugin's psi4 run sequence goes here psi4.set_global_option('BASIS', 'sto-3g') psi4.set_local_option('INTEGRAL_TRANS', 'PRINT', 1) scf_helper(name, **kwargs) returnvalue = psi4.plugin('integral_trans.so') psi4.set_variable('CURRENT ENERGY', returnvalue)
def run_myplugin1(name, **kwargs): r"""Function encoding sequence of PSI module and plugin calls so that myplugin1 can be called via :py:func:`~driver.energy`. >>> energy('myplugin1') """ lowername = name.lower() kwargs = p4util.kwargs_lower(kwargs) # Your plugin's psi4 run sequence goes here psi4.set_global_option('BASIS', 'sto-3g') psi4.set_local_option('MYPLUGIN1', 'PRINT', 1) energy('scf', **kwargs) returnvalue = psi4.plugin('myplugin1.so') return returnvalue
def run_fvno(name, **kwargs): r"""Function encoding sequence of PSI module and plugin calls so that fvno can be called via :py:func:`~driver.energy`. For post-scf plugins. >>> energy('fvno') """ lowername = name.lower() kwargs = p4util.kwargs_lower(kwargs) # Your plugin's psi4 run sequence goes here if ('wfn' in kwargs): if (kwargs['wfn'] == 'ccsd'): psi4.set_global_option('WFN', 'CCSD') elif (kwargs['wfn'] == 'ccsd(t)'): psi4.set_global_option('WFN', 'CCSD_T') scf_helper(name, **kwargs) psi4.transqt2() returnvalue = psi4.plugin('fvno.so')
def run_ccambit(name, **kwargs): r"""Function encoding sequence of PSI module and plugin calls so that ccambit can be called via :py:func:`~driver.energy`. For post-scf plugins. >>> energy('ccambit') """ lowername = name.lower() kwargs = p4util.kwargs_lower(kwargs) # Your plugin's psi4 run sequence goes here if ('wfn' in kwargs): if (kwargs['wfn'] == 'ccsd'): psi4.set_global_option('WFN', 'CCSD') elif (kwargs['wfn'] == 'ccsd(t)'): psi4.set_global_option('WFN', 'CCSD_T') scf_wfn = kwargs.get('ref_wfn', None) if scf_wfn is None: scf_wfn = driver.scf_helper(name, **kwargs) check_iwl_file_from_scf_type(psi4.get_option('SCF', 'SCF_TYPE'), scf_wfn) return psi4.plugin('ccambit.so', scf_wfn)
def ip_fitting(molecule, omega_l, omega_r, **kwargs): kwargs = p4util.kwargs_lower(kwargs) # By default, zero the omega to 3 digits omega_tol = kwargs.get('omega_tolerance', 1.0E-3) # By default, do up to twenty iterations maxiter = kwargs.get('maxiter', 20) # By default, do not read previous 180 orbitals file read = False read180 = '' if 'read' in kwargs: read = True read180 = kwargs['read'] # The molecule is required, and should be the neutral species molecule.update_geometry() charge0 = molecule.molecular_charge() mult0 = molecule.multiplicity() # How many electrons are there? N = 0 for A in range(molecule.natom()): N += molecule.Z(A) N -= charge0 N = int(N) Nb = int((N - mult0 + 1) / 2) Na = int(N - Nb) # Work in the ot namespace for this procedure psi4.IO.set_default_namespace("ot") # Burn in to determine orbital eigenvalues if read: psi4.set_global_option("GUESS", "READ") copy_file_to_scratch(read180, 'psi', 'ot', 180) old_guess = psi4.get_global_option("GUESS") psi4.set_global_option("DF_INTS_IO", "SAVE") psi4.print_out("""\n\t==> IP Fitting SCF: Burn-in <==\n""") E, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) psi4.set_global_option("DF_INTS_IO", "LOAD") # Determine H**O, to determine mult1 eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() if Na == Nb: H**O = -Nb elif Nb == 0: H**O = Na else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: H**O = Na else: H**O = -Nb Na1 = Na; Nb1 = Nb; if H**O > 0: Na1 = Na1 - 1; else: Nb1 = Nb1 - 1; charge1 = charge0 + 1; mult1 = Na1 - Nb1 + 1 omegas = [] E0s = [] E1s = [] kIPs = [] IPs = [] types = [] # Right endpoint psi4.set_global_option('DFT_OMEGA', omega_r) # Neutral if read: psi4.set_global_option("GUESS", "READ") p4util.copy_file_to_scratch(read180, 'psi', 'ot', 180) molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) psi4.print_out("""\n\t==> IP Fitting SCF: Neutral, Right Endpoint <==\n""") E0r, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() E_HOMO = 0.0; if Nb == 0: E_HOMO = eps_a[int(Na - 1)] else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: E_HOMO = E_a else: E_HOMO = E_b E_HOMOr = E_HOMO psi4.IO.change_file_namespace(180, "ot", "neutral") # Cation if read: psi4.set_global_option("GUESS", "READ") p4util.copy_file_to_scratch(read180, 'psi', 'ot', 180) molecule.set_molecular_charge(charge1) molecule.set_multiplicity(mult1) psi4.print_out("""\n\t==> IP Fitting SCF: Cation, Right Endpoint <==\n""") E1r = energy('scf', molecule=molecule, **kwargs) psi4.IO.change_file_namespace(180, "ot", "cation") IPr = E1r - E0r; kIPr = -E_HOMOr; delta_r = IPr - kIPr; if IPr > kIPr: message = ("""\n***IP Fitting Error: Right Omega limit should have kIP > IP""") raise ValidationError(message) omegas.append(omega_r) types.append('Right Limit') E0s.append(E0r) E1s.append(E1r) IPs.append(IPr) kIPs.append(kIPr) # Use previous orbitals from here out psi4.set_global_option("GUESS", "READ") # Left endpoint psi4.set_global_option('DFT_OMEGA', omega_l) # Neutral psi4.IO.change_file_namespace(180, "neutral", "ot") molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) psi4.print_out("""\n\t==> IP Fitting SCF: Neutral, Left Endpoint <==\n""") E0l, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() E_HOMO = 0.0 if Nb == 0: E_HOMO = eps_a[int(Na - 1)] else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: E_HOMO = E_a else: E_HOMO = E_b E_HOMOl = E_HOMO psi4.IO.change_file_namespace(180, "ot", "neutral") # Cation psi4.IO.change_file_namespace(180, "cation", "ot") molecule.set_molecular_charge(charge1) molecule.set_multiplicity(mult1) psi4.print_out("""\n\t==> IP Fitting SCF: Cation, Left Endpoint <==\n""") E1l = energy('scf', molecule=molecule, **kwargs) psi4.IO.change_file_namespace(180, "ot", "cation") IPl = E1l - E0l kIPl = -E_HOMOl delta_l = IPl - kIPl if IPl < kIPl: message = ("""\n***IP Fitting Error: Left Omega limit should have kIP < IP""") raise ValidationError(message) omegas.append(omega_l) types.append('Left Limit') E0s.append(E0l) E1s.append(E1l) IPs.append(IPl) kIPs.append(kIPl) converged = False repeat_l = 0 repeat_r = 0 step = 0 while True: step = step + 1 # Regula Falsi (modified) if repeat_l > 1: delta_l = delta_l / 2.0 if repeat_r > 1: delta_r = delta_r / 2.0 omega = - (omega_r - omega_l) / (delta_r - delta_l) * delta_l + omega_l psi4.set_global_option('DFT_OMEGA', omega) # Neutral psi4.IO.change_file_namespace(180, "neutral", "ot") molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) psi4.print_out("""\n\t==> IP Fitting SCF: Neutral, Omega = %11.3E <==\n""" % omega) E0, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() E_HOMO = 0.0 if Nb == 0: E_HOMO = eps_a[int(Na - 1)] else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: E_HOMO = E_a else: E_HOMO = E_b psi4.IO.change_file_namespace(180, "ot", "neutral") # Cation psi4.IO.change_file_namespace(180, "cation", "ot") molecule.set_molecular_charge(charge1) molecule.set_multiplicity(mult1) psi4.print_out("""\n\t==> IP Fitting SCF: Cation, Omega = %11.3E <==\n""" % omega) E1 = energy('scf', molecule=molecule, **kwargs) psi4.IO.change_file_namespace(180, "ot", "cation") IP = E1 - E0 kIP = -E_HOMO delta = IP - kIP if kIP > IP: omega_r = omega E0r = E0 E1r = E1 IPr = IP kIPr = kIP delta_r = delta repeat_r = 0 repeat_l = repeat_l + 1 else: omega_l = omega E0l = E0 E1l = E1 IPl = IP kIPl = kIP delta_l = delta repeat_l = 0; repeat_r = repeat_r + 1 omegas.append(omega) types.append('Regula-Falsi') E0s.append(E0) E1s.append(E1) IPs.append(IP) kIPs.append(kIP) # Termination if (abs(omega_l - omega_r) < omega_tol or step > maxiter): converged = True break # Properly, should clone molecule but since not returned and easy to unblemish, molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) psi4.IO.set_default_namespace("") psi4.print_out("""\n\t==> IP Fitting Results <==\n\n""") psi4.print_out("""\t => Occupation Determination <= \n\n""") psi4.print_out("""\t %6s %6s %6s %6s %6s %6s\n""" % ('N', 'Na', 'Nb', 'Charge', 'Mult', 'H**O')) psi4.print_out("""\t Neutral: %6d %6d %6d %6d %6d %6d\n""" % (N, Na, Nb, charge0, mult0, H**O)) psi4.print_out("""\t Cation: %6d %6d %6d %6d %6d\n\n""" % (N - 1, Na1, Nb1, charge1, mult1)) psi4.print_out("""\t => Regula Falsi Iterations <=\n\n""") psi4.print_out("""\t%3s %11s %14s %14s %14s %s\n""" % ('N','Omega','IP','kIP','Delta','Type')) for k in range(len(omegas)): psi4.print_out("""\t%3d %11.3E %14.6E %14.6E %14.6E %s\n""" % (k + 1, omegas[k], IPs[k], kIPs[k], IPs[k] - kIPs[k], types[k])) if converged: psi4.print_out("""\n\tIP Fitting Converged\n""") psi4.print_out("""\tFinal omega = %14.6E\n""" % ((omega_l + omega_r) / 2)) psi4.print_out("""\n\t"M,I. does the dying. Fleet just does the flying."\n""") psi4.print_out("""\t\t\t-Starship Troopers\n""") else: psi4.print_out("""\n\tIP Fitting did not converge!\n""") psi4.set_global_option("DF_INTS_IO", "NONE") psi4.set_global_option("GUESS", old_guess)
def frac_traverse(molecule, **kwargs): kwargs = p4util.kwargs_lower(kwargs) # The molecule is required, and should be the neutral species molecule.update_geometry() charge0 = molecule.molecular_charge() mult0 = molecule.multiplicity() chargep = charge0 + 1 chargem = charge0 - 1 # By default, the multiplicity of the cation/anion are mult0 + 1 # These are overridden with the cation_mult and anion_mult kwargs multp = kwargs.get('cation_mult', mult0 + 1) multm = kwargs.get('anion_mult', mult0 + 1) # By default, we start the frac procedure on the 25th iteration # when not reading a previous guess frac_start = kwargs.get('frac_start', 25) # By default, we occupy by tenths of electrons HOMO_occs = kwargs.get('HOMO_occs', [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0]) LUMO_occs = kwargs.get('LUMO_occs', [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0]) # By default, H**O and LUMO are both in alpha Z = 0; for A in range(molecule.natom()): Z += molecule.Z(A) Z -= charge0 H**O = kwargs.get('H**O', (Z / 2 + 1 if (Z % 2) else Z / 2)) LUMO = kwargs.get('LUMO', H**O + 1) # By default, DIIS in FRAC (1.0 occupation is always DIIS'd) frac_diis = kwargs.get('frac_diis', True) # By default, use the neutral orbitals as a guess for the anion neutral_guess = kwargs.get('neutral_guess', True) # By default, burn-in with UHF first, if UKS hf_guess = False if psi4.get_global_option('REFERENCE') == 'UKS': hf_guess = kwargs.get('hf_guess', True) # By default, re-guess at each N continuous_guess = kwargs.get('continuous_guess', False) # By default, drop the files to the molecule's name root = kwargs.get('filename', molecule.name()) traverse_filename = root + '.traverse.dat' # => Traverse <= # occs = [] energies = [] potentials = [] convs = [] # => Run the neutral for its orbitals, if requested <= # old_df_ints_io = psi4.get_global_option("DF_INTS_IO") psi4.set_global_option("DF_INTS_IO", "SAVE") old_guess = psi4.get_global_option("GUESS") if (neutral_guess): if (hf_guess): psi4.set_global_option("REFERENCE","UHF") energy('scf') psi4.set_global_option("GUESS", "READ") psi4.set_global_option("DF_INTS_IO", "LOAD") # => Run the anion first <= # molecule.set_molecular_charge(chargem) molecule.set_multiplicity(multm) # => Burn the anion in with hf, if requested <= # if hf_guess: psi4.set_global_option("REFERENCE","UHF") energy('scf', molecule=molecule, **kwargs) psi4.set_global_option("REFERENCE","UKS") psi4.set_global_option("GUESS", "READ") psi4.set_global_option("DF_INTS_IO", "SAVE") psi4.set_global_option("FRAC_START", frac_start) psi4.set_global_option("FRAC_RENORMALIZE", True) psi4.set_global_option("FRAC_LOAD", False) for occ in LUMO_occs: psi4.set_global_option("FRAC_OCC", [LUMO]) psi4.set_global_option("FRAC_VAL", [occ]) E, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) C = 1 if E == 0.0: E = psi4.get_variable('SCF ITERATION ENERGY') C = 0 if LUMO > 0: eps = wfn.epsilon_a() potentials.append(eps[int(LUMO) - 1]) else: eps = wfn.epsilon_b() potentials.append(eps[-int(LUMO) - 1]) occs.append(occ) energies.append(E) convs.append(C) psi4.set_global_option("FRAC_START", 2) psi4.set_global_option("FRAC_LOAD", True) psi4.set_global_option("GUESS", "READ") psi4.set_global_option("FRAC_DIIS", frac_diis) psi4.set_global_option("DF_INTS_IO", "LOAD") # => Run the neutral next <= # molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) # Burn the neutral in with hf, if requested <= # if not continuous_guess: psi4.set_global_option("GUESS", old_guess) if hf_guess: psi4.set_global_option("FRAC_START", 0) psi4.set_global_option("REFERENCE", "UHF") energy('scf', molecule=molecule, **kwargs) psi4.set_global_option("REFERENCE", "UKS") psi4.set_global_option("GUESS", "READ") psi4.set_global_option("FRAC_LOAD", False) psi4.set_global_option("FRAC_START", frac_start) psi4.set_global_option("FRAC_RENORMALIZE", True) for occ in HOMO_occs: psi4.set_global_option("FRAC_OCC", [H**O]) psi4.set_global_option("FRAC_VAL", [occ]) E, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) C = 1 if E == 0.0: E = psi4.get_variable('SCF ITERATION ENERGY') C = 0 if LUMO > 0: eps = wfn.epsilon_a() potentials.append(eps[int(H**O) - 1]) else: eps = wfn.epsilon_b() potentials.append(eps[-int(H**O) - 1]) occs.append(occ - 1.0) energies.append(E) convs.append(C) psi4.set_global_option("FRAC_START", 2) psi4.set_global_option("FRAC_LOAD", True) psi4.set_global_option("GUESS", "READ") psi4.set_global_option("FRAC_DIIS", frac_diis) psi4.set_global_option("DF_INTS_IO", "LOAD") psi4.set_global_option("DF_INTS_IO", old_df_ints_io) # => Print the results out <= # E = {} psi4.print_out("""\n ==> Fractional Occupation Traverse Results <==\n\n""") psi4.print_out("""\t%-11s %-24s %-24s %11s\n""" % ('N', 'Energy', 'H**O Energy', 'Converged')) for k in range(len(occs)): psi4.print_out("""\t%11.3E %24.16E %24.16E %11d\n""" % (occs[k], energies[k], potentials[k], convs[k])) E[occs[k]] = energies[k] psi4.print_out('\n\t"You trying to be a hero Watkins?"\n') psi4.print_out('\t"Just trying to kill some bugs sir!"\n') psi4.print_out('\t\t\t-Starship Troopers\n') # Drop the files out fh = open(traverse_filename, 'w') fh.write("""\t%-11s %-24s %-24s %11s\n""" % ('N', 'Energy', 'H**O Energy', 'Converged')) for k in range(len(occs)): fh.write("""\t%11.3E %24.16E %24.16E %11d\n""" % (occs[k], energies[k], potentials[k], convs[k])) fh.close() # Properly, should clone molecule but since not returned and easy to unblemish, molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) return E
def frac_nuke(molecule, **kwargs): kwargs = p4util.kwargs_lower(kwargs) # The molecule is required, and should be the neutral species molecule.update_geometry() charge0 = molecule.molecular_charge() mult0 = molecule.multiplicity() # By default, we start the frac procedure on the 25th iteration # when not reading a previous guess frac_start = kwargs.get('frac_start', 25) # By default, we occupy by tenths of electrons foccs = kwargs.get('foccs', [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0]) # By default, H**O and LUMO are both in alpha N = 0; for A in range(molecule.natom()): N += molecule.Z(A) N -= charge0 N = int(N) Nb = int((N - mult0 + 1) / 2) Na = int(N - Nb) charge = charge0 mult = mult0 # By default, nuke all the electrons Nmin = 0; if ('nmax' in kwargs): Nmin = N - int(kwargs['nmax']) # By default, DIIS in FRAC (1.0 occupation is always DIIS'd) frac_diis = kwargs.get('frac_diis', True) # By default, drop the files to the molecule's name root = kwargs.get('filename', molecule.name()) traverse_filename = root + '.traverse.dat' stats_filename = root + '.stats.dat' # => Traverse <= # psi4.set_global_option("DF_INTS_IO", "SAVE") Ns = [] energies = [] potentials = [] convs = [] stats = [] # Run one SCF to burn things in E, wfn= energy('scf', return_wfn=True, molecule=molecule, **kwargs) # Determine H**O eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() if Na == Nb: H**O = -Nb elif Nb == 0: H**O = Na else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: H**O = Na else: H**O = -Nb stats.append("""\t%6d %6d %6d %6d %6d %6d\n""" % (N, Na, Nb, charge, mult, H**O)) if H**O > 0: Na = Na - 1 else: Nb = Nb - 1 charge = charge + 1 mult = Na - Nb + 1 psi4.set_global_option("DF_INTS_IO", "LOAD") psi4.set_global_option("FRAC_START", frac_start) psi4.set_global_option("FRAC_RENORMALIZE", True) # Nuke 'em Rico! for Nintegral in range(N, Nmin, -1): # Nuke the current H**O for occ in foccs: psi4.set_global_option("FRAC_OCC", [H**O]) psi4.set_global_option("FRAC_VAL", [occ]) E, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) C = 1 if E == 0.0: E = psi4.get_variable('SCF ITERATION ENERGY') C = 0 if H**O > 0: eps = wfn.epsilon_a() potentials.append(eps[H**O - 1]) else: eps = wfn.epsilon_b() potentials.append(eps[-H**O - 1]) Ns.append(Nintegral + occ - 1.0) energies.append(E) convs.append(C) psi4.set_global_option("FRAC_START", 2) psi4.set_global_option("FRAC_LOAD", True) psi4.set_global_option("FRAC_DIIS", frac_diis) psi4.set_global_option("GUESS", "READ") # Set the next charge/mult molecule.set_molecular_charge(charge) molecule.set_multiplicity(mult) # Determine H**O print('DGAS: What ref should this point to?') #ref = psi4.legacy_wavefunction() eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() if Na == Nb: H**O = -Nb elif Nb == 0: H**O = Na else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: H**O = Na else: H**O = -Nb stats.append("""\t%6d %6d %6d %6d %6d %6d\n""" % (Nintegral-1, Na, Nb, charge, mult, H**O)) if H**O > 0: Na = Na - 1 else: Nb = Nb - 1 charge = charge + 1 mult = Na - Nb + 1 psi4.set_global_option("DF_INTS_IO", "NONE") # => Print the results out <= # E = {} psi4.print_out("""\n ==> Fractional Occupation Nuke Results <==\n\n""") psi4.print_out("""\t%-11s %-24s %-24s %11s\n""" % ('N', 'Energy', 'H**O Energy', 'Converged')) for k in range(len(Ns)): psi4.print_out("""\t%11.3E %24.16E %24.16E %11d\n""" % (Ns[k], energies[k], potentials[k], convs[k])) E[Ns[k]] = energies[k] psi4.print_out('\n') psi4.print_out("""\t%6s %6s %6s %6s %6s %6s\n""" % ('N', 'Na', 'Nb', 'Charge', 'Mult', 'H**O')) for line in stats: psi4.print_out(line) psi4.print_out('\n\t"You shoot a nuke down a bug hole, you got a lot of dead bugs"\n') psi4.print_out('\t\t\t-Starship Troopers\n') # Drop the files out fh = open(traverse_filename, 'w') fh.write("""\t%-11s %-24s %-24s %11s\n""" % ('N', 'Energy', 'H**O Energy', 'Converged')) for k in range(len(Ns)): fh.write("""\t%11.3E %24.16E %24.16E %11d\n""" % (Ns[k], energies[k], potentials[k], convs[k])) fh.close() fh = open(stats_filename, 'w') fh.write("""\t%6s %6s %6s %6s %6s %6s\n""" % ('N', 'Na', 'Nb', 'Charge', 'Mult', 'H**O')) for line in stats: fh.write(line) fh.close() # Properly, should clone molecule but since not returned and easy to unblemish, molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) return E
def run_fvno_gradient(name, **kwargs): psi4.set_global_option('DERTYPE', 'FIRST') run_fvno(name, **kwargs)
def run_gaussian_2(name, **kwargs): # throw an exception for open-shells if (psi4.get_option('SCF', 'REFERENCE') != 'RHF'): raise ValidationError("""g2 computations require "reference rhf".""") # stash user options: optstash = p4util.OptionsState(['FNOCC', 'COMPUTE_TRIPLES'], ['FNOCC', 'COMPUTE_MP4_TRIPLES'], ['FREEZE_CORE'], ['MP2_TYPE'], ['SCF', 'SCF_TYPE']) # override default scf_type psi4.set_local_option('SCF', 'SCF_TYPE', 'PK') # optimize geometry at scf level psi4.clean() psi4.set_global_option('BASIS', "6-31G(D)") driver.optimize('scf') psi4.clean() # scf frequencies for zpe # NOTE This line should not be needed, but without it there's a seg fault scf_e, ref = driver.frequency('scf', return_wfn=True) # thermodynamic properties du = psi4.get_variable('INTERNAL ENERGY CORRECTION') dh = psi4.get_variable('ENTHALPY CORRECTION') dg = psi4.get_variable('GIBBS FREE ENERGY CORRECTION') freqs = ref.frequencies() nfreq = freqs.dim(0) freqsum = 0.0 for i in range(0, nfreq): freqsum += freqs.get(i) zpe = freqsum / p4const.psi_hartree2wavenumbers * 0.8929 * 0.5 psi4.clean() # optimize geometry at mp2 (no frozen core) level # note: freeze_core isn't an option in MP2 psi4.set_global_option('FREEZE_CORE', "FALSE") psi4.set_global_option('MP2_TYPE', 'CONV') driver.optimize('mp2') psi4.clean() # qcisd(t) psi4.set_local_option('FNOCC', 'COMPUTE_MP4_TRIPLES', "TRUE") psi4.set_global_option('FREEZE_CORE', "TRUE") psi4.set_global_option('BASIS', "6-311G(D_P)") ref = driver.proc.run_fnocc('qcisd(t)', return_wfn=True, **kwargs) # HLC: high-level correction based on number of valence electrons nirrep = ref.nirrep() frzcpi = ref.frzcpi() nfzc = 0 for i in range(0, nirrep): nfzc += frzcpi[i] nalpha = ref.nalpha() - nfzc nbeta = ref.nbeta() - nfzc # hlc of gaussian-2 hlc = -0.00481 * nalpha - 0.00019 * nbeta # hlc of gaussian-1 hlc1 = -0.00614 * nalpha eqci_6311gdp = psi4.get_variable("QCISD(T) TOTAL ENERGY") emp4_6311gd = psi4.get_variable("MP4 TOTAL ENERGY") emp2_6311gd = psi4.get_variable("MP2 TOTAL ENERGY") psi4.clean() # correction for diffuse functions psi4.set_global_option('BASIS', "6-311+G(D_P)") driver.energy('mp4') emp4_6311pg_dp = psi4.get_variable("MP4 TOTAL ENERGY") emp2_6311pg_dp = psi4.get_variable("MP2 TOTAL ENERGY") psi4.clean() # correction for polarization functions psi4.set_global_option('BASIS', "6-311G(2DF_P)") driver.energy('mp4') emp4_6311g2dfp = psi4.get_variable("MP4 TOTAL ENERGY") emp2_6311g2dfp = psi4.get_variable("MP2 TOTAL ENERGY") psi4.clean() # big basis mp2 psi4.set_global_option('BASIS', "6-311+G(3DF_2P)") #run_fnocc('_mp2',**kwargs) driver.energy('mp2') emp2_big = psi4.get_variable("MP2 TOTAL ENERGY") psi4.clean() eqci = eqci_6311gdp e_delta_g2 = emp2_big + emp2_6311gd - emp2_6311g2dfp - emp2_6311pg_dp e_plus = emp4_6311pg_dp - emp4_6311gd e_2df = emp4_6311g2dfp - emp4_6311gd eg2 = eqci + e_delta_g2 + e_plus + e_2df eg2_mp2_0k = eqci + (emp2_big - emp2_6311gd) + hlc + zpe psi4.print_out('\n') psi4.print_out(' ==> G1/G2 Energy Components <==\n') psi4.print_out('\n') psi4.print_out(' QCISD(T): %20.12lf\n' % eqci) psi4.print_out(' E(Delta): %20.12lf\n' % e_delta_g2) psi4.print_out(' E(2DF): %20.12lf\n' % e_2df) psi4.print_out(' E(+): %20.12lf\n' % e_plus) psi4.print_out(' E(G1 HLC): %20.12lf\n' % hlc1) psi4.print_out(' E(G2 HLC): %20.12lf\n' % hlc) psi4.print_out(' E(ZPE): %20.12lf\n' % zpe) psi4.print_out('\n') psi4.print_out(' ==> 0 Kelvin Results <==\n') psi4.print_out('\n') eg2_0k = eg2 + zpe + hlc psi4.print_out(' G1: %20.12lf\n' % (eqci + e_plus + e_2df + hlc1 + zpe)) psi4.print_out(' G2(MP2): %20.12lf\n' % eg2_mp2_0k) psi4.print_out(' G2: %20.12lf\n' % eg2_0k) psi4.set_variable("G1 TOTAL ENERGY", eqci + e_plus + e_2df + hlc1 + zpe) psi4.set_variable("G2 TOTAL ENERGY", eg2_0k) psi4.set_variable("G2(MP2) TOTAL ENERGY", eg2_mp2_0k) psi4.print_out('\n') T = psi4.get_global_option('T') psi4.print_out(' ==> %3.0lf Kelvin Results <==\n' % T) psi4.print_out('\n') internal_energy = eg2_mp2_0k + du - zpe / 0.8929 enthalpy = eg2_mp2_0k + dh - zpe / 0.8929 gibbs = eg2_mp2_0k + dg - zpe / 0.8929 psi4.print_out(' G2(MP2) energy: %20.12lf\n' % internal_energy) psi4.print_out(' G2(MP2) enthalpy: %20.12lf\n' % enthalpy) psi4.print_out(' G2(MP2) free energy: %20.12lf\n' % gibbs) psi4.print_out('\n') psi4.set_variable("G2(MP2) INTERNAL ENERGY", internal_energy) psi4.set_variable("G2(MP2) ENTHALPY", enthalpy) psi4.set_variable("G2(MP2) FREE ENERGY", gibbs) internal_energy = eg2_0k + du - zpe / 0.8929 enthalpy = eg2_0k + dh - zpe / 0.8929 gibbs = eg2_0k + dg - zpe / 0.8929 psi4.print_out(' G2 energy: %20.12lf\n' % internal_energy) psi4.print_out(' G2 enthalpy: %20.12lf\n' % enthalpy) psi4.print_out(' G2 free energy: %20.12lf\n' % gibbs) psi4.set_variable("CURRENT ENERGY", eg2_0k) psi4.set_variable("G2 INTERNAL ENERGY", internal_energy) psi4.set_variable("G2 ENTHALPY", enthalpy) psi4.set_variable("G2 FREE ENERGY", gibbs) psi4.clean() optstash.restore() # return 0K g2 results return eg2_0k
def ip_fitting(molecule, omega_l, omega_r, **kwargs): kwargs = p4util.kwargs_lower(kwargs) # By default, zero the omega to 3 digits omega_tol = kwargs.get('omega_tolerance', 1.0E-3) # By default, do up to twenty iterations maxiter = kwargs.get('maxiter', 20) # By default, do not read previous 180 orbitals file read = False read180 = '' if 'read' in kwargs: read = True read180 = kwargs['read'] # The molecule is required, and should be the neutral species molecule.update_geometry() charge0 = molecule.molecular_charge() mult0 = molecule.multiplicity() # How many electrons are there? N = 0 for A in range(molecule.natom()): N += molecule.Z(A) N -= charge0 N = int(N) Nb = int((N - mult0 + 1) / 2) Na = int(N - Nb) # Work in the ot namespace for this procedure psi4.IO.set_default_namespace("ot") # Burn in to determine orbital eigenvalues if read: psi4.set_global_option("GUESS", "READ") copy_file_to_scratch(read180, 'psi', 'ot', 180) old_guess = psi4.get_global_option("GUESS") psi4.set_global_option("DF_INTS_IO", "SAVE") psi4.print_out("""\n\t==> IP Fitting SCF: Burn-in <==\n""") E, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) psi4.set_global_option("DF_INTS_IO", "LOAD") # Determine H**O, to determine mult1 eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() if Na == Nb: H**O = -Nb elif Nb == 0: H**O = Na else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: H**O = Na else: H**O = -Nb Na1 = Na Nb1 = Nb if H**O > 0: Na1 = Na1 - 1 else: Nb1 = Nb1 - 1 charge1 = charge0 + 1 mult1 = Na1 - Nb1 + 1 omegas = [] E0s = [] E1s = [] kIPs = [] IPs = [] types = [] # Right endpoint psi4.set_global_option('DFT_OMEGA', omega_r) # Neutral if read: psi4.set_global_option("GUESS", "READ") p4util.copy_file_to_scratch(read180, 'psi', 'ot', 180) molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) psi4.print_out("""\n\t==> IP Fitting SCF: Neutral, Right Endpoint <==\n""") E0r, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() E_HOMO = 0.0 if Nb == 0: E_HOMO = eps_a[int(Na - 1)] else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: E_HOMO = E_a else: E_HOMO = E_b E_HOMOr = E_HOMO psi4.IO.change_file_namespace(180, "ot", "neutral") # Cation if read: psi4.set_global_option("GUESS", "READ") p4util.copy_file_to_scratch(read180, 'psi', 'ot', 180) molecule.set_molecular_charge(charge1) molecule.set_multiplicity(mult1) psi4.print_out("""\n\t==> IP Fitting SCF: Cation, Right Endpoint <==\n""") E1r = energy('scf', molecule=molecule, **kwargs) psi4.IO.change_file_namespace(180, "ot", "cation") IPr = E1r - E0r kIPr = -E_HOMOr delta_r = IPr - kIPr if IPr > kIPr: message = ( """\n***IP Fitting Error: Right Omega limit should have kIP > IP""" ) raise ValidationError(message) omegas.append(omega_r) types.append('Right Limit') E0s.append(E0r) E1s.append(E1r) IPs.append(IPr) kIPs.append(kIPr) # Use previous orbitals from here out psi4.set_global_option("GUESS", "READ") # Left endpoint psi4.set_global_option('DFT_OMEGA', omega_l) # Neutral psi4.IO.change_file_namespace(180, "neutral", "ot") molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) psi4.print_out("""\n\t==> IP Fitting SCF: Neutral, Left Endpoint <==\n""") E0l, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() E_HOMO = 0.0 if Nb == 0: E_HOMO = eps_a[int(Na - 1)] else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: E_HOMO = E_a else: E_HOMO = E_b E_HOMOl = E_HOMO psi4.IO.change_file_namespace(180, "ot", "neutral") # Cation psi4.IO.change_file_namespace(180, "cation", "ot") molecule.set_molecular_charge(charge1) molecule.set_multiplicity(mult1) psi4.print_out("""\n\t==> IP Fitting SCF: Cation, Left Endpoint <==\n""") E1l = energy('scf', molecule=molecule, **kwargs) psi4.IO.change_file_namespace(180, "ot", "cation") IPl = E1l - E0l kIPl = -E_HOMOl delta_l = IPl - kIPl if IPl < kIPl: message = ( """\n***IP Fitting Error: Left Omega limit should have kIP < IP""") raise ValidationError(message) omegas.append(omega_l) types.append('Left Limit') E0s.append(E0l) E1s.append(E1l) IPs.append(IPl) kIPs.append(kIPl) converged = False repeat_l = 0 repeat_r = 0 step = 0 while True: step = step + 1 # Regula Falsi (modified) if repeat_l > 1: delta_l = delta_l / 2.0 if repeat_r > 1: delta_r = delta_r / 2.0 omega = -(omega_r - omega_l) / (delta_r - delta_l) * delta_l + omega_l psi4.set_global_option('DFT_OMEGA', omega) # Neutral psi4.IO.change_file_namespace(180, "neutral", "ot") molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) psi4.print_out( """\n\t==> IP Fitting SCF: Neutral, Omega = %11.3E <==\n""" % omega) E0, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() E_HOMO = 0.0 if Nb == 0: E_HOMO = eps_a[int(Na - 1)] else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: E_HOMO = E_a else: E_HOMO = E_b psi4.IO.change_file_namespace(180, "ot", "neutral") # Cation psi4.IO.change_file_namespace(180, "cation", "ot") molecule.set_molecular_charge(charge1) molecule.set_multiplicity(mult1) psi4.print_out( """\n\t==> IP Fitting SCF: Cation, Omega = %11.3E <==\n""" % omega) E1 = energy('scf', molecule=molecule, **kwargs) psi4.IO.change_file_namespace(180, "ot", "cation") IP = E1 - E0 kIP = -E_HOMO delta = IP - kIP if kIP > IP: omega_r = omega E0r = E0 E1r = E1 IPr = IP kIPr = kIP delta_r = delta repeat_r = 0 repeat_l = repeat_l + 1 else: omega_l = omega E0l = E0 E1l = E1 IPl = IP kIPl = kIP delta_l = delta repeat_l = 0 repeat_r = repeat_r + 1 omegas.append(omega) types.append('Regula-Falsi') E0s.append(E0) E1s.append(E1) IPs.append(IP) kIPs.append(kIP) # Termination if (abs(omega_l - omega_r) < omega_tol or step > maxiter): converged = True break # Properly, should clone molecule but since not returned and easy to unblemish, molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) psi4.IO.set_default_namespace("") psi4.print_out("""\n\t==> IP Fitting Results <==\n\n""") psi4.print_out("""\t => Occupation Determination <= \n\n""") psi4.print_out("""\t %6s %6s %6s %6s %6s %6s\n""" % ('N', 'Na', 'Nb', 'Charge', 'Mult', 'H**O')) psi4.print_out("""\t Neutral: %6d %6d %6d %6d %6d %6d\n""" % (N, Na, Nb, charge0, mult0, H**O)) psi4.print_out("""\t Cation: %6d %6d %6d %6d %6d\n\n""" % (N - 1, Na1, Nb1, charge1, mult1)) psi4.print_out("""\t => Regula Falsi Iterations <=\n\n""") psi4.print_out("""\t%3s %11s %14s %14s %14s %s\n""" % ('N', 'Omega', 'IP', 'kIP', 'Delta', 'Type')) for k in range(len(omegas)): psi4.print_out( """\t%3d %11.3E %14.6E %14.6E %14.6E %s\n""" % (k + 1, omegas[k], IPs[k], kIPs[k], IPs[k] - kIPs[k], types[k])) if converged: psi4.print_out("""\n\tIP Fitting Converged\n""") psi4.print_out("""\tFinal omega = %14.6E\n""" % ((omega_l + omega_r) / 2)) psi4.print_out( """\n\t"M,I. does the dying. Fleet just does the flying."\n""") psi4.print_out("""\t\t\t-Starship Troopers\n""") else: psi4.print_out("""\n\tIP Fitting did not converge!\n""") psi4.set_global_option("DF_INTS_IO", "NONE") psi4.set_global_option("GUESS", old_guess)
def _nbody_gufunc(func, method_string, **kwargs): """ Computes the nbody interaction energy, gradient, or Hessian depending on input. Parameters ---------- func : python function Python function that accepts method_string and a molecule and returns a energy, gradient, or Hessian. method_string : str Lowername to be passed to function molecule : psi4.Molecule (default: Global Molecule) Molecule to use in all computations return_wfn : bool (default: False) Return a wavefunction or not bsse_type : str or list (default: None, this function is not called) Type of BSSE correction to compute: CP, NoCP, or VMFC. The first in this list is returned by this function. max_nbody : int Maximum n-body to compute, cannot exceede the number of fragments in the moleucle ptype : str Type of the procedure passed in return_total_data : bool (default: False) If True returns the total data (energy/gradient/etc) of the system otherwise returns interaction data Returns ------- data : return type of func The interaction data wfn : psi4.Wavefunction (optional) A wavefunction with energy/gradient/hessian set appropriotely. This wavefunction also contains Notes ----- This is a generalized univeral function for compute interaction quantities. Examples -------- """ ### ==> Parse some kwargs <== kwargs = p4util.kwargs_lower(kwargs) return_wfn = kwargs.pop('return_wfn', False) ptype = kwargs.pop('ptype', None) return_total_data = kwargs.pop('return_total_data', False) molecule = kwargs.pop('molecule', psi4.get_active_molecule()) molecule.update_geometry() psi4.clean_variables() if ptype not in ['energy', 'gradient', 'hessian']: raise ValidationError("""N-Body driver: The ptype '%s' is not regonized.""" % ptype) # Figure out BSSE types do_cp = False do_nocp = False do_vmfc = False return_method = False # Must be passed bsse_type bsse_type_list = kwargs.pop('bsse_type') if bsse_type_list is None: raise ValidationError("N-Body GUFunc: Must pass a bsse_type") if not isinstance(bsse_type_list, list): bsse_type_list = [bsse_type_list] for num, btype in enumerate(bsse_type_list): if btype.lower() == 'cp': do_cp = True if (num == 0): return_method = 'cp' elif btype.lower() == 'nocp': do_nocp = True if (num == 0): return_method = 'nocp' elif btype.lower() == 'vmfc': do_vmfc = True if (num == 0): return_method = 'vmfc' else: raise ValidationError("N-Body GUFunc: bsse_type '%s' is not recognized" % btype.lower()) max_nbody = kwargs.get('max_nbody', -1) max_frag = molecule.nfragments() if max_nbody == -1: max_nbody = molecule.nfragments() else: max_nbody = min(max_nbody, max_frag) # What levels do we need? nbody_range = range(1, max_nbody + 1) fragment_range = range(1, max_frag + 1) # If we are doing CP lets save them integrals if 'cp' in bsse_type_list and (len(bsse_type_list) == 1): # Set to save RI integrals for repeated full-basis computations ri_ints_io = psi4.get_global_option('DF_INTS_IO') # inquire if above at all applies to dfmp2 or just scf psi4.set_global_option('DF_INTS_IO', 'SAVE') psioh = psi4.IOManager.shared_object() psioh.set_specific_retention(97, True) bsse_str = bsse_type_list[0] if len(bsse_type_list) >1: bsse_str = str(bsse_type_list) psi4.print_out("\n\n") psi4.print_out(" ===> N-Body Interaction Abacus <===\n") psi4.print_out(" BSSE Treatment: %s\n" % bsse_str) cp_compute_list = {x:set() for x in nbody_range} nocp_compute_list = {x:set() for x in nbody_range} vmfc_compute_list = {x:set() for x in nbody_range} vmfc_level_list = {x:set() for x in nbody_range} # Need to sum something slightly different # Build up compute sets if do_cp: # Everything is in dimer basis basis_tuple = tuple(fragment_range) for nbody in nbody_range: for x in it.combinations(fragment_range, nbody): cp_compute_list[nbody].add( (x, basis_tuple) ) if do_nocp: # Everything in monomer basis for nbody in nbody_range: for x in it.combinations(fragment_range, nbody): nocp_compute_list[nbody].add( (x, x) ) if do_vmfc: # Like a CP for all combinations of pairs or greater for nbody in nbody_range: for cp_combos in it.combinations(fragment_range, nbody): basis_tuple = tuple(cp_combos) for interior_nbody in nbody_range: for x in it.combinations(cp_combos, interior_nbody): combo_tuple = (x, basis_tuple) vmfc_compute_list[interior_nbody].add( combo_tuple ) vmfc_level_list[len(basis_tuple)].add( combo_tuple ) # Build a comprehensive compute_range compute_list = {x:set() for x in nbody_range} for n in nbody_range: compute_list[n] |= cp_compute_list[n] compute_list[n] |= nocp_compute_list[n] compute_list[n] |= vmfc_compute_list[n] psi4.print_out(" Number of %d-body computations: %d\n" % (n, len(compute_list[n]))) # Build size and slices dictionaries fragment_size_dict = {frag: molecule.extract_subsets(frag).natom() for frag in range(1, max_frag+1)} start = 0 fragment_slice_dict = {} for k, v in fragment_size_dict.items(): fragment_slice_dict[k] = slice(start, start + v) start += v molecule_total_atoms = sum(fragment_size_dict.values()) # Now compute the energies energies_dict = {} ptype_dict = {} for n in compute_list.keys(): psi4.print_out("\n ==> N-Body: Now computing %d-body complexes <==\n\n" % n) print("\n ==> N-Body: Now computing %d-body complexes <==\n" % n) total = len(compute_list[n]) for num, pair in enumerate(compute_list[n]): psi4.print_out("\n N-Body: Computing complex (%d/%d) with fragments %s in the basis of fragments %s.\n\n" % (num + 1, total, str(pair[0]), str(pair[1]))) ghost = list(set(pair[1]) - set(pair[0])) current_mol = molecule.extract_subsets(list(pair[0]), ghost) ptype_dict[pair] = func(method_string, molecule=current_mol, **kwargs) energies_dict[pair] = psi4.get_variable("CURRENT ENERGY") psi4.print_out("\n N-Body: Complex Energy (fragments = %s, basis = %s: %20.14f)\n" % (str(pair[0]), str(pair[1]), energies_dict[pair])) if 'cp' in bsse_type_list and (len(bsse_type_list) == 1): psi4.set_global_option('DF_INTS_IO', 'LOAD') psi4.clean() # Final dictionaries cp_energy_by_level = {n: 0.0 for n in nbody_range} nocp_energy_by_level = {n: 0.0 for n in nbody_range} cp_energy_body_dict = {n: 0.0 for n in nbody_range} nocp_energy_body_dict = {n: 0.0 for n in nbody_range} vmfc_energy_body_dict = {n: 0.0 for n in nbody_range} # Build out ptype dictionaries if needed if ptype != 'energy': if ptype == 'gradient': arr_shape = (molecule_total_atoms, 3) elif ptype == 'hessian': arr_shape = (molecule_total_atoms * 3, molecule_total_atoms * 3) else: raise KeyError("N-Body: ptype '%s' not recognized" % ptype) cp_ptype_by_level = {n: np.zeros(arr_shape) for n in nbody_range} nocp_ptype_by_level = {n: np.zeros(arr_shape) for n in nbody_range} cp_ptype_body_dict = {n: np.zeros(arr_shape) for n in nbody_range} nocp_ptype_body_dict = {n: np.zeros(arr_shape) for n in nbody_range} vmfc_ptype_body_dict = {n: np.zeros(arr_shape) for n in nbody_range} else: cp_ptype_by_level, cp_ptype_body_dict = None, None nocp_ptype_by_level, nocp_ptype_body_dict = None, None vmfc_ptype_by_level= None # Sum up all of the levels for n in nbody_range: # Energy cp_energy_by_level[n] = sum(energies_dict[v] for v in cp_compute_list[n]) nocp_energy_by_level[n] = sum(energies_dict[v] for v in nocp_compute_list[n]) # Special vmfc case if n > 1: vmfc_energy_body_dict[n] = vmfc_energy_body_dict[n - 1] for tup in vmfc_level_list[n]: vmfc_energy_body_dict[n] += ((-1) ** (n - len(tup[0]))) * energies_dict[tup] # Do ptype if ptype != 'energy': _sum_cluster_ptype_data(ptype, ptype_dict, cp_compute_list[n], fragment_slice_dict, fragment_size_dict, cp_ptype_by_level[n]) _sum_cluster_ptype_data(ptype, ptype_dict, nocp_compute_list[n], fragment_slice_dict, fragment_size_dict, nocp_ptype_by_level[n]) _sum_cluster_ptype_data(ptype, ptype_dict, vmfc_level_list[n], fragment_slice_dict, fragment_size_dict, vmfc_ptype_by_level[n], vmfc=True) # Compute cp energy and ptype if do_cp: for n in nbody_range: if n == max_frag: cp_energy_body_dict[n] = cp_energy_by_level[n] if ptype != 'energy': cp_ptype_body_dict[n][:] = cp_ptype_by_level[n] continue for k in range(1, n + 1): take_nk = nCr(max_frag - k - 1, n - k) sign = ((-1) ** (n - k)) value = cp_energy_by_level[k] cp_energy_body_dict[n] += take_nk * sign * value if ptype != 'energy': value = cp_ptype_by_level[k] cp_ptype_body_dict[n] += take_nk * sign * value _print_nbody_energy(cp_energy_body_dict, "Counterpoise Corrected (CP)") cp_interaction_energy = cp_energy_body_dict[max_nbody] - cp_energy_body_dict[1] psi4.set_variable('Counterpoise Corrected Total Energy', cp_energy_body_dict[max_nbody]) psi4.set_variable('Counterpoise Corrected Interaction Energy', cp_interaction_energy) for n in nbody_range[1:]: var_key = 'CP-CORRECTED %d-BODY INTERACTION ENERGY' % n psi4.set_variable(var_key, cp_energy_body_dict[n] - cp_energy_body_dict[1]) # Compute nocp energy and ptype if do_nocp: for n in nbody_range: if n == max_frag: nocp_energy_body_dict[n] = nocp_energy_by_level[n] if ptype != 'energy': nocp_ptype_body_dict[n][:] = nocp_ptype_by_level[n] continue for k in range(1, n + 1): take_nk = nCr(max_frag - k - 1, n - k) sign = ((-1) ** (n - k)) value = nocp_energy_by_level[k] nocp_energy_body_dict[n] += take_nk * sign * value if ptype != 'energy': value = nocp_ptype_by_level[k] nocp_ptype_body_dict[n] += take_nk * sign * value _print_nbody_energy(nocp_energy_body_dict, "Non-Counterpoise Corrected (NoCP)") nocp_interaction_energy = nocp_energy_body_dict[max_nbody] - nocp_energy_body_dict[1] psi4.set_variable('Non-Counterpoise Corrected Total Energy', nocp_energy_body_dict[max_nbody]) psi4.set_variable('Non-Counterpoise Corrected Interaction Energy', nocp_interaction_energy) for n in nbody_range[1:]: var_key = 'NOCP-CORRECTED %d-BODY INTERACTION ENERGY' % n psi4.set_variable(var_key, nocp_energy_body_dict[n] - nocp_energy_body_dict[1]) # Compute vmfc energy and ptype if do_vmfc: _print_nbody_energy(vmfc_energy_body_dict, "Valiron-Mayer Function Couterpoise (VMFC)") vmfc_interaction_energy = vmfc_energy_body_dict[max_nbody] - vmfc_energy_body_dict[1] psi4.set_variable('Valiron-Mayer Function Couterpoise Total Energy', vmfc_energy_body_dict[max_nbody]) psi4.set_variable('Valiron-Mayer Function Couterpoise Interaction Energy', vmfc_interaction_energy) for n in nbody_range[1:]: var_key = 'VMFC-CORRECTED %d-BODY INTERACTION ENERGY' % n psi4.set_variable(var_key, vmfc_energy_body_dict[n] - vmfc_energy_body_dict[1]) if return_method == 'cp': ptype_body_dict = cp_ptype_body_dict energy_body_dict = cp_energy_body_dict elif return_method == 'nocp': ptype_body_dict = nocp_ptype_body_dict energy_body_dict = nocp_energy_body_dict elif return_method == 'vmfc': ptype_body_dict = vmfc_ptype_body_dict energy_body_dict = vmfc_energy_body_dict else: raise ValidationError("N-Body Wrapper: Invalid return type. Should never be here, please post this error on github.") # Figure out and build return types if return_total_data: ret_energy = energy_body_dict[max_nbody] else: ret_energy = energy_body_dict[max_nbody] ret_energy -= energy_body_dict[1] if ptype != 'energy': if return_total_data: np_final_ptype = ptype_body_dict[max_nbody].copy() else: np_final_ptype = ptype_body_dict[max_nbody].copy() np_final_ptype -= ptype_body_dict[1] ret_ptype = psi4.Matrix(*np_cp_final_ptype.shape) ret_ptype_view = np.asarray(final_ptype) ret_ptype_view[:] = np_final_ptype else: ret_ptype = ret_energy # Build and set a wavefunction wfn = psi4.new_wavefunction(molecule, 'sto-3g') wfn.nbody_energy = energies_dict wfn.nbody_ptype = ptype_dict wfn.nbody_body_energy = energy_body_dict wfn.nbody_body_ptype = ptype_body_dict if ptype == 'gradient': wfn.set_gradient(ret_ptype) elif ptype == 'hessian': wfn.set_hessian(ret_ptype) psi4.set_variable("CURRENT ENERGY", ret_energy) if return_wfn: return (ret_ptype, wfn) else: return ret_ptype
import psi4 psi4.set_output_file("output.dat", False) geom = psi4.geometry(""" He He 1 5 """) psi4.set_global_option("SCF_TYPE", "DIRECT") psi4.set_global_option("BASIS", "STO-3G") scf_e = psi4.energy('SCF') psi4.compare_values(-5.6155679150795779, scf_e, 6, 'SCF Energy')
def fitScf(self): """Function to run scf and fit a system of diffuse charges to resulting density. """ basisChanged = psi4.has_option_changed("BASIS") ribasisChanged = psi4.has_option_changed("DF_BASIS_SCF") scftypeChanged = psi4.has_option_changed("SCF_TYPE") basis = psi4.get_option("BASIS") ribasis = psi4.get_option("DF_BASIS_SCF") scftype = psi4.get_option("SCF_TYPE") psi4.print_out(" => Diffuse SCF (Determines Da) <=\n\n") activate(self.molecule) psi4.set_global_option("BASIS", self.basisname) psi4.set_global_option("DF_BASIS_SCF", self.ribasisname) psi4.set_global_option("SCF_TYPE", "DF") energy('scf') psi4.print_out("\n") self.fitGeneral() psi4.clean() psi4.set_global_option("BASIS", basis) psi4.set_global_option("DF_BASIS_SCF", ribasis) psi4.set_global_option("SCF_TYPE", scftype) if not basisChanged: psi4.revoke_option_changed("BASIS") if not ribasisChanged: psi4.revoke_option_changed("DF_BASIS_SCF") if not scftypeChanged: psi4.revoke_option_changed("SCF_TYPE")
def frac_nuke(molecule, **kwargs): kwargs = p4util.kwargs_lower(kwargs) # The molecule is required, and should be the neutral species molecule.update_geometry() charge0 = molecule.molecular_charge() mult0 = molecule.multiplicity() # By default, we start the frac procedure on the 25th iteration # when not reading a previous guess frac_start = kwargs.get('frac_start', 25) # By default, we occupy by tenths of electrons foccs = kwargs.get('foccs', [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0]) # By default, H**O and LUMO are both in alpha N = 0 for A in range(molecule.natom()): N += molecule.Z(A) N -= charge0 N = int(N) Nb = int((N - mult0 + 1) / 2) Na = int(N - Nb) charge = charge0 mult = mult0 # By default, nuke all the electrons Nmin = 0 if ('nmax' in kwargs): Nmin = N - int(kwargs['nmax']) # By default, DIIS in FRAC (1.0 occupation is always DIIS'd) frac_diis = kwargs.get('frac_diis', True) # By default, drop the files to the molecule's name root = kwargs.get('filename', molecule.name()) traverse_filename = root + '.traverse.dat' stats_filename = root + '.stats.dat' # => Traverse <= # psi4.set_global_option("DF_INTS_IO", "SAVE") Ns = [] energies = [] potentials = [] convs = [] stats = [] # Run one SCF to burn things in E, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) # Determine H**O eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() if Na == Nb: H**O = -Nb elif Nb == 0: H**O = Na else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: H**O = Na else: H**O = -Nb stats.append("""\t%6d %6d %6d %6d %6d %6d\n""" % (N, Na, Nb, charge, mult, H**O)) if H**O > 0: Na = Na - 1 else: Nb = Nb - 1 charge = charge + 1 mult = Na - Nb + 1 psi4.set_global_option("DF_INTS_IO", "LOAD") psi4.set_global_option("FRAC_START", frac_start) psi4.set_global_option("FRAC_RENORMALIZE", True) # Nuke 'em Rico! for Nintegral in range(N, Nmin, -1): # Nuke the current H**O for occ in foccs: psi4.set_global_option("FRAC_OCC", [H**O]) psi4.set_global_option("FRAC_VAL", [occ]) E, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) C = 1 if E == 0.0: E = psi4.get_variable('SCF ITERATION ENERGY') C = 0 if H**O > 0: eps = wfn.epsilon_a() potentials.append(eps[H**O - 1]) else: eps = wfn.epsilon_b() potentials.append(eps[-H**O - 1]) Ns.append(Nintegral + occ - 1.0) energies.append(E) convs.append(C) psi4.set_global_option("FRAC_START", 2) psi4.set_global_option("FRAC_LOAD", True) psi4.set_global_option("FRAC_DIIS", frac_diis) psi4.set_global_option("GUESS", "READ") # Set the next charge/mult molecule.set_molecular_charge(charge) molecule.set_multiplicity(mult) # Determine H**O print('DGAS: What ref should this point to?') #ref = psi4.legacy_wavefunction() eps_a = wfn.epsilon_a() eps_b = wfn.epsilon_b() if Na == Nb: H**O = -Nb elif Nb == 0: H**O = Na else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if E_a >= E_b: H**O = Na else: H**O = -Nb stats.append("""\t%6d %6d %6d %6d %6d %6d\n""" % (Nintegral - 1, Na, Nb, charge, mult, H**O)) if H**O > 0: Na = Na - 1 else: Nb = Nb - 1 charge = charge + 1 mult = Na - Nb + 1 psi4.set_global_option("DF_INTS_IO", "NONE") # => Print the results out <= # E = {} psi4.print_out("""\n ==> Fractional Occupation Nuke Results <==\n\n""") psi4.print_out("""\t%-11s %-24s %-24s %11s\n""" % ('N', 'Energy', 'H**O Energy', 'Converged')) for k in range(len(Ns)): psi4.print_out("""\t%11.3E %24.16E %24.16E %11d\n""" % (Ns[k], energies[k], potentials[k], convs[k])) E[Ns[k]] = energies[k] psi4.print_out('\n') psi4.print_out("""\t%6s %6s %6s %6s %6s %6s\n""" % ('N', 'Na', 'Nb', 'Charge', 'Mult', 'H**O')) for line in stats: psi4.print_out(line) psi4.print_out( '\n\t"You shoot a nuke down a bug hole, you got a lot of dead bugs"\n') psi4.print_out('\t\t\t-Starship Troopers\n') # Drop the files out fh = open(traverse_filename, 'w') fh.write("""\t%-11s %-24s %-24s %11s\n""" % ('N', 'Energy', 'H**O Energy', 'Converged')) for k in range(len(Ns)): fh.write("""\t%11.3E %24.16E %24.16E %11d\n""" % (Ns[k], energies[k], potentials[k], convs[k])) fh.close() fh = open(stats_filename, 'w') fh.write("""\t%6s %6s %6s %6s %6s %6s\n""" % ('N', 'Na', 'Nb', 'Charge', 'Mult', 'H**O')) for line in stats: fh.write(line) fh.close() # Properly, should clone molecule but since not returned and easy to unblemish, molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) return E
def frac_traverse(molecule, **kwargs): kwargs = p4util.kwargs_lower(kwargs) # The molecule is required, and should be the neutral species molecule.update_geometry() charge0 = molecule.molecular_charge() mult0 = molecule.multiplicity() chargep = charge0 + 1 chargem = charge0 - 1 # By default, the multiplicity of the cation/anion are mult0 + 1 # These are overridden with the cation_mult and anion_mult kwargs multp = kwargs.get('cation_mult', mult0 + 1) multm = kwargs.get('anion_mult', mult0 + 1) # By default, we start the frac procedure on the 25th iteration # when not reading a previous guess frac_start = kwargs.get('frac_start', 25) # By default, we occupy by tenths of electrons HOMO_occs = kwargs.get( 'HOMO_occs', [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0]) LUMO_occs = kwargs.get( 'LUMO_occs', [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0]) # By default, H**O and LUMO are both in alpha Z = 0 for A in range(molecule.natom()): Z += molecule.Z(A) Z -= charge0 H**O = kwargs.get('H**O', (Z / 2 + 1 if (Z % 2) else Z / 2)) LUMO = kwargs.get('LUMO', H**O + 1) # By default, DIIS in FRAC (1.0 occupation is always DIIS'd) frac_diis = kwargs.get('frac_diis', True) # By default, use the neutral orbitals as a guess for the anion neutral_guess = kwargs.get('neutral_guess', True) # By default, burn-in with UHF first, if UKS hf_guess = False if psi4.get_global_option('REFERENCE') == 'UKS': hf_guess = kwargs.get('hf_guess', True) # By default, re-guess at each N continuous_guess = kwargs.get('continuous_guess', False) # By default, drop the files to the molecule's name root = kwargs.get('filename', molecule.name()) traverse_filename = root + '.traverse.dat' # => Traverse <= # occs = [] energies = [] potentials = [] convs = [] # => Run the neutral for its orbitals, if requested <= # old_df_ints_io = psi4.get_global_option("DF_INTS_IO") psi4.set_global_option("DF_INTS_IO", "SAVE") old_guess = psi4.get_global_option("GUESS") if (neutral_guess): if (hf_guess): psi4.set_global_option("REFERENCE", "UHF") energy('scf') psi4.set_global_option("GUESS", "READ") psi4.set_global_option("DF_INTS_IO", "LOAD") # => Run the anion first <= # molecule.set_molecular_charge(chargem) molecule.set_multiplicity(multm) # => Burn the anion in with hf, if requested <= # if hf_guess: psi4.set_global_option("REFERENCE", "UHF") energy('scf', molecule=molecule, **kwargs) psi4.set_global_option("REFERENCE", "UKS") psi4.set_global_option("GUESS", "READ") psi4.set_global_option("DF_INTS_IO", "SAVE") psi4.set_global_option("FRAC_START", frac_start) psi4.set_global_option("FRAC_RENORMALIZE", True) psi4.set_global_option("FRAC_LOAD", False) for occ in LUMO_occs: psi4.set_global_option("FRAC_OCC", [LUMO]) psi4.set_global_option("FRAC_VAL", [occ]) E, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) C = 1 if E == 0.0: E = psi4.get_variable('SCF ITERATION ENERGY') C = 0 if LUMO > 0: eps = wfn.epsilon_a() potentials.append(eps[int(LUMO) - 1]) else: eps = wfn.epsilon_b() potentials.append(eps[-int(LUMO) - 1]) occs.append(occ) energies.append(E) convs.append(C) psi4.set_global_option("FRAC_START", 2) psi4.set_global_option("FRAC_LOAD", True) psi4.set_global_option("GUESS", "READ") psi4.set_global_option("FRAC_DIIS", frac_diis) psi4.set_global_option("DF_INTS_IO", "LOAD") # => Run the neutral next <= # molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) # Burn the neutral in with hf, if requested <= # if not continuous_guess: psi4.set_global_option("GUESS", old_guess) if hf_guess: psi4.set_global_option("FRAC_START", 0) psi4.set_global_option("REFERENCE", "UHF") energy('scf', molecule=molecule, **kwargs) psi4.set_global_option("REFERENCE", "UKS") psi4.set_global_option("GUESS", "READ") psi4.set_global_option("FRAC_LOAD", False) psi4.set_global_option("FRAC_START", frac_start) psi4.set_global_option("FRAC_RENORMALIZE", True) for occ in HOMO_occs: psi4.set_global_option("FRAC_OCC", [H**O]) psi4.set_global_option("FRAC_VAL", [occ]) E, wfn = energy('scf', return_wfn=True, molecule=molecule, **kwargs) C = 1 if E == 0.0: E = psi4.get_variable('SCF ITERATION ENERGY') C = 0 if LUMO > 0: eps = wfn.epsilon_a() potentials.append(eps[int(H**O) - 1]) else: eps = wfn.epsilon_b() potentials.append(eps[-int(H**O) - 1]) occs.append(occ - 1.0) energies.append(E) convs.append(C) psi4.set_global_option("FRAC_START", 2) psi4.set_global_option("FRAC_LOAD", True) psi4.set_global_option("GUESS", "READ") psi4.set_global_option("FRAC_DIIS", frac_diis) psi4.set_global_option("DF_INTS_IO", "LOAD") psi4.set_global_option("DF_INTS_IO", old_df_ints_io) # => Print the results out <= # E = {} psi4.print_out( """\n ==> Fractional Occupation Traverse Results <==\n\n""") psi4.print_out("""\t%-11s %-24s %-24s %11s\n""" % ('N', 'Energy', 'H**O Energy', 'Converged')) for k in range(len(occs)): psi4.print_out("""\t%11.3E %24.16E %24.16E %11d\n""" % (occs[k], energies[k], potentials[k], convs[k])) E[occs[k]] = energies[k] psi4.print_out('\n\t"You trying to be a hero Watkins?"\n') psi4.print_out('\t"Just trying to kill some bugs sir!"\n') psi4.print_out('\t\t\t-Starship Troopers\n') # Drop the files out fh = open(traverse_filename, 'w') fh.write("""\t%-11s %-24s %-24s %11s\n""" % ('N', 'Energy', 'H**O Energy', 'Converged')) for k in range(len(occs)): fh.write("""\t%11.3E %24.16E %24.16E %11d\n""" % (occs[k], energies[k], potentials[k], convs[k])) fh.close() # Properly, should clone molecule but since not returned and easy to unblemish, molecule.set_molecular_charge(charge0) molecule.set_multiplicity(mult0) return E
import psi4 import numpy as np psi4.set_output_file("output.dat", False) mol_string = """ He He 1 **R** """ mols = [(d, mol_string.replace("**R**", "%5.3f" % d)) for d in np.linspace(2, 5, 4)] psi4.set_global_option("BASIS", "6-31G") out = {} for d, mol in mols: geom = psi4.geometry(mol) out[d] = psi4.energy('SCF', molecule=geom) bench_dict = {2.0: -5.70825982153, 3.0: -5.71036140727, 4.0: -5.71036306964, 5.0: -5.71036203769} for key in bench_dict.keys(): val = out[key] bench = bench_dict[key] psi4.compare_values(val, bench, 6, 'SCF Energy @%5.3fR' % key)
def ip_fitting(mol, omega_l, omega_r, **kwargs): kwargs = p4util.kwargs_lower(kwargs) # By default, zero the omega to 3 digits omega_tol = 1.0E-3; if (kwargs.has_key('omega_tolerance')): omega_tol = kwargs['omega_tolerance'] # By default, do up to twenty iterations maxiter = 20; if (kwargs.has_key('maxiter')): maxiter = kwargs['maxiter'] # By default, do not read previous 180 orbitals file read = False; read180 = '' if (kwargs.has_key('read')): read = True; read180 = kwargs['read'] # The molecule is required, and should be the neutral species mol.update_geometry() activate(mol) charge0 = mol.molecular_charge() mult0 = mol.multiplicity() # How many electrons are there? N = 0; for A in range(mol.natom()): N += mol.Z(A) N -= charge0 N = int(N) Nb = int((N - mult0 + 1)/2) Na = int(N - Nb) # Work in the ot namespace for this procedure psi4.IO.set_default_namespace("ot") # Burn in to determine orbital eigenvalues if (read): psi4.set_global_option("GUESS", "READ") copy_file_to_scratch(read180, 'psi', 'ot', 180) old_guess = psi4.get_global_option("GUESS") psi4.set_global_option("DF_INTS_IO", "SAVE") psi4.print_out('\n\t==> IP Fitting SCF: Burn-in <==\n') energy('scf') psi4.set_global_option("DF_INTS_IO", "LOAD") # Determine H**O, to determine mult1 ref = psi4.wavefunction() eps_a = ref.epsilon_a() eps_b = ref.epsilon_b() if (Na == Nb): H**O = -Nb elif (Nb == 0): H**O = Na else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if (E_a >= E_b): H**O = Na else: H**O = -Nb Na1 = Na; Nb1 = Nb; if (H**O > 0): Na1 = Na1-1; else: Nb1 = Nb1-1; charge1 = charge0 + 1; mult1 = Na1 - Nb1 + 1 omegas = []; E0s = []; E1s = []; kIPs = []; IPs = []; types = []; # Right endpoint psi4.set_global_option('DFT_OMEGA',omega_r) # Neutral if (read): psi4.set_global_option("GUESS", "READ") p4util.copy_file_to_scratch(read180, 'psi', 'ot', 180) mol.set_molecular_charge(charge0) mol.set_multiplicity(mult0) psi4.print_out('\n\t==> IP Fitting SCF: Neutral, Right Endpoint <==\n') E0r = energy('scf') ref = psi4.wavefunction() eps_a = ref.epsilon_a() eps_b = ref.epsilon_b() E_HOMO = 0.0; if (Nb == 0): E_HOMO = eps_a[int(Na-1)] else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if (E_a >= E_b): E_HOMO = E_a; else: E_HOMO = E_b; E_HOMOr = E_HOMO; psi4.IO.change_file_namespace(180,"ot","neutral") # Cation if (read): psi4.set_global_option("GUESS", "READ") p4util.copy_file_to_scratch(read180, 'psi', 'ot', 180) mol.set_molecular_charge(charge1) mol.set_multiplicity(mult1) psi4.print_out('\n\t==> IP Fitting SCF: Cation, Right Endpoint <==\n') E1r = energy('scf') psi4.IO.change_file_namespace(180,"ot","cation") IPr = E1r - E0r; kIPr = -E_HOMOr; delta_r = IPr - kIPr; if (IPr > kIPr): psi4.print_out('\n***IP Fitting Error: Right Omega limit should have kIP > IP') sys.exit(1) omegas.append(omega_r) types.append('Right Limit') E0s.append(E0r) E1s.append(E1r) IPs.append(IPr) kIPs.append(kIPr) # Use previous orbitals from here out psi4.set_global_option("GUESS","READ") # Left endpoint psi4.set_global_option('DFT_OMEGA',omega_l) # Neutral psi4.IO.change_file_namespace(180,"neutral","ot") mol.set_molecular_charge(charge0) mol.set_multiplicity(mult0) psi4.print_out('\n\t==> IP Fitting SCF: Neutral, Left Endpoint <==\n') E0l = energy('scf') ref = psi4.wavefunction() eps_a = ref.epsilon_a() eps_b = ref.epsilon_b() E_HOMO = 0.0; if (Nb == 0): E_HOMO = eps_a[int(Na-1)] else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if (E_a >= E_b): E_HOMO = E_a; else: E_HOMO = E_b; E_HOMOl = E_HOMO; psi4.IO.change_file_namespace(180,"ot","neutral") # Cation psi4.IO.change_file_namespace(180,"cation","ot") mol.set_molecular_charge(charge1) mol.set_multiplicity(mult1) psi4.print_out('\n\t==> IP Fitting SCF: Cation, Left Endpoint <==\n') E1l = energy('scf') psi4.IO.change_file_namespace(180,"ot","cation") IPl = E1l - E0l; kIPl = -E_HOMOl; delta_l = IPl - kIPl; if (IPl < kIPl): psi4.print_out('\n***IP Fitting Error: Left Omega limit should have kIP < IP') sys.exit(1) omegas.append(omega_l) types.append('Left Limit') E0s.append(E0l) E1s.append(E1l) IPs.append(IPl) kIPs.append(kIPl) converged = False repeat_l = 0; repeat_r = 0; step = 0; while True: step = step + 1; # Regula Falsi (modified) if (repeat_l > 1): delta_l = delta_l / 2.0; if (repeat_r > 1): delta_r = delta_r / 2.0; omega = - (omega_r - omega_l) / (delta_r - delta_l) * delta_l + omega_l; psi4.set_global_option('DFT_OMEGA',omega) # Neutral psi4.IO.change_file_namespace(180,"neutral","ot") mol.set_molecular_charge(charge0) mol.set_multiplicity(mult0) psi4.print_out('\n\t==> IP Fitting SCF: Neutral, Omega = %11.3E <==\n' % omega) E0 = energy('scf') ref = psi4.wavefunction() eps_a = ref.epsilon_a() eps_b = ref.epsilon_b() E_HOMO = 0.0; if (Nb == 0): E_HOMO = eps_a[int(Na-1)] else: E_a = eps_a[int(Na - 1)] E_b = eps_b[int(Nb - 1)] if (E_a >= E_b): E_HOMO = E_a; else: E_HOMO = E_b; psi4.IO.change_file_namespace(180,"ot","neutral") # Cation psi4.IO.change_file_namespace(180,"cation","ot") mol.set_molecular_charge(charge1) mol.set_multiplicity(mult1) psi4.print_out('\n\t==> IP Fitting SCF: Cation, Omega = %11.3E <==\n' % omega) E1 = energy('scf') psi4.IO.change_file_namespace(180,"ot","cation") IP = E1 - E0; kIP = -E_HOMO; delta = IP - kIP; if (kIP > IP): omega_r = omega E0r = E0 E1r = E1 IPr = IP kIPr = kIP delta_r = delta repeat_r = 0; repeat_l = repeat_l + 1; else: omega_l = omega E0l = E0 E1l = E1 IPl = IP kIPl = kIP delta_l = delta repeat_l = 0; repeat_r = repeat_r + 1; omegas.append(omega) types.append('Regula-Falsi') E0s.append(E0) E1s.append(E1) IPs.append(IP) kIPs.append(kIP) # Termination if (abs(omega_l - omega_r) < omega_tol or step > maxiter): converged = True; break psi4.IO.set_default_namespace("") psi4.print_out('\n\t==> IP Fitting Results <==\n\n') psi4.print_out('\t => Occupation Determination <= \n\n') psi4.print_out('\t %6s %6s %6s %6s %6s %6s\n' %('N', 'Na', 'Nb', 'Charge', 'Mult', 'H**O')) psi4.print_out('\t Neutral: %6d %6d %6d %6d %6d %6d\n' %(N, Na, Nb, charge0, mult0, H**O)) psi4.print_out('\t Cation: %6d %6d %6d %6d %6d\n\n' %(N-1, Na1, Nb1, charge1, mult1)) psi4.print_out('\t => Regula Falsi Iterations <=\n\n') psi4.print_out('\t%3s %11s %14s %14s %14s %s\n' % ('N','Omega','IP','kIP','Delta','Type')) for k in range(len(omegas)): psi4.print_out('\t%3d %11.3E %14.6E %14.6E %14.6E %s\n' % (k+1,omegas[k],IPs[k],kIPs[k],IPs[k] - kIPs[k], types[k])) if (converged): psi4.print_out('\n\tIP Fitting Converged\n') psi4.print_out('\tFinal omega = %14.6E\n' % ((omega_l + omega_r) / 2)) psi4.print_out('\n\t"M,I. does the dying. Fleet just does the flying."\n') psi4.print_out('\t\t\t-Starship Troopers\n') else: psi4.print_out('\n\tIP Fitting did not converge!\n') psi4.set_global_option("DF_INTS_IO", "NONE") psi4.set_global_option("GUESS", old_guess)
def run_gaussian_2(name, **kwargs): # throw an exception for open-shells if (psi4.get_option('SCF','REFERENCE') != 'RHF' ): raise ValidationError("""g2 computations require "reference rhf".""") # stash user options: optstash = p4util.OptionsState( ['FNOCC','COMPUTE_TRIPLES'], ['FNOCC','COMPUTE_MP4_TRIPLES'], ['FREEZE_CORE'], ['MP2_TYPE'], ['SCF','SCF_TYPE']) # override default scf_type psi4.set_local_option('SCF','SCF_TYPE','PK') # optimize geometry at scf level psi4.clean() psi4.set_global_option('BASIS',"6-31G(D)") driver.optimize('scf') psi4.clean() # scf frequencies for zpe # NOTE This line should not be needed, but without it there's a seg fault scf_e, ref = driver.frequency('scf', return_wfn=True) # thermodynamic properties du = psi4.get_variable('INTERNAL ENERGY CORRECTION') dh = psi4.get_variable('ENTHALPY CORRECTION') dg = psi4.get_variable('GIBBS FREE ENERGY CORRECTION') freqs = ref.frequencies() nfreq = freqs.dim(0) freqsum = 0.0 for i in range(0, nfreq): freqsum += freqs.get(i) zpe = freqsum / p4const.psi_hartree2wavenumbers * 0.8929 * 0.5 psi4.clean() # optimize geometry at mp2 (no frozen core) level # note: freeze_core isn't an option in MP2 psi4.set_global_option('FREEZE_CORE',"FALSE") psi4.set_global_option('MP2_TYPE', 'CONV') driver.optimize('mp2') psi4.clean() # qcisd(t) psi4.set_local_option('FNOCC','COMPUTE_MP4_TRIPLES',"TRUE") psi4.set_global_option('FREEZE_CORE',"TRUE") psi4.set_global_option('BASIS',"6-311G(D_P)") ref = driver.proc.run_fnocc('qcisd(t)', return_wfn=True, **kwargs) # HLC: high-level correction based on number of valence electrons nirrep = ref.nirrep() frzcpi = ref.frzcpi() nfzc = 0 for i in range (0,nirrep): nfzc += frzcpi[i] nalpha = ref.nalpha() - nfzc nbeta = ref.nbeta() - nfzc # hlc of gaussian-2 hlc = -0.00481 * nalpha -0.00019 * nbeta # hlc of gaussian-1 hlc1 = -0.00614 * nalpha eqci_6311gdp = psi4.get_variable("QCISD(T) TOTAL ENERGY") emp4_6311gd = psi4.get_variable("MP4 TOTAL ENERGY") emp2_6311gd = psi4.get_variable("MP2 TOTAL ENERGY") psi4.clean() # correction for diffuse functions psi4.set_global_option('BASIS',"6-311+G(D_P)") driver.energy('mp4') emp4_6311pg_dp = psi4.get_variable("MP4 TOTAL ENERGY") emp2_6311pg_dp = psi4.get_variable("MP2 TOTAL ENERGY") psi4.clean() # correction for polarization functions psi4.set_global_option('BASIS',"6-311G(2DF_P)") driver.energy('mp4') emp4_6311g2dfp = psi4.get_variable("MP4 TOTAL ENERGY") emp2_6311g2dfp = psi4.get_variable("MP2 TOTAL ENERGY") psi4.clean() # big basis mp2 psi4.set_global_option('BASIS',"6-311+G(3DF_2P)") #run_fnocc('_mp2',**kwargs) driver.energy('mp2') emp2_big = psi4.get_variable("MP2 TOTAL ENERGY") psi4.clean() eqci = eqci_6311gdp e_delta_g2 = emp2_big + emp2_6311gd - emp2_6311g2dfp - emp2_6311pg_dp e_plus = emp4_6311pg_dp - emp4_6311gd e_2df = emp4_6311g2dfp - emp4_6311gd eg2 = eqci + e_delta_g2 + e_plus + e_2df eg2_mp2_0k = eqci + (emp2_big - emp2_6311gd) + hlc + zpe psi4.print_out('\n') psi4.print_out(' ==> G1/G2 Energy Components <==\n') psi4.print_out('\n') psi4.print_out(' QCISD(T): %20.12lf\n' % eqci) psi4.print_out(' E(Delta): %20.12lf\n' % e_delta_g2) psi4.print_out(' E(2DF): %20.12lf\n' % e_2df) psi4.print_out(' E(+): %20.12lf\n' % e_plus) psi4.print_out(' E(G1 HLC): %20.12lf\n' % hlc1) psi4.print_out(' E(G2 HLC): %20.12lf\n' % hlc) psi4.print_out(' E(ZPE): %20.12lf\n' % zpe) psi4.print_out('\n') psi4.print_out(' ==> 0 Kelvin Results <==\n') psi4.print_out('\n') eg2_0k = eg2 + zpe + hlc psi4.print_out(' G1: %20.12lf\n' % (eqci + e_plus + e_2df + hlc1 + zpe)) psi4.print_out(' G2(MP2): %20.12lf\n' % eg2_mp2_0k) psi4.print_out(' G2: %20.12lf\n' % eg2_0k) psi4.set_variable("G1 TOTAL ENERGY",eqci + e_plus + e_2df + hlc1 + zpe) psi4.set_variable("G2 TOTAL ENERGY",eg2_0k) psi4.set_variable("G2(MP2) TOTAL ENERGY",eg2_mp2_0k) psi4.print_out('\n') T = psi4.get_global_option('T') psi4.print_out(' ==> %3.0lf Kelvin Results <==\n'% T) psi4.print_out('\n') internal_energy = eg2_mp2_0k + du - zpe / 0.8929 enthalpy = eg2_mp2_0k + dh - zpe / 0.8929 gibbs = eg2_mp2_0k + dg - zpe / 0.8929 psi4.print_out(' G2(MP2) energy: %20.12lf\n' % internal_energy ) psi4.print_out(' G2(MP2) enthalpy: %20.12lf\n' % enthalpy) psi4.print_out(' G2(MP2) free energy: %20.12lf\n' % gibbs) psi4.print_out('\n') psi4.set_variable("G2(MP2) INTERNAL ENERGY",internal_energy) psi4.set_variable("G2(MP2) ENTHALPY",enthalpy) psi4.set_variable("G2(MP2) FREE ENERGY",gibbs) internal_energy = eg2_0k + du - zpe / 0.8929 enthalpy = eg2_0k + dh - zpe / 0.8929 gibbs = eg2_0k + dg - zpe / 0.8929 psi4.print_out(' G2 energy: %20.12lf\n' % internal_energy ) psi4.print_out(' G2 enthalpy: %20.12lf\n' % enthalpy) psi4.print_out(' G2 free energy: %20.12lf\n' % gibbs) psi4.set_variable("CURRENT ENERGY",eg2_0k) psi4.set_variable("G2 INTERNAL ENERGY",internal_energy) psi4.set_variable("G2 ENTHALPY",enthalpy) psi4.set_variable("G2 FREE ENERGY",gibbs) psi4.clean() optstash.restore() # return 0K g2 results return eg2_0k
def _set_convergence_criterion(ptype, method_name, scf_Ec, pscf_Ec, scf_Dc, pscf_Dc, gen_Ec, verbose=1): r""" This function will set local SCF and global energy convergence criterion to the defaults listed at: http://www.psicode.org/psi4manual/master/scf.html#convergence-and- algorithm-defaults. SCF will be converged more tightly if a post-SCF method is select (pscf_Ec, and pscf_Dc) else the looser (scf_Ec, and scf_Dc convergence criterion will be used). ptype - Procedure type (energy, gradient, etc). Nearly always test on procedures['energy'] since that's guaranteed to exist for a method. method_name - Name of the method scf_Ec - E convergence criterion for scf target method pscf_Ec - E convergence criterion for scf of post-scf target method scf_Dc - D convergence criterion for scf target method pscf_Dc - D convergence criterion for scf of post-scf target method gen_Ec - E convergence criterion for post-scf target method """ optstash = p4util.OptionsState( ['SCF', 'E_CONVERGENCE'], ['SCF', 'D_CONVERGENCE'], ['E_CONVERGENCE']) # Kind of want to move this out of here _method_exists(ptype, method_name) if verbose >= 2: print(' Setting convergence', end=' ') # Set method-dependent scf convergence criteria, check against energy routines if not psi4.has_option_changed('SCF', 'E_CONVERGENCE'): if procedures['energy'][method_name] in [proc.run_scf, proc.run_dft]: psi4.set_local_option('SCF', 'E_CONVERGENCE', scf_Ec) if verbose >= 2: print(scf_Ec, end=' ') else: psi4.set_local_option('SCF', 'E_CONVERGENCE', pscf_Ec) if verbose >= 2: print(pscf_Ec, end=' ') else: if verbose >= 2: print('CUSTOM', psi4.get_option('SCF', 'E_CONVERGENCE'), end=' ') if not psi4.has_option_changed('SCF', 'D_CONVERGENCE'): if procedures['energy'][method_name] in [proc.run_scf, proc.run_dft]: psi4.set_local_option('SCF', 'D_CONVERGENCE', scf_Dc) if verbose >= 2: print(scf_Dc, end=' ') else: psi4.set_local_option('SCF', 'D_CONVERGENCE', pscf_Dc) if verbose >= 2: print(pscf_Dc, end=' ') else: if verbose >= 2: print('CUSTOM', psi4.get_option('SCF', 'D_CONVERGENCE'), end=' ') # Set post-scf convergence criteria (global will cover all correlated modules) if not psi4.has_global_option_changed('E_CONVERGENCE'): if procedures['energy'][method_name] not in [proc.run_scf, proc.run_dft]: psi4.set_global_option('E_CONVERGENCE', gen_Ec) if verbose >= 2: print(gen_Ec, end=' ') else: if procedures['energy'][method_name] not in [proc.run_scf, proc.run_dft]: if verbose >= 2: print('CUSTOM', psi4.get_global_option('E_CONVERGENCE'), end=' ') if verbose >= 2: print('') return optstash