Пример #1
0
def test_pcmsolver():
    """pcmsolver/scf"""
    #! pcm

    nucenergy   =  12.0367196636183458
    polenergy   =  -0.0053060443528559
    totalenergy = -55.4559426361734040

    NH3 = psi4.geometry("""
    symmetry c1
    N     -0.0000000001    -0.1040380466      0.0000000000
    H     -0.9015844116     0.4818470201     -1.5615900098
    H     -0.9015844116     0.4818470201      1.5615900098
    H      1.8031688251     0.4818470204      0.0000000000
    units bohr
    no_reorient
    no_com
    """)

    psi4.set_options({
      'basis': 'STO-3G',
      'scf_type': 'pk',
      'pcm': True,
      'pcm_scf_type': 'total',
    })

    psi4.pcm_helper("""
       Units = Angstrom
       Medium {
       SolverType = IEFPCM
       Solvent = Water
       }

       Cavity {
       RadiiSet = UFF
       Type = GePol
       Scaling = False
       Area = 0.3
       Mode = Implicit
       }
    """)

    print('RHF-PCM, total algorithm')
    energy_scf1, wfn1 = psi4.energy('scf', return_wfn=True)
    assert psi4.compare_values(nucenergy, NH3.nuclear_repulsion_energy(), 10, "Nuclear repulsion energy (PCM, total algorithm)") #TEST
    assert psi4.compare_values(totalenergy, energy_scf1, 10, "Total energy (PCM, total algorithm)") #TEST
    assert psi4.compare_values(polenergy, wfn1.get_variable("PCM POLARIZATION ENERGY"), 6, "Polarization energy (PCM, total algorithm)") #TEST

    psi4.set_options({'pcm_scf_type': 'separate'})
    print('RHF-PCM, separate algorithm')
    energy_scf2 = psi4.energy('scf')
    assert psi4.compare_values(totalenergy, energy_scf2, 10, "Total energy (PCM, separate algorithm)")
    assert psi4.compare_values(polenergy, psi4.get_variable("PCM POLARIZATION ENERGY"), 6, "Polarization energy (PCM, separate algorithm)")

    # Now force use of UHF on NH3 to check sanity of the algorithm with PCM
    psi4.set_options({'pcm_scf_type': 'total', 'reference': 'uhf'})
    print('UHF-PCM, total algorithm')
    energy_scf3 = psi4.energy('scf')
    assert psi4.compare_values(totalenergy, energy_scf3, 10, "Total energy (PCM, separate algorithm)")
    assert psi4.compare_values(polenergy, psi4.get_variable("PCM POLARIZATION ENERGY"), 6, "Polarization energy (PCM, separate algorithm)")
Пример #2
0
def test_mrcc():
    """mrcc/ccsdt"""
    #! CCSDT cc-pVDZ energy for the H2O molecule using MRCC

    h2o = psi4.geometry("""
        o
        h 1 1.0
        h 1 1.0 2 104.5
    """)

    psi4.set_options({'basis': 'cc-pvdz', 'freeze_core': 'true'})

    psi4.energy('mrccsdt')

    assert psi4.compare_values(8.801465529972,
                               psi4.get_variable("NUCLEAR REPULSION ENERGY"),
                               6, 'NRE')
    assert psi4.compare_values(-76.021418445155,
                               psi4.get_variable("SCF TOTAL ENERGY"), 6, 'SCF')
    assert psi4.compare_values(-0.204692406830,
                               psi4.get_variable("MP2 CORRELATION ENERGY"), 6,
                               'MP2 correlation')
    assert psi4.compare_values(-0.217715210258,
                               psi4.get_variable("CCSDT CORRELATION ENERGY"),
                               6, 'CCSDT correlation')
    assert psi4.compare_values(-76.239133655413,
                               psi4.get_variable("CURRENT ENERGY"), 6, 'CCSDT')
Пример #3
0
def test_psi4_cc():
    """cc1"""
    #! RHF-CCSD 6-31G** all-electron optimization of the H2O molecule

    psi4.core.clean()
    h2o = psi4.geometry("""
        O
        H 1 0.97
        H 1 0.97 2 103.0
    """)

    psi4.set_options({"basis": '6-31G**'})

    psi4.optimize('ccsd')

    refnuc = 9.1654609427539
    refscf = -76.0229427274435
    refccsd = -0.20823570806196
    reftotal = -76.2311784355056

    assert psi4.compare_values(refnuc, h2o.nuclear_repulsion_energy(), 3,
                               "Nuclear repulsion energy")
    assert psi4.compare_values(refscf, psi4.get_variable("SCF total energy"),
                               5, "SCF energy")
    assert psi4.compare_values(refccsd,
                               psi4.get_variable("CCSD correlation energy"), 4,
                               "CCSD contribution")
    assert psi4.compare_values(reftotal, psi4.get_variable("Current energy"),
                               7, "Total energy")
Пример #4
0
def run_vibronic(state1,state2,method1='ccsd',method2='eom-ccsd'):
    """
    Performs the different steps needed to compute the spectrum
    """

    lowermethod1 = method1.lower()
    lowermethod2 = method2.lower()

    # Perform optimizations and save states 
    psi4.set_active_molecule(state1)
    print "Optimizing Ground State..."
    optimize(lowermethod1)
    E1=psi4.get_variable("CURRENT ENERGY")

    psi4.set_active_molecule(state2)
    print "Optimizing Excited State..."
    optimize(lowermethod2)
    E2=psi4.get_variable("CURRENT ENERGY")
    
    # Compute Hessian on first state (for AS model)
    psi4.set_active_molecule(state1)
    frequencies(lowermethod1)
    
    # Select states for vibronic:
    #  active molecule is initial state
    #  secondary molecule is final state
    psi4.set_active_molecule(state1)
    psi4.set_secondary_molecule(state2)
    
    # Compute adiavatic energy
    DE = (E2-E1)
    psi4.set_variable("CURRENT ENERGY",DE)

    # Call the plugin
    psi4.plugin('vibronic.so')
Пример #5
0
def disabled_test_forte():
    """aci-10: Perform aci on benzyne"""

    import forte

    refscf    = -229.20378006852584
    refaci    = -229.359450812283
    refacipt2 = -229.360444943286

    mbenzyne = psi4.geometry("""
      0 1
       C   0.0000000000  -2.5451795941   0.0000000000
       C   0.0000000000   2.5451795941   0.0000000000
       C  -2.2828001669  -1.3508352528   0.0000000000
       C   2.2828001669  -1.3508352528   0.0000000000
       C   2.2828001669   1.3508352528   0.0000000000
       C  -2.2828001669   1.3508352528   0.0000000000
       H  -4.0782187459  -2.3208602146   0.0000000000
       H   4.0782187459  -2.3208602146   0.0000000000
       H   4.0782187459   2.3208602146   0.0000000000
       H  -4.0782187459   2.3208602146   0.0000000000

      units bohr
    """)

    psi4.set_options({
       'basis': 'DZ',
       'df_basis_mp2': 'cc-pvdz-ri',
       'reference': 'uhf',
       'scf_type': 'pk',
       'd_convergence': 10,
       'e_convergence': 12,
       'guess': 'gwh',
    })

    psi4.set_module_options("FORTE", {
      'root_sym': 0,
      'frozen_docc':     [2,1,0,0,0,0,2,1],
      'restricted_docc': [3,2,0,0,0,0,2,3],
      'active':          [1,0,1,2,1,2,1,0],
      'multiplicity': 1,
      'aci_nroot': 1,
      'job_type': 'aci',
      'sigma': 0.001,
      'aci_select_type': 'aimed_energy',
      'aci_spin_projection': 1,
      'aci_enforce_spin_complete': True,
      'aci_add_aimed_degenerate': False,
      'aci_project_out_spin_contaminants': False,
      'diag_algorithm': 'full',
      'aci_quiet_mode': True,
    })

    scf = psi4.energy('scf')
    assert psi4.compare_values(refscf, scf,10,"SCF Energy")

    psi4.energy('forte')
    assert psi4.compare_values(refaci, psi4.get_variable("ACI ENERGY"),10,"ACI energy")
    assert psi4.compare_values(refacipt2, psi4.get_variable("ACI+PT2 ENERGY"),8,"ACI+PT2 energy")
Пример #6
0
def disabled_test_forte():
    """aci-10: Perform aci on benzyne"""

    import forte

    refscf    = -229.20378006852584
    refaci    = -229.359450812283
    refacipt2 = -229.360444943286

    mbenzyne = psi4.geometry("""
      0 1
       C   0.0000000000  -2.5451795941   0.0000000000
       C   0.0000000000   2.5451795941   0.0000000000
       C  -2.2828001669  -1.3508352528   0.0000000000
       C   2.2828001669  -1.3508352528   0.0000000000
       C   2.2828001669   1.3508352528   0.0000000000
       C  -2.2828001669   1.3508352528   0.0000000000
       H  -4.0782187459  -2.3208602146   0.0000000000
       H   4.0782187459  -2.3208602146   0.0000000000
       H   4.0782187459   2.3208602146   0.0000000000
       H  -4.0782187459   2.3208602146   0.0000000000

      units bohr
    """)

    psi4.set_options({
       'basis': 'DZ',
       'df_basis_mp2': 'cc-pvdz-ri',
       'reference': 'uhf',
       'scf_type': 'pk',
       'd_convergence': 10,
       'e_convergence': 12,
       'guess': 'gwh',
    })

    psi4.set_module_options("FORTE", {
      'root_sym': 0,
      'frozen_docc':     [2,1,0,0,0,0,2,1],
      'restricted_docc': [3,2,0,0,0,0,2,3],
      'active':          [1,0,1,2,1,2,1,0],
      'multiplicity': 1,
      'aci_nroot': 1,
      'job_type': 'aci',
      'sigma': 0.001,
      'aci_select_type': 'aimed_energy',
      'aci_spin_projection': 1,
      'aci_enforce_spin_complete': True,
      'aci_add_aimed_degenerate': False,
      'aci_project_out_spin_contaminants': False,
      'diag_algorithm': 'full',
      'aci_quiet_mode': True,
    })

    scf = psi4.energy('scf')
    assert psi4.compare_values(refscf, scf,10,"SCF Energy")

    psi4.energy('forte')
    assert psi4.compare_values(refaci, psi4.get_variable("ACI ENERGY"),10,"ACI energy")
    assert psi4.compare_values(refacipt2, psi4.get_variable("ACI+PT2 ENERGY"),8,"ACI+PT2 energy")
Пример #7
0
def test_psi4_sapt():
    """sapt1"""
    #! SAPT0 cc-pVDZ computation of the ethene-ethyne interaction energy, using the cc-pVDZ-JKFIT RI basis for SCF
    #! and cc-pVDZ-RI for SAPT.  Monomer geometries are specified using Cartesian coordinates.

    Eref = [
        85.1890645313, -0.00359915058, 0.00362911158, -0.00083137117,
        -0.00150542374, -0.00230683391
    ]

    ethene_ethyne = psi4.geometry("""
         0 1
         C     0.000000    -0.667578    -2.124659
         C     0.000000     0.667578    -2.124659
         H     0.923621    -1.232253    -2.126185
         H    -0.923621    -1.232253    -2.126185
         H    -0.923621     1.232253    -2.126185
         H     0.923621     1.232253    -2.126185
         --
         0 1
         C     0.000000     0.000000     2.900503
         C     0.000000     0.000000     1.693240
         H     0.000000     0.000000     0.627352
         H     0.000000     0.000000     3.963929
         units angstrom
    """)

    # this molecule will crash test if molecule passing broken
    barrier = psi4.geometry("""
     0 1
     He
    """)

    psi4.set_options({
        "basis": "cc-pvdz",
        "guess": "sad",
        "scf_type": "df",
        "sad_print": 2,
        "d_convergence": 11,
        "puream": True,
        "print": 1
    })

    psi4.energy('sapt0', molecule=ethene_ethyne)

    Eelst = psi4.get_variable("SAPT ELST ENERGY")
    Eexch = psi4.get_variable("SAPT EXCH ENERGY")
    Eind = psi4.get_variable("SAPT IND ENERGY")
    Edisp = psi4.get_variable("SAPT DISP ENERGY")
    ET = psi4.get_variable("SAPT0 TOTAL ENERGY")

    assert psi4.compare_values(Eref[0],
                               ethene_ethyne.nuclear_repulsion_energy(), 9,
                               "Nuclear Repulsion Energy")
    assert psi4.compare_values(Eref[1], Eelst, 6, "SAPT0 Eelst")
    assert psi4.compare_values(Eref[2], Eexch, 6, "SAPT0 Eexch")
    assert psi4.compare_values(Eref[3], Eind, 6, "SAPT0 Eind")
    assert psi4.compare_values(Eref[4], Edisp, 6, "SAPT0 Edisp")
    assert psi4.compare_values(Eref[5], ET, 6, "SAPT0 Etotal")
Пример #8
0
def test_v2rdm_casscf():
    """v2rdm_casscf/tests/v2rdm1"""
    #! cc-pvdz N2 (6,6) active space Test DQG

    print(
        '        N2 / cc-pVDZ / DQG(6,6), scf_type = CD / 1e-12, rNN = 0.5 A')

    import v2rdm_casscf

    n2 = psi4.geometry("""
    0 1
    n
    n 1 r
    """)

    interloper = psi4.geometry("""
    0 1
    O
    H 1 1.0
    H 1 1.0 2 90.0
    """)

    psi4.set_options({
        'basis': 'cc-pvdz',
        'scf_type': 'cd',
        'cholesky_tolerance': 1e-12,
        'd_convergence': 1e-10,
        'maxiter': 500,
        'restricted_docc': [2, 0, 0, 0, 0, 2, 0, 0],
        'active': [1, 0, 1, 1, 0, 1, 1, 1],
    })
    psi4.set_module_options(
        'v2rdm_casscf',
        {
            'positivity': 'dqg',
            'r_convergence': 1e-5,
            'e_convergence': 1e-6,
            'maxiter': 20000,
            #'orbopt_frequency': 1000,
            #'mu_update_frequency': 1000,
        })

    psi4.activate(n2)

    n2.r = 0.5
    refscf = -103.04337420425350
    refv2rdm = -103.086205379481

    psi4.energy('v2rdm-casscf', molecule=n2)

    assert psi4.compare_values(refscf, psi4.get_variable("SCF TOTAL ENERGY"),
                               8, "SCF total energy")
    assert psi4.compare_values(refv2rdm, psi4.get_variable("CURRENT ENERGY"),
                               5, "v2RDM-CASSCF total energy")
Пример #9
0
def test_psi4_sapt():
    """sapt1"""
    #! SAPT0 cc-pVDZ computation of the ethene-ethyne interaction energy, using the cc-pVDZ-JKFIT RI basis for SCF
    #! and cc-pVDZ-RI for SAPT.  Monomer geometries are specified using Cartesian coordinates.

    Eref = [ 85.189064196429101,  -0.00359915058,  0.00362911158,
             -0.00083137117,      -0.00150542374, -0.00230683391 ]

    ethene_ethyne = psi4.geometry("""
         0 1
         C     0.000000    -0.667578    -2.124659
         C     0.000000     0.667578    -2.124659
         H     0.923621    -1.232253    -2.126185
         H    -0.923621    -1.232253    -2.126185
         H    -0.923621     1.232253    -2.126185
         H     0.923621     1.232253    -2.126185
         --
         0 1
         C     0.000000     0.000000     2.900503
         C     0.000000     0.000000     1.693240
         H     0.000000     0.000000     0.627352
         H     0.000000     0.000000     3.963929
         units angstrom
    """)

    # this molecule will crash test if molecule passing broken
    barrier = psi4.geometry("""
     0 1
     He
    """)

    psi4.set_options({
        "basis": "cc-pvdz",
        "guess": "sad",
        "scf_type": "df",
        "sad_print": 2,
        "d_convergence": 11,
        "puream": True,
        "print": 1})

    psi4.energy('sapt0', molecule=ethene_ethyne)

    Eelst = psi4.get_variable("SAPT ELST ENERGY")
    Eexch = psi4.get_variable("SAPT EXCH ENERGY")
    Eind  = psi4.get_variable("SAPT IND ENERGY")
    Edisp = psi4.get_variable("SAPT DISP ENERGY")
    ET    = psi4.get_variable("SAPT0 TOTAL ENERGY")

    assert psi4.compare_values(Eref[0], ethene_ethyne.nuclear_repulsion_energy(), 9, "Nuclear Repulsion Energy")
    assert psi4.compare_values(Eref[1], Eelst, 6, "SAPT0 Eelst")
    assert psi4.compare_values(Eref[2], Eexch, 6, "SAPT0 Eexch")
    assert psi4.compare_values(Eref[3], Eind, 6, "SAPT0 Eind")
    assert psi4.compare_values(Eref[4], Edisp, 6, "SAPT0 Edisp")
    assert psi4.compare_values(Eref[5], ET, 6, "SAPT0 Etotal")
Пример #10
0
def test_v2rdm_casscf():
    """v2rdm_casscf/tests/v2rdm1"""
    #! cc-pvdz N2 (6,6) active space Test DQG

    print('        N2 / cc-pVDZ / DQG(6,6), scf_type = CD / 1e-12, rNN = 0.5 A')

    import v2rdm_casscf

    n2 = psi4.geometry("""
    0 1
    n
    n 1 r
    """)

    interloper = psi4.geometry("""
    0 1
    O
    H 1 1.0
    H 1 1.0 2 90.0
    """)

    psi4.set_options({
      'basis': 'cc-pvdz',
      'scf_type': 'cd',
      'cholesky_tolerance': 1e-12,
      'd_convergence': 1e-10,
      'maxiter': 500,
      'restricted_docc': [ 2, 0, 0, 0, 0, 2, 0, 0 ],
      'active': [ 1, 0, 1, 1, 0, 1, 1, 1 ],
    })
    ##psi4.set_module_options('v2rdm_casscf', {
    psi4.set_options({
    #  'positivity': 'dqg',
      'r_convergence': 1e-5,
      'e_convergence': 1e-6,
      'maxiter': 20000,
    #  #'orbopt_frequency': 1000,
    #  #'mu_update_frequency': 1000,
    })

    psi4.activate(n2)

    n2.r     = 0.5
    refscf   = -103.04337420425350
    refv2rdm = -103.086205379481

    psi4.energy('v2rdm-casscf', molecule=n2)

    assert psi4.compare_values(refscf, psi4.get_variable("SCF TOTAL ENERGY"), 8, "SCF total energy")
    assert psi4.compare_values(refv2rdm, psi4.get_variable("CURRENT ENERGY"), 5, "v2RDM-CASSCF total energy")
Пример #11
0
def run_v2rdm_casscf(name, **kwargs):
    r"""Function encoding sequence of PSI module and plugin calls so that
    v2rdm_casscf can be called via :py:func:`~driver.energy`. For post-scf plugins.

    >>> energy('v2rdm_casscf')

    """

    lowername = name.lower()
    kwargs = p4util.kwargs_lower(kwargs)

    optstash = p4util.OptionsState(['SCF', 'DF_INTS_IO'])

    psi4.set_local_option('SCF', 'DF_INTS_IO', 'SAVE')

    # Your plugin's psi4 run sequence goes here
    scf_wfn = scf_helper(name, **kwargs)

    # if restarting from a checkpoint file, this file
    # needs to be in scratch with the correct name
    filename = psi4.get_option("V2RDM_CASSCF", "RESTART_FROM_CHECKPOINT_FILE")

    # todo PSIF_V2RDM_CHECKPOINT should be definied in psifiles.h
    if (filename != ""):
        molname = psi4.wavefunction().molecule().name()
        p4util.copy_file_to_scratch(filename, 'psi', molname, 269, False)

    returnvalue = psi4.plugin('v2rdm_casscf.so', scf_wfn)

    #psi4.set_variable('CURRENT ENERGY', returnvalue)

    return psi4.get_variable('CURRENT ENERGY')
Пример #12
0
def run_gpu_dfcc(name, **kwargs):
    """Function encoding sequence of PSI module calls for
    a GPU-accelerated DF-CCSD(T) computation.

    >>> energy('df-ccsd(t)')

    """
    lowername = name.lower()
    kwargs = kwargs_lower(kwargs)

    # stash user options
    optstash = OptionsState(
        ['GPU_DFCC','COMPUTE_TRIPLES'],
        ['GPU_DFCC','DFCC'],
        ['GPU_DFCC','NAT_ORBS'],
        ['SCF','DF_INTS_IO'],
        ['SCF','SCF_TYPE'])

    psi4.set_local_option('SCF','DF_INTS_IO', 'SAVE')
    psi4.set_local_option('GPU_DFCC','DFCC', True)

    # throw an exception for open-shells
    if (psi4.get_option('SCF','REFERENCE') != 'RHF' ):
        raise ValidationError("Error: %s requires \"reference rhf\"." % lowername)

    # override symmetry:
    molecule = psi4.get_active_molecule()
    molecule.update_geometry()
    molecule.reset_point_group('c1')
    molecule.fix_orientation(1)
    molecule.update_geometry()

    # triples?
    if (lowername == 'gpu-df-ccsd'):
        psi4.set_local_option('GPU_DFCC','COMPUTE_TRIPLES', False)
    if (lowername == 'gpu-df-ccsd(t)'):
        psi4.set_local_option('GPU_DFCC','COMPUTE_TRIPLES', True)
    #if (lowername == 'fno-df-ccsd'):
    #    psi4.set_local_option('GPU_DFCC','COMPUTE_TRIPLES', False)
    #    psi4.set_local_option('GPU_DFCC','NAT_ORBS', True)
    #if (lowername == 'fno-df-ccsd(t)'):
    #    psi4.set_local_option('GPU_DFCC','COMPUTE_TRIPLES', True)
    #    psi4.set_local_option('GPU_DFCC','NAT_ORBS', True)

    # set scf-type to df unless the user wants something else
    if psi4.has_option_changed('SCF','SCF_TYPE') == False:
       psi4.set_local_option('SCF','SCF_TYPE', 'DF')

    if psi4.get_option('GPU_DFCC','DF_BASIS_CC') == '':
       basis   = psi4.get_global_option('BASIS')
       dfbasis = corresponding_rifit(basis)
       psi4.set_local_option('GPU_DFCC','DF_BASIS_CC',dfbasis)

    scf_helper(name,**kwargs)
    psi4.plugin('gpu_dfcc.so')

    # restore options
    optstash.restore()

    return psi4.get_variable("CURRENT ENERGY")
Пример #13
0
def run_v2rdm_casscf(name, **kwargs):
    r"""Function encoding sequence of PSI module and plugin calls so that
    v2rdm_casscf can be called via :py:func:`~driver.energy`. For post-scf plugins.

    >>> energy('v2rdm_casscf')

    """

    lowername = name.lower()
    kwargs = p4util.kwargs_lower(kwargs)

    optstash = p4util.OptionsState(
        ['SCF', 'DF_INTS_IO'])

    psi4.set_local_option('SCF', 'DF_INTS_IO', 'SAVE')

    # Your plugin's psi4 run sequence goes here
    scf_wfn = scf_helper(name, **kwargs)

    # if restarting from a checkpoint file, this file
    # needs to be in scratch with the correct name
    filename = psi4.get_option("V2RDM_CASSCF","RESTART_FROM_CHECKPOINT_FILE")

    # todo PSIF_V2RDM_CHECKPOINT should be definied in psifiles.h
    if ( filename != "" ):
        molname = psi4.wavefunction().molecule().name()
        p4util.copy_file_to_scratch(filename,'psi',molname,269,False)

    returnvalue = psi4.plugin('v2rdm_casscf.so',scf_wfn)

    #psi4.set_variable('CURRENT ENERGY', returnvalue)

    return psi4.get_variable('CURRENT ENERGY')
Пример #14
0
def test_mp2():
    """
    test for energies
    """
    ao_ints, test_scf_param, e_ZZ_repulsion = scf.init(\
        os.path.dirname(__file__) + "/test_mp2.yml")
    eps, C, D, F = scf.scf(ao_ints, test_scf_param, e_ZZ_repulsion)
    energy = scf.get_SCF_energy(ao_ints['H'], F, D, False) + e_ZZ_repulsion

    # psi4 setup
    import psi4
    mol = psi4.geometry("""
    O
    H 1 1.1
    H 1 1.1 2 104
    """)
    mol.update_geometry()

    bas = psi4.core.BasisSet.build(mol, target="cc-pVDZ")
    mints = psi4.core.MintsHelper(bas)

    # DF-MP2
    psi4.set_options({"scf_type": "df"})
    psi4.set_options({"MP2_type": "CONV"})
    psi4_energy = psi4.energy("MP2/cc-pVDZ", molecule = mol)
    psi4_energy_MP2 = psi4.get_variable('SCS-MP2 TOTAL ENERGY')

    test_scf_param.update({"method": "MP2"})
    test_scf_param.update({"is_fitted": "True"})
    eps, C, D, F = scf.scf(ao_ints, test_scf_param, e_ZZ_repulsion)
    H = ao_ints['T'] + ao_ints['V']
    energy = np.sum((F+H)*D) + e_ZZ_repulsion
    energy_corr = mp2.get_mp2_energy(\
        eps, C, ao_ints['g4'], test_scf_param['nel_alpha'])
    assert(np.allclose(energy + energy_corr, psi4_energy_MP2) == True)
Пример #15
0
def test_v2rdm6():
    #! cc-pvdz N2 (6,6) active space Test DQG

    print('        N2 / cc-pVDZ / DQG(6,6), geometry optimization')

    import psi4

    n2 = psi4.geometry("""
    0 1
    n
    n 1 1.1
    """)

    psi4.set_options({
        'basis': 'cc-pvdz',
        'scf_type': 'pk',
        'd_convergence': 1e-10,
        'maxiter': 500,
        'restricted_docc': [2, 0, 0, 0, 0, 2, 0, 0],
        'active': [1, 0, 1, 1, 0, 1, 1, 1],
    })
    psi4.set_module_options(
        'v2rdm_casscf',
        {
            'positivity': 'dqg',
            #'r_convergence': 1e-7,
            'r_convergence': 1e-6,
            'e_convergence': 1e-5,
            'orbopt_gradient_convergence': 1e-8,
            'maxiter': 20000,
        })

    psi4.activate(n2)

    psi4.optimize('v2rdm-casscf')

    refnuc = 23.1968666562054260
    refscf = -108.95016246035139
    refv2rdm = -109.095505119442

    assert psi4.compare_values(refnuc, n2.nuclear_repulsion_energy(), 4,
                               "Nuclear repulsion energy")
    assert psi4.compare_values(refscf, psi4.get_variable("SCF TOTAL ENERGY"),
                               5, "SCF total energy")
    assert psi4.compare_values(refv2rdm, psi4.get_variable("CURRENT ENERGY"),
                               4, "v2RDM-CASSCF total energy")
Пример #16
0
def test_v2rdm2():
    #! cc-pvdz N2 (6,6) active space Test DQG

    print('        N2 / cc-pVDZ / DQG(6,6), scf_type = DF, rNN = 1.1 A')

    import psi4

    n2 = psi4.geometry("""
    0 1
    n
    n 1 r
    """)

    psi4.set_options({
        'basis': 'cc-pvdz',
        'scf_type': 'df',
        'd_convergence': 1e-10,
        'maxiter': 500,
        'restricted_docc': [2, 0, 0, 0, 0, 2, 0, 0],
        'active': [1, 0, 1, 1, 0, 1, 1, 1],
    })
    psi4.set_module_options(
        'v2rdm_casscf', {
            'positivity': 'dqg',
            'r_convergence': 1e-5,
            'e_convergence': 1e-6,
            'maxiter': 20000,
        })

    psi4.activate(n2)

    n2.r = 1.1
    refscf = -108.95348837831371
    refv2rdm = -109.094404909477

    psi4.energy('v2rdm-casscf')

    assert psi4.compare_values(refscf, psi4.get_variable("SCF TOTAL ENERGY"),
                               8, "SCF total energy")
    assert psi4.compare_values(refv2rdm, psi4.get_variable("CURRENT ENERGY"),
                               5, "v2RDM-CASSCF total energy")
Пример #17
0
def test_mrcc():
    """mrcc/ccsdt"""
    #! CCSDT cc-pVDZ energy for the H2O molecule using MRCC

    h2o = psi4.geometry("""
        o
        h 1 1.0
        h 1 1.0 2 104.5
    """)

    psi4.set_options({
        'basis': 'cc-pvdz',
        'freeze_core': 'true'})

    psi4.energy('mrccsdt')

    assert psi4.compare_values(  8.801465529972, psi4.get_variable("NUCLEAR REPULSION ENERGY"), 6, 'NRE')
    assert psi4.compare_values(-76.021418445155, psi4.get_variable("SCF TOTAL ENERGY"), 6, 'SCF')
    assert psi4.compare_values( -0.204692406830, psi4.get_variable("MP2 CORRELATION ENERGY") , 6, 'MP2 correlation')
    assert psi4.compare_values( -0.217715210258, psi4.get_variable("CCSDT CORRELATION ENERGY"), 6, 'CCSDT correlation')
    assert psi4.compare_values(-76.239133655413, psi4.get_variable("CURRENT ENERGY"), 6, 'CCSDT')
Пример #18
0
def test_cfour():
    """cfour/sp-rhf-ccsd_t_"""
    #! single-point CCSD(T)/qz2p on water

    print('        <<< Translation of ZMAT to Psi4 format to Cfour >>>')

    psi4.geometry("""
    O
    H 1 R
    H 1 R 2 A

    R=0.958
    A=104.5
    """)

    psi4.set_options({
    'cfour_CALC_level': 'CCSD(T)',
    'cfour_BASIS': 'qz2p',
    'cfour_SCF_CONV': 12,
    'cfour_CC_CONV': 12,
    })

    psi4.energy('cfour')

    assert psi4.compare_values(-76.062748460117, psi4.get_variable('scf total energy'), 6, 'SCF')
    assert psi4.compare_values(-76.332940127333, psi4.get_variable('mp2 total energy'), 6, 'MP2')
    assert psi4.compare_values(-76.338453951890, psi4.get_variable('ccsd total energy'), 6, 'CCSD')
    assert psi4.compare_values(-0.275705491773, psi4.get_variable('ccsd correlation energy'), 6, 'CCSD corl')
    assert psi4.compare_values(-76.345717549886, psi4.get_variable('ccsd(t) total energy'), 6, 'CCSD(T)')
    assert psi4.compare_values(-0.282969089769, psi4.get_variable('ccsd(t) correlation energy'), 6, 'CCSD(T) corl')
Пример #19
0
def test_cfour():
    """cfour/sp-rhf-ccsd_t_"""
    #! single-point CCSD(T)/qz2p on water

    print('        <<< Translation of ZMAT to Psi4 format to Cfour >>>')

    psi4.geometry("""
    O
    H 1 R
    H 1 R 2 A

    R=0.958
    A=104.5
    """)

    psi4.set_options({
    'cfour_CALC_level': 'CCSD(T)',
    'cfour_BASIS': 'qz2p',
    'cfour_SCF_CONV': 12,
    'cfour_CC_CONV': 12,
    })

    psi4.energy('cfour')

    assert psi4.compare_values(-76.062748460117, psi4.get_variable('scf total energy'), 6, 'SCF')
    assert psi4.compare_values(-76.332940127333, psi4.get_variable('mp2 total energy'), 6, 'MP2')
    assert psi4.compare_values(-76.338453951890, psi4.get_variable('ccsd total energy'), 6, 'CCSD')
    assert psi4.compare_values(-0.275705491773, psi4.get_variable('ccsd correlation energy'), 6, 'CCSD corl')
    assert psi4.compare_values(-76.345717549886, psi4.get_variable('ccsd(t) total energy'), 6, 'CCSD(T)')
    assert psi4.compare_values(-0.282969089769, psi4.get_variable('ccsd(t) correlation energy'), 6, 'CCSD(T) corl')
Пример #20
0
def test_snsmp2():
    """snsmp2/he-he"""

    HeHe = psi4.geometry("""
    0 1
    He 0 0 0
    --
    He 2 0 0
    """)

    e = psi4.energy('sns-mp2')

    assert psi4.compare_values(0.00176708227, psi4.get_variable('SNS-MP2 TOTAL ENERGY'), 5, "SNS-MP2 IE [Eh]")
Пример #21
0
def test_snsmp2():
    """snsmp2/he-he"""

    HeHe = psi4.geometry("""
    0 1
    He 0 0 0
    --
    He 2 0 0
    """)

    e = psi4.energy('sns-mp2')

    assert psi4.compare_values(0.00176708227, psi4.get_variable('SNS-MP2 TOTAL ENERGY'), 5, "SNS-MP2 IE [Eh]")
Пример #22
0
def test_psi4_basic():
    """tu1-h2o-energy"""
    #! Sample HF/cc-pVDZ H2O computation

    h2o = psi4.geometry("""
      O
      H 1 0.96
      H 1 0.96 2 104.5
    """)

    psi4.set_options({'basis': "cc-pVDZ"})
    psi4.energy('scf')

    assert psi4.compare_values(-76.0266327341067125, psi4.get_variable('SCF TOTAL ENERGY'), 6, 'SCF energy')
Пример #23
0
def test_psi4_basic():
    """tu1-h2o-energy"""
    #! Sample HF/cc-pVDZ H2O computation

    h2o = psi4.geometry("""
      O
      H 1 0.96
      H 1 0.96 2 104.5
    """)

    psi4.set_options({'basis': "cc-pVDZ"})
    psi4.energy('scf')

    assert psi4.compare_values(-76.0266327341067125, psi4.get_variable('SCF TOTAL ENERGY'), 6, 'SCF energy')
Пример #24
0
def test_psi4_cc():
    """cc1"""
    #! RHF-CCSD 6-31G** all-electron optimization of the H2O molecule

    psi4.core.clean()
    h2o = psi4.geometry("""
        O
        H 1 0.97
        H 1 0.97 2 103.0
    """)

    psi4.set_options({"basis": '6-31G**'})

    psi4.optimize('ccsd')

    refnuc   =   9.1654609427539
    refscf   = -76.0229427274435
    refccsd  = -0.20823570806196
    reftotal = -76.2311784355056

    assert psi4.compare_values(refnuc,   h2o.nuclear_repulsion_energy(), 3, "Nuclear repulsion energy")
    assert psi4.compare_values(refscf,   psi4.get_variable("SCF total energy"), 5, "SCF energy")
    assert psi4.compare_values(refccsd,  psi4.get_variable("CCSD correlation energy"), 4, "CCSD contribution")
    assert psi4.compare_values(reftotal, psi4.get_variable("Current energy"), 7, "Total energy")
Пример #25
0
def test_chemps2():
    """chemps2/scf-n2"""
    #! dmrg-scf on N2

    N2 = psi4.geometry("""
      N       0.0000   0.0000   0.0000
      N       0.0000   0.0000   2.1180
    units au
    """)

    psi4.set_options({
    'basis': 'cc-pVDZ',
    'reference': 'rhf',
    'e_convergence': 1e-12,
    'd_convergence': 1e-12,

    'dmrg_irrep': 0,
    'dmrg_multiplicity': 1,
    'restricted_docc': [ 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 ],
    'active': [ 2 , 0 , 1 , 1 , 0 , 2 , 1 , 1 ],

    'dmrg_sweep_states': [   500,  1000,  1000 ],
    'dmrg_sweep_energy_conv': [ 1e-10, 1e-10, 1e-10 ],
    'dmrg_sweep_dvdson_rtol': [  1e-4,  1e-6,  1e-8 ],
    'dmrg_sweep_max_sweeps': [     5,     5,    10 ],
    'dmrg_sweep_noise_prefac': [  0.05,  0.05,   0.0 ],
    'dmrg_print_corr': True,
    'dmrg_mps_write': False,

    'dmrg_unitary_write': True,
    'dmrg_diis': True,
    'dmrg_scf_diis_thr': 1e-2,
    'dmrg_diis_write': True,

    'dmrg_excitation': 0,   # Ground state
    'dmrg_scf_state_avg': False,
    'dmrg_scf_active_space': 'NO',  # INPUT; NO; LOC
    'dmrg_local_init': False,
    })

    psi4.energy("dmrg-scf")

    ref_energy = -109.1035023353
    assert psi4.compare_values(ref_energy, psi4.get_variable("CURRENT ENERGY"), 6, "DMRG Energy")
Пример #26
0
def test_chemps2():
    """chemps2/scf-n2"""
    #! dmrg-scf on N2

    N2 = psi4.geometry("""
      N       0.0000   0.0000   0.0000
      N       0.0000   0.0000   2.1180
    units au
    """)

    psi4.set_options({
    'basis': 'cc-pVDZ',
    'reference': 'rhf',
    'e_convergence': 1e-12,
    'd_convergence': 1e-12,

    'dmrg_irrep': 0,
    'dmrg_multiplicity': 1,
    'restricted_docc': [ 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 ],
    'active': [ 2 , 0 , 1 , 1 , 0 , 2 , 1 , 1 ],

    'dmrg_sweep_states': [   500,  1000,  1000 ],
    'dmrg_sweep_energy_conv': [ 1e-10, 1e-10, 1e-10 ],
    'dmrg_sweep_dvdson_rtol': [  1e-4,  1e-6,  1e-8 ],
    'dmrg_sweep_max_sweeps': [     5,     5,    10 ],
    'dmrg_sweep_noise_prefac': [  0.05,  0.05,   0.0 ],
    'dmrg_print_corr': True,
    'dmrg_mps_write': False,

    'dmrg_unitary_write': True,
    'dmrg_diis': True,
    'dmrg_scf_diis_thr': 1e-2,
    'dmrg_diis_write': True,

    'dmrg_excitation': 0,   # Ground state
    'dmrg_scf_state_avg': False,
    'dmrg_scf_active_space': 'NO',  # INPUT; NO; LOC
    'dmrg_local_init': False,
    })

    psi4.energy("dmrg-scf")

    ref_energy = -109.1035023353
    assert psi4.compare_values(ref_energy, psi4.get_variable("CURRENT ENERGY"), 6, "DMRG Energy")
Пример #27
0
def test_libefp():
    """libefp/qchem-qmefp-sp"""
    #! EFP on mixed QM (water) and EFP (water + 2 * ammonia) system.
    #! An EFP-only calc performed first to test vales against q-chem.

    qmefp = psi4.geometry("""
    # QM fragment
    0 1
    units bohr
    O1     0.000000000000     0.000000000000     0.224348285559
    H2    -1.423528800232     0.000000000000    -0.897393142237
    H3     1.423528800232     0.000000000000    -0.897393142237
    # EFP as EFP fragments
    --
    efp h2o -4.014110144291     2.316749370493    -1.801514729931 -2.902133 1.734999 -1.953647
    --
    efp NH3,1.972094713645,,3.599497221584 ,    5.447701074734 -1.105309 2.033306 -1.488582
    --
    efp NH3 -7.876296399270    -1.854372164887    -2.414804197762  2.526442 1.658262 -2.742084
    """)

    #  <<<  EFP calc  >>>
    psi4.set_options({
        'basis': '6-31g*',
        'scf_type': 'pk',
        'guess': 'core',
        'df_scf_guess': False})

    psi4.energy('efp')
    assert psi4.compare_values( 9.1793879214, qmefp.nuclear_repulsion_energy(), 6, 'QM NRE')
    assert psi4.compare_values(-0.0004901368, psi4.get_variable('efp elst energy'), 6, 'EFP-EFP Elst')  # from q-chem
    assert psi4.compare_values(-0.0003168768, psi4.get_variable('efp ind energy'), 6, 'EFP-EFP Indc')
    assert psi4.compare_values(-0.0021985285, psi4.get_variable('efp disp energy'), 6, 'EFP-EFP Disp')  # from q-chem
    assert psi4.compare_values( 0.0056859871, psi4.get_variable('efp exch energy'), 6, 'EFP-EFP Exch')  # from q-chem
    assert psi4.compare_values( 0.0026804450, psi4.get_variable('efp total energy'), 6, 'EFP-EFP Totl')
    assert psi4.compare_values( 0.0026804450, psi4.get_variable('current energy'), 6, 'Current')
    psi4.core.print_variables()

    psi4.core.clean()
    psi4.core.clean_variables()

    #  <<<  QM + EFP calc  >>>
    psi4.set_options({
        'e_convergence': 12,
        'd_convergence': 12})
    psi4.energy('scf')

    assert psi4.compare_values( 9.1793879214, qmefp.nuclear_repulsion_energy(), 6, 'QM NRE')
    assert psi4.compare_values( 0.2622598847, psi4.get_variable('efp total energy') - psi4.get_variable('efp ind energy'), 6, 'EFP corr to SCF')  # from q-chem
    assert psi4.compare_values(-0.0117694790, psi4.get_variable('efp ind energy'), 6, 'QM-EFP Indc')  # from q-chem
    assert psi4.compare_values(-0.0021985285, psi4.get_variable('efp disp energy'), 6, 'EFP-EFP Disp')  # from q-chem
    assert psi4.compare_values( 0.0056859871, psi4.get_variable('efp exch energy'), 6, 'EFP-EFP Exch')  # from q-chem
    assert psi4.compare_values( 0.2504904057, psi4.get_variable('efp total energy'), 6, 'EFP-EFP Totl')  # from q-chem
    assert psi4.compare_values(-76.0139362744, psi4.get_variable('scf total energy'), 6, 'SCF')  # from q-chem
    psi4.core.print_variables()
Пример #28
0
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)

    # Flip this off for now, needs more testing
    # 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]))

            # Flip this off for now, needs more testing
            #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_body_dict = 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
Пример #29
0
def test_psi4_scfproperty():
    """scf-property"""
    #! UFH and B3LYP cc-pVQZ properties for the CH2 molecule.

    with open('grid.dat', 'w') as handle:
        handle.write("""\
0.0  0.0  0.0
1.1  1.3  1.4
""")

    ch2 = psi4.geometry("""
        0 3
        c
        h 1 b1
        h 1 b1 2 a1

        b1 = 1.0
        a1 = 125.0
    """)

    # Get a reasonable guess, to save some iterations
    psi4.set_options({
        "scf_type": "pk",
        "basis": "6-31G**",
        "e_convergence": 8,
        "docc": [2, 0, 0, 1],
        "socc": [1, 0, 1, 0],
        "reference": "uhf"})

    ch2.update_geometry()
    assert psi4.compare_values(6.648418918908746, ch2.nuclear_repulsion_energy(), 9, "Nuclear repulsion energy")

    props = ['DIPOLE', 'QUADRUPOLE', 'MULLIKEN_CHARGES', 'LOWDIN_CHARGES',
             'WIBERG_LOWDIN_INDICES', 'MAYER_INDICES', 'MAYER_INDICES',
             'MO_EXTENTS', 'GRID_FIELD', 'GRID_ESP', 'ESP_AT_NUCLEI',
             'MULTIPOLE(5)', 'NO_OCCUPATIONS']

    psi4.properties('scf', properties=props)

    assert psi4.compare_values(psi4.get_variable("CURRENT ENERGY"), -38.91591819679808, 6, "SCF energy")
    assert psi4.compare_values(psi4.get_variable('SCF DIPOLE X'), 0.000000000000, 4, "SCF DIPOLE X")
    assert psi4.compare_values(psi4.get_variable('SCF DIPOLE Y'), 0.000000000000, 4, "SCF DIPOLE Y")
    assert psi4.compare_values(psi4.get_variable('SCF DIPOLE Z'), 0.572697798348, 4, "SCF DIPOLE Z")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE XX'), -7.664066833060, 4, "SCF QUADRUPOLE XX")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE YY'), -6.097755074075, 4, "SCF QUADRUPOLE YY")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE ZZ'), -7.074596012050, 4, "SCF QUADRUPOLE ZZ")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE XY'), 0.000000000000, 4, "SCF QUADRUPOLE XY")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE XZ'), 0.000000000000, 4, "SCF QUADRUPOLE XZ")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE YZ'), 0.000000000000, 4, "SCF QUADRUPOLE YZ")

    psi4.properties('B3LYP', properties=props)

    assert psi4.compare_values(psi4.get_variable('CURRENT ENERGY'), -39.14134740550916, 6, "B3LYP energy")
    assert psi4.compare_values(psi4.get_variable('B3LYP DIPOLE X'), 0.000000000000, 4, "B3LYP DIPOLE X")
    assert psi4.compare_values(psi4.get_variable('B3LYP DIPOLE Y'), -0.000000000000, 4, "B3LYP DIPOLE Y")
    assert psi4.compare_values(psi4.get_variable('B3LYP DIPOLE Z'), 0.641741521158, 4, "B3LYP DIPOLE Z")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE XX'), -7.616483183211, 4, "B3LYP QUADRUPOLE XX")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE YY'), -6.005896804551, 4, "B3LYP QUADRUPOLE YY")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE ZZ'), -7.021817489904, 4, "B3LYP QUADRUPOLE ZZ")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE XY'), 0.000000000000, 4, "B3LYP QUADRUPOLE XY")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE XZ'), 0.000000000000, 4, "B3LYP QUADRUPOLE XZ")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE YZ'), -0.000000000000, 4, "B3LYP QUADRUPOLE YZ")
Пример #30
0
P 1 1.00
         0.2148820000           1.0000000000
P 1 1.00
         0.0638500000           1.0000000000
D 2 1.00
         2.3062000000           0.2027000000
         0.7232000000           0.5791000000
D 2 1.00
         0.2149000000           0.7854500000
         0.0639000000           0.5338700000
****
""")

ccsd_e, wfn = psi4.properties('ccsd', properties=['dipole'], return_wfn=True)
psi4.oeprop(wfn, "DIPOLE", "QUADRUPOLE", title="(OEPROP)CC")
psi4.compare_values(psi4.get_variable("(OEPROP)CC DIPOLE X"), 0.000000000000,
                    6, "CC DIPOLE X")  #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC DIPOLE Y"), 0.000000000000,
                    6, "CC DIPOLE Y")  #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC DIPOLE Z"), -1.840334899884,
                    6, "CC DIPOLE Z")  #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE XX"),
                    -7.864006962064, 6, "CC QUADRUPOLE XX")  #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE XY"),
                    0.000000000000, 6, "CC QUADRUPOLE XY")  #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE XZ"),
                    0.000000000000, 6, "CC QUADRUPOLE XZ")  #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE YY"),
                    -4.537386915305, 6, "CC QUADRUPOLE YY")  #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE YZ"),
                    0.000000000000, 6, "CC QUADRUPOLE YZ")  #TEST
Пример #31
0
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
Пример #32
0
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
Пример #33
0
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
Пример #34
0
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
Пример #35
0
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
Пример #36
0
def test_libefp():
    """libefp/qchem-qmefp-sp"""
    #! EFP on mixed QM (water) and EFP (water + 2 * ammonia) system.
    #! An EFP-only calc performed first to test vales against q-chem.

    qmefp = psi4.geometry("""
    # QM fragment
    0 1
    units bohr
    O1     0.000000000000     0.000000000000     0.224348285559
    H2    -1.423528800232     0.000000000000    -0.897393142237
    H3     1.423528800232     0.000000000000    -0.897393142237
    # EFP as EFP fragments
    --
    efp h2o -4.014110144291     2.316749370493    -1.801514729931 -2.902133 1.734999 -1.953647
    --
    efp NH3,1.972094713645,,3.599497221584 ,    5.447701074734 -1.105309 2.033306 -1.488582
    --
    efp NH3 -7.876296399270    -1.854372164887    -2.414804197762  2.526442 1.658262 -2.742084
    """)

    #  <<<  EFP calc  >>>
    psi4.set_options({
        'basis': '6-31g*',
        'scf_type': 'pk',
        'guess': 'core',
        'df_scf_guess': False
    })

    psi4.energy('efp')
    assert psi4.compare_values(9.1793879214, qmefp.nuclear_repulsion_energy(),
                               6, 'QM NRE')
    assert psi4.compare_values(-0.0004901368,
                               psi4.get_variable('efp elst energy'), 6,
                               'EFP-EFP Elst')  # from q-chem
    assert psi4.compare_values(-0.0003168768,
                               psi4.get_variable('efp ind energy'), 6,
                               'EFP-EFP Indc')
    assert psi4.compare_values(-0.0021985285,
                               psi4.get_variable('efp disp energy'), 6,
                               'EFP-EFP Disp')  # from q-chem
    assert psi4.compare_values(0.0056859871,
                               psi4.get_variable('efp exch energy'), 6,
                               'EFP-EFP Exch')  # from q-chem
    assert psi4.compare_values(0.0026804450,
                               psi4.get_variable('efp total energy'), 6,
                               'EFP-EFP Totl')
    assert psi4.compare_values(0.0026804450,
                               psi4.get_variable('current energy'), 6,
                               'Current')
    psi4.core.print_variables()

    psi4.core.clean()
    psi4.core.clean_variables()

    #  <<<  QM + EFP calc  >>>
    psi4.set_options({'e_convergence': 12, 'd_convergence': 12})
    psi4.energy('scf')

    assert psi4.compare_values(9.1793879214, qmefp.nuclear_repulsion_energy(),
                               6, 'QM NRE')
    assert psi4.compare_values(0.2622598847,
                               psi4.get_variable('efp total energy') -
                               psi4.get_variable('efp ind energy'), 6,
                               'EFP corr to SCF')  # from q-chem
    assert psi4.compare_values(-0.0117694790,
                               psi4.get_variable('efp ind energy'), 6,
                               'QM-EFP Indc')  # from q-chem
    assert psi4.compare_values(-0.0021985285,
                               psi4.get_variable('efp disp energy'), 6,
                               'EFP-EFP Disp')  # from q-chem
    assert psi4.compare_values(0.0056859871,
                               psi4.get_variable('efp exch energy'), 6,
                               'EFP-EFP Exch')  # from q-chem
    assert psi4.compare_values(0.2504904057,
                               psi4.get_variable('efp total energy'), 6,
                               'EFP-EFP Totl')  # from q-chem
    assert psi4.compare_values(-76.0139362744,
                               psi4.get_variable('scf total energy'), 6,
                               'SCF')  # from q-chem
    psi4.core.print_variables()
Пример #37
0
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
Пример #38
0
        # Build a new vector that is orthornormal to all previous vectors
        dvecs.copy(svecs, n, swork_vec)
        norm = dvecs.norm(n)
        dvecs.symnormalize(1 / norm, n)
 
        total_proj = 0
        for i in range(num_vecs):
            proj = svecs.vdot(cvecs, swork_vec, i)
            total_proj += proj
            dvecs.axpy(-proj, cvecs, n, i)
 
        norm = dvecs.norm(n)
        dvecs.symnormalize(1 / norm, n)
 
        # This *should* screen out contributions that are projected out by above
        if True:
            cvecs.write(num_vecs, 0)
            cvecs.copy(dvecs, num_vecs, n)
            num_vecs += 1
        

print(    'SCF energy:           % 16.10f' % (scf_energy))
for n in range(nroot):
    print('State %d Total Energy: % 16.10f' % (n,CI_E[n] + mol.nuclear_repulsion_energy())) 

E = psi4.energy('detci')
psi4.driver.p4util.compare_values(psi4.get_variable('CI ROOT 0 TOTAL ENERGY'), CI_E[0]+ mol.nuclear_repulsion_energy(), 6, 'CI Root 0 Total Energy')
if(nroot > 1):
    psi4.driver.p4util.compare_values(psi4.get_variable('CI ROOT 1 TOTAL ENERGY'), CI_E[1]+ mol.nuclear_repulsion_energy(), 6, 'CI Root 1 Total Energy')
Пример #39
0
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
Пример #40
0
def test_dftd3():
    """dftd3/energy"""
    #! Exercises the various DFT-D corrections, both through python directly and through c++

    ref_d2         = [-0.00390110, -0.00165271, -0.00058118]
    ref_d3zero     = [-0.00285088, -0.00084340, -0.00031923]
    ref_d3bj       = [-0.00784595, -0.00394347, -0.00226683]

    ref_pbe_d2     = [-0.00278650, -0.00118051, -0.00041513]
    ref_pbe_d3zero = [-0.00175474, -0.00045421, -0.00016839]
    ref_pbe_d3bj   = [-0.00475937, -0.00235265, -0.00131239]

    eneyne = psi4.geometry("""
    C   0.000000  -0.667578  -2.124659
    C   0.000000   0.667578  -2.124659
    H   0.923621  -1.232253  -2.126185
    H  -0.923621  -1.232253  -2.126185
    H  -0.923621   1.232253  -2.126185
    H   0.923621   1.232253  -2.126185
    --
    C   0.000000   0.000000   2.900503
    C   0.000000   0.000000   1.693240
    H   0.000000   0.000000   0.627352
    H   0.000000   0.000000   3.963929
    """)

    psi4.print_stdout('  -D correction from Py-side')
    eneyne.update_geometry()
    E, G = eneyne.run_dftd3('b3lyp', 'd2gr')
    assert psi4.compare_values(ref_d2[0], E, 7, 'Ethene-Ethyne -D2')
    mA = eneyne.extract_subsets(1)
    E, G = mA.run_dftd3('b3lyp', 'd2gr')
    assert psi4.compare_values(ref_d2[1], E, 7, 'Ethene -D2')
    mB = eneyne.extract_subsets(2)
    E, G = mB.run_dftd3('b3lyp', 'd2gr')
    assert psi4.compare_values(ref_d2[2], E, 7, 'Ethyne -D2')
    #mBcp = eneyne.extract_subsets(2,1)
    #E, G = mBcp.run_dftd3('b3lyp', 'd2gr')
    #compare_values(ref_d2[2], E, 7, 'Ethyne(CP) -D2')

    E, G = eneyne.run_dftd3('b3lyp', 'd3zero')
    assert psi4.compare_values(ref_d3zero[0], E, 7, 'Ethene-Ethyne -D3 (zero)')
    mA = eneyne.extract_subsets(1)
    E, G = mA.run_dftd3('b3lyp', 'd3zero')
    assert psi4.compare_values(ref_d3zero[1], E, 7, 'Ethene -D3 (zero)')
    mB = eneyne.extract_subsets(2)
    E, G = mB.run_dftd3('b3lyp', 'd3zero')
    assert psi4.compare_values(ref_d3zero[2], E, 7, 'Ethyne -D3 (zero)')

    E, G = eneyne.run_dftd3('b3lyp', 'd3bj')
    assert psi4.compare_values(ref_d3bj[0], E, 7, 'Ethene-Ethyne -D3 (bj)')
    mA = eneyne.extract_subsets(1)
    E, G = mA.run_dftd3('b3lyp', 'd3bj')
    assert psi4.compare_values(ref_d3bj[1], E, 7, 'Ethene -D3 (bj)')
    mB = eneyne.extract_subsets(2)
    E, G = mB.run_dftd3('b3lyp', 'd3bj')
    assert psi4.compare_values(ref_d3bj[2], E, 7, 'Ethyne -D3 (bj)')

    E, G = eneyne.run_dftd3('b3lyp', 'd3')
    assert psi4.compare_values(ref_d3zero[0], E, 7, 'Ethene-Ethyne -D3 (alias)')
    E, G = eneyne.run_dftd3('b3lyp', 'd')
    assert psi4.compare_values(ref_d2[0], E, 7, 'Ethene-Ethyne -D (alias)')
    E, G = eneyne.run_dftd3('b3lyp', 'd2')
    assert psi4.compare_values(ref_d2[0], E, 7, 'Ethene-Ethyne -D2 (alias)')

    psi4.set_options({'basis': 'sto-3g',
                      'scf_type': 'df',
                      'dft_radial_points': 50,  # use really bad grid for speed since all we want is the -D value
                      'dft_spherical_points': 110,
                      #'scf print': 3,  # will print dftd3 program output to psi4 output file
                    })

    psi4.print_stdout('  -D correction from C-side')
    psi4.activate(mA)
    #psi4.energy('b3lyp-d2p4')
    #assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling psi4 Disp class)')
    #psi4.energy('b3lyp-d2gr')
    #assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling dftd3 -old)')
    #psi4.energy('b3lyp-d3zero')
    #assert psi4.compare_values(ref_d3zero[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -zero)')
    psi4.energy('b3lyp-d3bj')
    assert psi4.compare_values(ref_d3bj[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -bj)')

    psi4.energy('b3lyp-d2')
    assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (alias)')
    #psi4.energy('b3lyp-d3')
    #assert psi4.compare_values(ref_d3zero[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (alias)')
    #psi4.energy('b3lyp-d')
    #assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D (alias)')
    psi4.energy('wb97x-d')
    assert psi4.compare_values(-0.000834247063, psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene wb97x-d (chg)')

    psi4.print_stdout('  non-default -D correction from C-side')
    psi4.activate(mB)
    #psi4.set_options({'dft_dispersion_parameters': [0.75]})
    #psi4.energy('b3lyp-d2p4')
    #assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling psi4 Disp class)')
    #psi4.set_options({'dft_dispersion_parameters': [0.75, 20.0]})
    #psi4.energy('b3lyp-d2gr')
    #assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling dftd3 -old)')
    #psi4.set_options({'dft_dispersion_parameters': [1.0,  0.722, 1.217, 14.0]})
    #psi4.energy('b3lyp-d3zero')
    #assert psi4.compare_values(ref_pbe_d3zero[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -zero)')
    psi4.set_options({'dft_dispersion_parameters': [1.000, 0.7875, 0.4289, 4.4407]})
    psi4.energy('b3lyp-d3bj')
    assert psi4.compare_values(ref_pbe_d3bj[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -bj)')

    psi4.set_options({'dft_dispersion_parameters': [0.75]})
    psi4.energy('b3lyp-d2')
    assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (alias)')
    psi4.set_options({'dft_dispersion_parameters': [1.0,  0.722, 1.217, 14.0]})
    psi4.energy('b3lyp-d3')
    assert psi4.compare_values(ref_pbe_d3zero[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (alias)')
    psi4.set_options({'dft_dispersion_parameters': [0.75]})
    psi4.energy('b3lyp-d')
    assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D (alias)')
    psi4.activate(mA)
    psi4.set_options({'dft_dispersion_parameters': [1.0]})
    psi4.energy('wb97x-d')
    assert psi4.compare_values(-0.000834247063, psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene wb97x-d (chg)')

    psi4.print_stdout('  non-default -D correction from Py-side')
    eneyne.update_geometry()
    eneyne.run_dftd3('b3lyp', 'd2gr', {'s6': 0.75})
    assert psi4.compare_values(ref_pbe_d2[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D2')
    mA = eneyne.extract_subsets(1)
    mA.run_dftd3('b3lyp', 'd2gr', {'s6': 0.75})
    assert psi4.compare_values(ref_pbe_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2')
    mB = eneyne.extract_subsets(2)
    mB.run_dftd3('b3lyp', 'd2gr', {'s6': 0.75})
    assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethyne -D2')

    eneyne.run_dftd3('b3lyp', 'd3zero', {'s6': 1.0,  's8': 0.722, 'sr6': 1.217, 'alpha6': 14.0})
    assert psi4.compare_values(ref_pbe_d3zero[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D3 (zero)')
    mA = eneyne.extract_subsets(1)
    mA.run_dftd3('b3lyp', 'd3zero', {'s6': 1.0,  's8': 0.722, 'sr6': 1.217, 'alpha6': 14.0})
    assert psi4.compare_values(ref_pbe_d3zero[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (zero)')
    mB = eneyne.extract_subsets(2)
    mB.run_dftd3('b3lyp', 'd3zero', {'s6': 1.0,  's8': 0.722, 'sr6': 1.217, 'alpha6': 14.0})
    assert psi4.compare_values(ref_pbe_d3zero[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethyne -D3 (zero)')

    eneyne.run_dftd3('b3lyp', 'd3bj', {'s6': 1.000, 's8':  0.7875, 'a1':  0.4289, 'a2': 4.4407})
    assert psi4.compare_values(ref_pbe_d3bj[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D3 (bj)')
    mA = eneyne.extract_subsets(1)
    mA.run_dftd3('b3lyp', 'd3bj', {'s6': 1.000, 's8':  0.7875, 'a1':  0.4289, 'a2': 4.4407})
    assert psi4.compare_values(ref_pbe_d3bj[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (bj)')
    mB = eneyne.extract_subsets(2)
    mB.run_dftd3('b3lyp', 'd3bj', {'s6': 1.000, 's8':  0.7875, 'a1':  0.4289, 'a2': 4.4407})
    assert psi4.compare_values(ref_pbe_d3bj[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethyne -D3 (bj)')
    eneyne.run_dftd3('b3lyp', 'd3', {'s6': 1.0,  's8': 0.722, 'sr6': 1.217, 'alpha6': 14.0})

    assert psi4.compare_values(ref_pbe_d3zero[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D3 (alias)')
    eneyne.run_dftd3('b3lyp', 'd', {'s6': 0.75})
    assert psi4.compare_values(ref_pbe_d2[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D (alias)')
    eneyne.run_dftd3('b3lyp', 'd2', {'s6': 0.75})
    assert psi4.compare_values(ref_pbe_d2[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene-Ethyne -D2 (alias)')
Пример #41
0
sapt_printer('Elst10', Elst10)
sapt_printer('Exch10', Exch10)
sapt_printer('Disp20', Disp20)
sapt_printer('Exch-Disp20', ExchDisp20)
sapt_printer('Ind20,r', Ind20r)
sapt_printer('Exch-Ind20,r', ExchInd20r)
print('-' * 70)
sapt0_no_S2 = Exch10 + Elst10 + Disp20 + ExchDisp20 + Ind20r + ExchInd20r
sapt_printer('Total SAPT0', sapt0_no_S2)
print('')

# Print Psi4 Results
psi4.set_options({'df_basis_sapt': 'aug-cc-pvtz-ri'})
psi4.energy('sapt0')

Eelst = psi4.get_variable('SAPT ELST ENERGY')
Eexch = psi4.get_variable('SAPT EXCH10 ENERGY')
Eexch_S2 = psi4.get_variable('SAPT EXCH10(S^2) ENERGY')
Eind = psi4.get_variable('SAPT IND20,R ENERGY')
Eexind = psi4.get_variable('SAPT EXCH-IND20,R ENERGY')
Edisp = psi4.get_variable('SAPT DISP20 ENERGY')
Eexdisp = psi4.get_variable('SAPT EXCH-DISP20 ENERGY')

print('Psi4 SAPT0 Results')
print('-' * 70)
sapt_printer('Elst10', Eelst)
sapt_printer('Exch10', Eexch)
sapt_printer('Exch10(S^2)', Eexch_S2)
sapt_printer('Disp20', Edisp)
sapt_printer('Exch-Disp20(S^2)', Eexdisp)
sapt_printer('Ind20,r', Eind)
Пример #42
0
sapt_printer('Elst10', Elst10)
sapt_printer('Exch10', Exch10)
sapt_printer('Disp20', Disp20)
sapt_printer('Exch-Disp20', ExchDisp20)
sapt_printer('Ind20,r', Ind20r)
sapt_printer('Exch-Ind20,r', ExchInd20r)
print('-' * 70)
sapt0_no_S2 = Exch10 + Elst10 + Disp20 + ExchDisp20 + Ind20r + ExchInd20r
sapt_printer('Total SAPT0', sapt0_no_S2)
print('')

# Print Psi4 Results
psi4.set_options({'df_basis_sapt': 'aug-cc-pvtz-ri'})
psi4.energy('sapt0')

Eelst = psi4.get_variable('SAPT ELST ENERGY')
Eexch = psi4.get_variable('SAPT EXCH10 ENERGY')
Eexch_S2 = psi4.get_variable('SAPT EXCH10(S^2) ENERGY')
Eind = psi4.get_variable('SAPT IND20,R ENERGY')
Eexind = psi4.get_variable('SAPT EXCH-IND20,R ENERGY')
Edisp = psi4.get_variable('SAPT DISP20 ENERGY')
Eexdisp = psi4.get_variable('SAPT EXCH-DISP20 ENERGY')

print('Psi4 SAPT0 Results')
print('-' * 70)
sapt_printer('Elst10', Eelst)
sapt_printer('Exch10', Eexch)
sapt_printer('Exch10(S^2)', Eexch_S2)
sapt_printer('Disp20', Edisp)
sapt_printer('Exch-Disp20(S^2)', Eexdisp)
sapt_printer('Ind20,r', Eind)
Пример #43
0
def test_psi4_scfproperty():
    """scf-property"""
    #! UFH and B3LYP cc-pVQZ properties for the CH2 molecule.

    with open('grid.dat', 'w') as handle:
        handle.write("""\
0.0  0.0  0.0
1.1  1.3  1.4
""")

    ch2 = psi4.geometry("""
        0 3
        c
        h 1 b1
        h 1 b1 2 a1

        b1 = 1.0
        a1 = 125.0
    """)

    # Get a reasonable guess, to save some iterations
    psi4.set_options({
        "scf_type": "pk",
        "basis": "6-31G**",
        "e_convergence": 8,
        "docc": [2, 0, 0, 1],
        "socc": [1, 0, 1, 0],
        "reference": "uhf"
    })

    ch2.update_geometry()
    assert psi4.compare_values(6.6484189450, ch2.nuclear_repulsion_energy(), 9,
                               "Nuclear repulsion energy")

    props = [
        'DIPOLE', 'QUADRUPOLE', 'MULLIKEN_CHARGES', 'LOWDIN_CHARGES',
        'WIBERG_LOWDIN_INDICES', 'MAYER_INDICES', 'MAYER_INDICES',
        'MO_EXTENTS', 'GRID_FIELD', 'GRID_ESP', 'ESP_AT_NUCLEI',
        'MULTIPOLE(5)', 'NO_OCCUPATIONS'
    ]

    psi4.properties('scf', properties=props)

    assert psi4.compare_values(psi4.get_variable("CURRENT ENERGY"),
                               -38.91591819679808, 6, "SCF energy")
    assert psi4.compare_values(psi4.get_variable('SCF DIPOLE X'),
                               0.000000000000, 4, "SCF DIPOLE X")
    assert psi4.compare_values(psi4.get_variable('SCF DIPOLE Y'),
                               0.000000000000, 4, "SCF DIPOLE Y")
    assert psi4.compare_values(psi4.get_variable('SCF DIPOLE Z'),
                               0.572697798348, 4, "SCF DIPOLE Z")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE XX'),
                               -7.664066833060, 4, "SCF QUADRUPOLE XX")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE YY'),
                               -6.097755074075, 4, "SCF QUADRUPOLE YY")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE ZZ'),
                               -7.074596012050, 4, "SCF QUADRUPOLE ZZ")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE XY'),
                               0.000000000000, 4, "SCF QUADRUPOLE XY")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE XZ'),
                               0.000000000000, 4, "SCF QUADRUPOLE XZ")
    assert psi4.compare_values(psi4.get_variable('SCF QUADRUPOLE YZ'),
                               0.000000000000, 4, "SCF QUADRUPOLE YZ")

    psi4.properties('B3LYP', properties=props)

    assert psi4.compare_values(psi4.get_variable('CURRENT ENERGY'),
                               -39.14134740550916, 6, "B3LYP energy")
    assert psi4.compare_values(psi4.get_variable('B3LYP DIPOLE X'),
                               0.000000000000, 4, "B3LYP DIPOLE X")
    assert psi4.compare_values(psi4.get_variable('B3LYP DIPOLE Y'),
                               -0.000000000000, 4, "B3LYP DIPOLE Y")
    assert psi4.compare_values(psi4.get_variable('B3LYP DIPOLE Z'),
                               0.641741521158, 4, "B3LYP DIPOLE Z")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE XX'),
                               -7.616483183211, 4, "B3LYP QUADRUPOLE XX")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE YY'),
                               -6.005896804551, 4, "B3LYP QUADRUPOLE YY")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE ZZ'),
                               -7.021817489904, 4, "B3LYP QUADRUPOLE ZZ")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE XY'),
                               0.000000000000, 4, "B3LYP QUADRUPOLE XY")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE XZ'),
                               0.000000000000, 4, "B3LYP QUADRUPOLE XZ")
    assert psi4.compare_values(psi4.get_variable('B3LYP QUADRUPOLE YZ'),
                               -0.000000000000, 4, "B3LYP QUADRUPOLE YZ")
Пример #44
0
def test_dftd3():
    """dftd3/energy"""
    #! Exercises the various DFT-D corrections, both through python directly and through c++

    ref_d2 = [-0.00390110, -0.00165271, -0.00058118]
    ref_d3zero = [-0.00285088, -0.00084340, -0.00031923]
    ref_d3bj = [-0.00784595, -0.00394347, -0.00226683]

    ref_pbe_d2 = [-0.00278650, -0.00118051, -0.00041513]
    ref_pbe_d3zero = [-0.00175474, -0.00045421, -0.00016839]
    ref_pbe_d3bj = [-0.00475937, -0.00235265, -0.00131239]

    eneyne = psi4.geometry("""
    C   0.000000  -0.667578  -2.124659
    C   0.000000   0.667578  -2.124659
    H   0.923621  -1.232253  -2.126185
    H  -0.923621  -1.232253  -2.126185
    H  -0.923621   1.232253  -2.126185
    H   0.923621   1.232253  -2.126185
    --
    C   0.000000   0.000000   2.900503
    C   0.000000   0.000000   1.693240
    H   0.000000   0.000000   0.627352
    H   0.000000   0.000000   3.963929
    """)

    psi4.print_stdout('  -D correction from Py-side')
    eneyne.update_geometry()
    E, G = eneyne.run_dftd3('b3lyp', 'd2gr')
    assert psi4.compare_values(ref_d2[0], E, 7, 'Ethene-Ethyne -D2')
    mA = eneyne.extract_subsets(1)
    E, G = mA.run_dftd3('b3lyp', 'd2gr')
    assert psi4.compare_values(ref_d2[1], E, 7, 'Ethene -D2')
    mB = eneyne.extract_subsets(2)
    E, G = mB.run_dftd3('b3lyp', 'd2gr')
    assert psi4.compare_values(ref_d2[2], E, 7, 'Ethyne -D2')
    #mBcp = eneyne.extract_subsets(2,1)
    #E, G = mBcp.run_dftd3('b3lyp', 'd2gr')
    #compare_values(ref_d2[2], E, 7, 'Ethyne(CP) -D2')

    E, G = eneyne.run_dftd3('b3lyp', 'd3zero')
    assert psi4.compare_values(ref_d3zero[0], E, 7, 'Ethene-Ethyne -D3 (zero)')
    mA = eneyne.extract_subsets(1)
    E, G = mA.run_dftd3('b3lyp', 'd3zero')
    assert psi4.compare_values(ref_d3zero[1], E, 7, 'Ethene -D3 (zero)')
    mB = eneyne.extract_subsets(2)
    E, G = mB.run_dftd3('b3lyp', 'd3zero')
    assert psi4.compare_values(ref_d3zero[2], E, 7, 'Ethyne -D3 (zero)')

    E, G = eneyne.run_dftd3('b3lyp', 'd3bj')
    assert psi4.compare_values(ref_d3bj[0], E, 7, 'Ethene-Ethyne -D3 (bj)')
    mA = eneyne.extract_subsets(1)
    E, G = mA.run_dftd3('b3lyp', 'd3bj')
    assert psi4.compare_values(ref_d3bj[1], E, 7, 'Ethene -D3 (bj)')
    mB = eneyne.extract_subsets(2)
    E, G = mB.run_dftd3('b3lyp', 'd3bj')
    assert psi4.compare_values(ref_d3bj[2], E, 7, 'Ethyne -D3 (bj)')

    E, G = eneyne.run_dftd3('b3lyp', 'd3')
    assert psi4.compare_values(ref_d3zero[0], E, 7,
                               'Ethene-Ethyne -D3 (alias)')
    E, G = eneyne.run_dftd3('b3lyp', 'd')
    assert psi4.compare_values(ref_d2[0], E, 7, 'Ethene-Ethyne -D (alias)')
    E, G = eneyne.run_dftd3('b3lyp', 'd2')
    assert psi4.compare_values(ref_d2[0], E, 7, 'Ethene-Ethyne -D2 (alias)')

    psi4.set_options({
        'basis': 'sto-3g',
        'scf_type': 'df',
        'dft_radial_points':
        50,  # use really bad grid for speed since all we want is the -D value
        'dft_spherical_points': 110,
        #'scf print': 3,  # will print dftd3 program output to psi4 output file
    })

    psi4.print_stdout('  -D correction from C-side')
    psi4.activate(mA)
    #psi4.energy('b3lyp-d2p4')
    #assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling psi4 Disp class)')
    #psi4.energy('b3lyp-d2gr')
    #assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling dftd3 -old)')
    #psi4.energy('b3lyp-d3zero')
    #assert psi4.compare_values(ref_d3zero[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -zero)')
    psi4.energy('b3lyp-d3bj')
    assert psi4.compare_values(
        ref_d3bj[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene -D3 (calling dftd3 -bj)')

    psi4.energy('b3lyp-d2')
    assert psi4.compare_values(
        ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene -D2 (alias)')
    #psi4.energy('b3lyp-d3')
    #assert psi4.compare_values(ref_d3zero[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (alias)')
    #psi4.energy('b3lyp-d')
    #assert psi4.compare_values(ref_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D (alias)')
    psi4.energy('wb97x-d')
    assert psi4.compare_values(
        -0.000834247063, psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene wb97x-d (chg)')

    psi4.print_stdout('  non-default -D correction from C-side')
    psi4.activate(mB)
    #psi4.set_options({'dft_dispersion_parameters': [0.75]})
    #psi4.energy('b3lyp-d2p4')
    #assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling psi4 Disp class)')
    #psi4.set_options({'dft_dispersion_parameters': [0.75, 20.0]})
    #psi4.energy('b3lyp-d2gr')
    #assert psi4.compare_values(ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D2 (calling dftd3 -old)')
    #psi4.set_options({'dft_dispersion_parameters': [1.0,  0.722, 1.217, 14.0]})
    #psi4.energy('b3lyp-d3zero')
    #assert psi4.compare_values(ref_pbe_d3zero[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7, 'Ethene -D3 (calling dftd3 -zero)')
    psi4.set_options(
        {'dft_dispersion_parameters': [1.000, 0.7875, 0.4289, 4.4407]})
    psi4.energy('b3lyp-d3bj')
    assert psi4.compare_values(
        ref_pbe_d3bj[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene -D3 (calling dftd3 -bj)')

    psi4.set_options({'dft_dispersion_parameters': [0.75]})
    psi4.energy('b3lyp-d2')
    assert psi4.compare_values(
        ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene -D2 (alias)')
    psi4.set_options({'dft_dispersion_parameters': [1.0, 0.722, 1.217, 14.0]})
    psi4.energy('b3lyp-d3')
    assert psi4.compare_values(
        ref_pbe_d3zero[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'),
        7, 'Ethene -D3 (alias)')
    psi4.set_options({'dft_dispersion_parameters': [0.75]})
    psi4.energy('b3lyp-d')
    assert psi4.compare_values(
        ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene -D (alias)')
    psi4.activate(mA)
    psi4.set_options({'dft_dispersion_parameters': [1.0]})
    psi4.energy('wb97x-d')
    assert psi4.compare_values(
        -0.000834247063, psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene wb97x-d (chg)')

    psi4.print_stdout('  non-default -D correction from Py-side')
    eneyne.update_geometry()
    eneyne.run_dftd3('b3lyp', 'd2gr', {'s6': 0.75})
    assert psi4.compare_values(
        ref_pbe_d2[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene-Ethyne -D2')
    mA = eneyne.extract_subsets(1)
    mA.run_dftd3('b3lyp', 'd2gr', {'s6': 0.75})
    assert psi4.compare_values(
        ref_pbe_d2[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene -D2')
    mB = eneyne.extract_subsets(2)
    mB.run_dftd3('b3lyp', 'd2gr', {'s6': 0.75})
    assert psi4.compare_values(
        ref_pbe_d2[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethyne -D2')

    eneyne.run_dftd3('b3lyp', 'd3zero', {
        's6': 1.0,
        's8': 0.722,
        'sr6': 1.217,
        'alpha6': 14.0
    })
    assert psi4.compare_values(
        ref_pbe_d3zero[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'),
        7, 'Ethene-Ethyne -D3 (zero)')
    mA = eneyne.extract_subsets(1)
    mA.run_dftd3('b3lyp', 'd3zero', {
        's6': 1.0,
        's8': 0.722,
        'sr6': 1.217,
        'alpha6': 14.0
    })
    assert psi4.compare_values(
        ref_pbe_d3zero[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'),
        7, 'Ethene -D3 (zero)')
    mB = eneyne.extract_subsets(2)
    mB.run_dftd3('b3lyp', 'd3zero', {
        's6': 1.0,
        's8': 0.722,
        'sr6': 1.217,
        'alpha6': 14.0
    })
    assert psi4.compare_values(
        ref_pbe_d3zero[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'),
        7, 'Ethyne -D3 (zero)')

    eneyne.run_dftd3('b3lyp', 'd3bj', {
        's6': 1.000,
        's8': 0.7875,
        'a1': 0.4289,
        'a2': 4.4407
    })
    assert psi4.compare_values(
        ref_pbe_d3bj[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene-Ethyne -D3 (bj)')
    mA = eneyne.extract_subsets(1)
    mA.run_dftd3('b3lyp', 'd3bj', {
        's6': 1.000,
        's8': 0.7875,
        'a1': 0.4289,
        'a2': 4.4407
    })
    assert psi4.compare_values(
        ref_pbe_d3bj[1], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene -D3 (bj)')
    mB = eneyne.extract_subsets(2)
    mB.run_dftd3('b3lyp', 'd3bj', {
        's6': 1.000,
        's8': 0.7875,
        'a1': 0.4289,
        'a2': 4.4407
    })
    assert psi4.compare_values(
        ref_pbe_d3bj[2], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethyne -D3 (bj)')
    eneyne.run_dftd3('b3lyp', 'd3', {
        's6': 1.0,
        's8': 0.722,
        'sr6': 1.217,
        'alpha6': 14.0
    })

    assert psi4.compare_values(
        ref_pbe_d3zero[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'),
        7, 'Ethene-Ethyne -D3 (alias)')
    eneyne.run_dftd3('b3lyp', 'd', {'s6': 0.75})
    assert psi4.compare_values(
        ref_pbe_d2[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene-Ethyne -D (alias)')
    eneyne.run_dftd3('b3lyp', 'd2', {'s6': 0.75})
    assert psi4.compare_values(
        ref_pbe_d2[0], psi4.get_variable('DISPERSION CORRECTION ENERGY'), 7,
        'Ethene-Ethyne -D2 (alias)')
Пример #45
0
        dvecs.copy(svecs, n, swork_vec)
        norm = dvecs.norm(n)
        dvecs.symnormalize(1 / norm, n)

        total_proj = 0
        for i in range(num_vecs):
            proj = svecs.vdot(cvecs, swork_vec, i)
            total_proj += proj
            dvecs.axpy(-proj, cvecs, n, i)

        norm = dvecs.norm(n)
        dvecs.symnormalize(1 / norm, n)

        # This *should* screen out contributions that are projected out by above
        if True:
            cvecs.write(num_vecs, 0)
            cvecs.copy(dvecs, num_vecs, n)
            num_vecs += 1

print('SCF energy:           % 16.10f' % (scf_energy))
for n in range(nroot):
    print('State %d Total Energy: % 16.10f' % (n, CI_E[n] + mol.nuclear_repulsion_energy()))
print("")

E = psi4.energy('detci')

for n in range(nroot):
    ci_ref = psi4.get_variable('CI ROOT %d TOTAL ENERGY' % n)
    ci_compute = CI_E[n] + mol.nuclear_repulsion_energy()
    psi4.compare_values(ci_ref, ci_compute, 6, 'CI Root %d Total Energy' % n)
Пример #46
0
    # ==> Build Stochastic Integral Matrices <==
    # Create two random vector
    vec = np.random.choice([-1, 1], size=(Qia.shape[0]))
    vecp = np.random.choice([-1, 1], size=(Qia.shape[0]))

    # Generate first R matrices
    ia = np.einsum("Q,Qia->ia", vec, Qia)
    iap = np.einsum("Q,Qia->ia", vecp, Qia)

    # ==> Calculate a single stochastic RI-MP2 (sRI-MP2) sample <==

    # Caculate sRI-MP2 correlation energy
    e_srimp2 += 2.0 * np.einsum('ijab,ia,ia,jb,jb->', denom, ia, iap, ia, iap)
    e_srimp2 -= np.einsum('ijab,ia,ib,jb,ja->', denom, ia, iap, ia, iap)

e_srimp2 /= float(nsample)
total_time = time.time() - t
time_per_sample = total_time / float(nsample)

# Print sample energy to output
print("\nNumber of samples:                 % 16d" % nsample)
print("Total time (s):                    % 16.2f" % total_time)
print("Time per sample (us):              % 16.2f" % (time_per_sample * 1.e6))
print("sRI-MP2 correlation sample energy: % 16.10f" % e_srimp2)

psi_mp2_energy = psi4.energy("MP2")
mp2_correlation_energy = psi4.get_variable("MP2 CORRELATION ENERGY")

print("\nRI-MP2 energy:                     % 16.10f" % mp2_correlation_energy)
print("Sample error                       % 16.10f" % (e_srimp2 - mp2_correlation_energy))
Пример #47
0
def writeCSX(name, **kwargs):
    """function to write the CSX file

    """

    if not psi4.get_global_option('WRITE_CSX'):
        return

    # import csx_api for csx writing
    import os
    import math
    import inspect
    #import openbabel
    import qcdb
    import qcdb.periodictable
    import csx2_api as api
    lowername = name.lower()
    # Make sure the molecule the user provided is the active one
    if ('molecule' in kwargs):
        activate(kwargs['molecule'])
        del kwargs['molecule']
    molecule = psi4.get_active_molecule()
    molecule.update_geometry()
    # Determine the derivative type
    calledby = inspect.stack()[1][3]
    derdict = {
        'energy': 0,
        'property': 0,
        'gradient': 1,
        'optimize': 1,
        'frequency': 2,
        'frequencies': 2,
        'hessian': 2,
        }
    dertype = derdict[calledby]
    hasFreq = False
    # Start to write the CSX file
    # First grab molecular information and energies from psi4
    geom = molecule.save_string_xyz()  # OB
    atomLine = geom.split('\n')  # OB

    # general molecular information
    atomNum = molecule.natom()
    molSym = molecule.schoenflies_symbol()
    molCharge = molecule.molecular_charge()
    molMulti = molecule.multiplicity()
    # energy information
    molBasis = psi4.get_global_option('BASIS')
    molSpin = psi4.get_global_option('REFERENCE')
    molMethod = psi4.get_global_option('WFN')
    mol1E = psi4.get_variable('ONE-ELECTRON ENERGY')
    mol2E = psi4.get_variable('TWO-ELECTRON ENERGY')
    molNE = psi4.get_variable('NUCLEAR REPULSION ENERGY')
    molPE = mol1E + mol2E
    molEE = psi4.get_variable('CURRENT ENERGY')
    # wavefunction information
    try:
        wfn = kwargs['wfn']
    except AttributeError:
        pass
    if wfn:
        molOrbE = wfn.epsilon_a()
        molOrbEb = wfn.epsilon_b()
        orbNmopi = wfn.nmopi()
        orbNsopi = wfn.nsopi()
        orbNum = wfn.nmo() if molOrbE else 0
        orbSNum = wfn.nso()
        molOrb = wfn.Ca()
        orbNirrep = wfn.nirrep()
        orbAotoso = wfn.aotoso()
        orbDoccpi = wfn.doccpi()
        orbSoccpi = wfn.soccpi()
        basisNbf = wfn.basisset().nbf()
        basisDim = psi4.Dimension(1, 'basisDim')
        basisDim.__setitem__(0, basisNbf)
        wfnRestricted = True
        orbE = []
        hlist = []
        orblist = []
        orbOcc = []
        molOrbmo = psi4.Matrix('molOrbmo', basisDim, orbNmopi)
        molOrbmo.gemm(False, False, 1.0, orbAotoso, molOrb, 0.0)
        if molSpin == 'UHF':
            wfnRestricted = False
            orbEb = []
            hlistCb = []
            orblistCb = []
            orbOccCb = []
            molOrbCb = wfn.Cb()
            molOrbmoCb = psi4.Matrix('molOrbmoCb', basisDim, orbNmopi)
            molOrbmoCb.gemm(False, False, 1.0, orbAotoso, molOrbCb, 0.0)
        count = 0
        eleExtra = 1 if wfnRestricted else 0
        for ih in range(orbNirrep):
            for iorb in range(orbNmopi.__getitem__(ih)):
                hlist.append(ih)
                orblist.append(iorb)
                if molOrbE:
                    orbE.append(molOrbE.get(count))
                eleNum = 1 if iorb < (orbDoccpi.__getitem__(ih) + orbSoccpi.__getitem__(ih)) else 0
                eleNum += eleExtra if iorb < orbDoccpi.__getitem__(ih) else 0
                orbOcc.append(eleNum)
                count += 1
        orbMos = sorted(zip(orbE, zip(hlist, orblist)))
        orbOccString = ' '.join(str(x) for x in sorted(orbOcc, reverse=True))
        orbCaString = []
        for imos in range(orbNum):
            (h, s) = orbMos[imos][1]
            orbCa = []
            for iso in range(orbSNum):
                orbEle = molOrbmo.get(h, iso, s)
                orbCa.append(orbEle)
            orbCaString.append(' '.join(str(x) for x in orbCa))
        orbEString = ' '.join(str(x) for x in sorted(orbE))
        # now for beta spin
        if not wfnRestricted:
            count = 0
            for ih in range(orbNirrep):
                for iorb in range(orbNmopi.__getitem__(ih)):
                    hlistCb.append(ih)
                    orblist.append(iorb)
                    if molOrbEb:
                        orbEb.append(molOrbEb.get(count))
                    eleNum = 1 if iorb < (orbDoccpi.__getitem__(ih) + orbSoccpi.__getitem__(ih)) else 0
                    if iorb < orbDoccpi.__getitem__(ih):
                        eleNum += eleExtra
                    orbOccCb.append(eleNum)
                    count += 1
            orbMosCb = sorted(zip(orbEb, zip(hlist, orblist)))
            orbOccCbString = ' '.join(str(x) for x in sorted(orbOccCb, reverse=True))
            orbCbString = []
            for imos in range(orbNum):
                (h, s) = orbMosCb[imos][1]
                orbCb = []
                for iso in range(orbSNum):
                    orbEle = molOrbmoCb.get(h, iso, s)
                    orbCb.append(orbEle)
                orbCbString.append(' '.join(str(x) for x in orbCb))
            orbEbString = ' '.join(str(x) for x in sorted(orbEb))
        #   orbColString = ' '.join(str(x) for x in orbCol)
        if wfnRestricted:
            wfn1 = api.waveFunctionType(
                orbitalCount=orbNum,
                orbitalOccupancies=orbOccString)
            orbe1 = api.stringArrayType(unit='gc:hartree')
            orbe1.set_valueOf_(orbEString)
            orbs1 = api.orbitalsType()
            for iorb in range(orbNum):
                orb1 = api.stringArrayType(id=iorb+1)
                orb1.set_valueOf_(orbCaString[iorb])
                orbs1.add_orbital(orb1)
            wfn1.set_orbitals(orbs1)
            wfn1.set_orbitalEnergies(orbe1)
        else:
            wfn1 = api.waveFunctionType(orbitalCount=orbNum)
            # alpha electron: 1.5
            orbe1 = api.stringArrayType(unit='gc:hartree')
            orbe1.set_valueOf_(orbEString)
            wfn1.set_alphaOrbitalEnergies(orbe1)
            wfn1.set_alphaOrbitalOccupancies(orbOccString)
            aorbs1 = api.orbitalsType()
            for iorb in range(orbNum):
                orb1 = api.stringArrayType(id=iorb+1)
                orb1.set_valueOf_(orbCaString[iorb])
                aorbs1.add_orbital(orb1)
            wfn1.set_alphaOrbitals(aorbs1)
            # beta electron: 1.5
            orbeb1 = api.stringArrayType(unit='gc:hartree')
            orbeb1.set_valueOf_(orbEbString)
            wfn1.set_betaOrbitalEnergies(orbeb1)
            wfn1.set_betaOrbitalOccupancies(orbOccCbString)
            borbs1 = api.orbitalsType()
            for iorb in range(orbNum):
                orb1 = api.stringArrayType(id=iorb+1)
                orb1.set_valueOf_(orbCbString[iorb])
                borbs1.add_orbital(orb1)
            wfn1.set_betaOrbitals(borbs1)
    # frequency information
    if dertype == 2:
        hasFreq = True
        molFreq = psi4.get_frequencies()
        molFreqNum = molFreq.dim(0)
        frq = []
        irInt = []
        for ifrq in range(molFreqNum):
            frq.append(molFreq.get(ifrq))
            irInt.append(0.0)
        frqString = ' '.join(str(x) for x in frq)
        intString = ' '.join(str(x) for x in irInt)
        normMod = psi4.get_normalmodes()
        normMdString = []
        count = 0
        for ifrq in range(molFreqNum):
            normM = []
            for iatm in range(atomNum):
                for ixyz in range(3):
                    normM.append(normMod.get(count))
                    count += 1
            normMdString.append(' '.join(str(x) for x in normM))
        vib1 = api.vibAnalysisType(vibrationCount=molFreqNum)
        freq1 = api.stringArrayType(unit="gc:cm-1")
        freq1.set_valueOf_(frqString)
        vib1.set_frequencies(freq1)
        irint1 = api.stringArrayType()
        irint1.set_valueOf_(intString)
        vib1.set_irIntensities(irint1)
        norms1 = api.normalModesType()
        for ifrq in range(molFreqNum):
            norm1 = api.normalModeType(id=ifrq+1)
            norm1.set_valueOf_(normMdString[ifrq])
            norms1.add_normalMode(norm1)
        vib1.set_normalModes(norms1)
    # dipole moment information
    molDipoleX = psi4.get_variable('CURRENT DIPOLE X')
    molDipoleY = psi4.get_variable('CURRENT DIPOLE Y')
    molDipoleZ = psi4.get_variable('CURRENT DIPOLE Z')
    molDipoleTot = math.sqrt(
        molDipoleX * molDipoleX +
        molDipoleY * molDipoleY +
        molDipoleZ * molDipoleZ)
    prop1 = api.propertiesType()
    sprop1 = api.propertyType(
        name='dipoleMomentX',
        unit='gc:debye')
    sprop1.set_valueOf_(molDipoleX)
    sprop2 = api.propertyType(
        name='dipoleMomentY',
        unit='gc:debye')
    sprop2.set_valueOf_(molDipoleY)
    sprop3 = api.propertyType(
        name='dipoleMomentZ',
        unit='gc:debye')
    sprop3.set_valueOf_(molDipoleZ)
    sprop4 = api.propertyType(
        name='dipoleMomentAverage',
        unit='gc:debye')
    sprop4.set_valueOf_(molDipoleTot)
    prop1.add_systemProperty(sprop1)
    prop1.add_systemProperty(sprop2)
    prop1.add_systemProperty(sprop3)
    prop1.add_systemProperty(sprop4)

    # get the basename for the CSX file
    psio = psi4.IO.shared_object()
    namespace = psio.get_default_namespace()
    #csxfilename = '.'.join([namespace, str(os.getpid()), 'csx'])
    csxfilename = os.path.splitext(psi4.outfile_name())[0] + '.csx'
    csxfile = open(csxfilename, 'w')
    csxVer = psi4.get_global_option('CSX_VERSION')

    # Both CSX versions 0 and 1 depended on the procedures table, which in
    #   turn required the writeCSX function to be in the driver.py file
    #   itself. Starting with 1.5 (1, to run), this dependence is broken and
    #   CSX has been shifted into a plugin.

    # Start to generate CSX elements
    # CSX version 1.5
    if csxVer == 2.0:
        #       import csx1_api as api
        cs1 = api.csType(version='2.0') #5')

        # molPublication section: 1.5
        mp1 = api.mpubType(
            title=psi4.get_global_option('PUBLICATIONTITLE'),
            abstract=psi4.get_global_option('PUBLICATIONABSTRACT'),
            publisher=psi4.get_global_option('PUBLICATIONPUBLISHER'),
            status=['PRELIMINARY', 'DRAFT', 'FINAL'].index(psi4.get_global_option('PUBLICATIONSTATUS')),
            category=psi4.get_global_option('PUBLICATIONCATEGORY'),
            visibility=['PRIVATE', 'PROTECTED', 'PUBLIC'].index(psi4.get_global_option('PUBLICATIONVISIBILITY')),
            tags=psi4.get_global_option('PUBLICATIONTAGS'),
            key=psi4.get_global_option('PUBLICATIONKEY'))
        email = psi4.get_global_option('EMAIL').replace('__', '@')
        mp1.add_author(api.authorType(
            creator=psi4.get_global_option('CORRESPONDINGAUTHOR'),
            type_='gc:CorrespondingAuthor',
            organization=psi4.get_global_option('ORGANIZATION'),
            email=None if email == '' else email))
        #mp1 = api.mpType(
        #   title='', abstract='', publisher='', status=0, category=2, visibility=0, tags='', key='')
        mp1.set_sourcePackage(api.sourcePackageType(name='Psi4', version=psi4.version()))
        #mp1.add_author(api.authorType(creator='', type_='cs:corresponding', organization='', email=''))
        cs1.set_molecularPublication(mp1)

        # molSystem section: 1.5
        ms1 = api.msysType(
            systemCharge=molCharge,
            systemMultiplicity=molMulti, id='s1')
        temp1 = api.dataWithUnitsType(unit='gc:kelvin')
        temp1.set_valueOf_(0.0)  # LAB dispute
        ms1.set_systemTemperature(temp1)
        mol1 = api.moleculeType(id='m1', atomCount=molecule.natom())
        #OBmol1 = api.moleculeType(id='m1', atomCount=atomNum)
        #OBobmol1 = openbabel.OBMol()
        #OBfor iatm in range(atomNum):
        #OB    atomField = atomLine[iatm + 1].split()
        #OB    atmSymbol = atomField[0]
        #OB    xCoord = float(atomField[1])
        #OB    yCoord = float(atomField[2])
        #OB    zCoord = float(atomField[3])
        #OB    obatm = obmol1.NewAtom()
        #OB    obatm.SetAtomicNum(qcdb.periodictable.el2z[atmSymbol.upper()])
        #OB    obatm.SetVector(xCoord, yCoord, zCoord)
        #OBobmol1.ConnectTheDots()
        #OBobmol1.PerceiveBondOrders()
        #OBobmol1.SetTotalSpinMultiplicity(molMulti)
        #OBobmol1.SetTotalCharge(molCharge)
        #OBconv1 = openbabel.OBConversion()
        #OBconv1.SetInAndOutFormats('mol', 'inchi')
        #OBconv1.SetOptions('K', conv1.OUTOPTIONS)
        #OBinchikey = conv1.WriteString(obmol1)
        #OBmol1.set_inchiKey(inchikey.rstrip())
        #OBiatm = 0
        for at in range(molecule.natom()):
            #xCoord1 = api.dataWithUnitsType(unit='cs:angstrom')
            #yCoord1 = api.dataWithUnitsType(unit='cs:angstrom')
            #zCoord1 = api.dataWithUnitsType(unit='cs:angstrom')
            #xCoord1.set_valueOf_(molecule.x(at) * p4const.psi_bohr2angstroms)
            #yCoord1.set_valueOf_(molecule.y(at) * p4const.psi_bohr2angstroms)
            #zCoord1.set_valueOf_(molecule.z(at) * p4const.psi_bohr2angstroms)
            xCoord1 = api.dataWithUnitsType(unit='gc:bohr')
            yCoord1 = api.dataWithUnitsType(unit='gc:bohr')
            zCoord1 = api.dataWithUnitsType(unit='gc:bohr')
            xCoord1.set_valueOf_(molecule.x(at))
            yCoord1.set_valueOf_(molecule.y(at))
            zCoord1.set_valueOf_(molecule.z(at))
            # LAB 8jun2015: not getting masses from OB anymore so now dependent on qc programs
            #   current proposition is changing API so masses only go into CSX if relevant (e.g., vib)
            #   same situation as temperature
            atm = api.atomType(
                id='a' + str(at + 1),
                elementSymbol=molecule.symbol(at),
                atomMass=molecule.mass(at),  # psi4 uses mass of most common isotope; OB uses natural distribution mass
                xCoord3D=xCoord1,
                yCoord3D=yCoord1,
                zCoord3D=zCoord1,
                basisSet='bse:' + molBasis,
                calculatedAtomCharge=0,
                formalAtomCharge=0)
            #OBiatm += 1
            #OBcoord1 = api.coordinationType()
            #OBibond = 0
            #OBfor nb_atom in openbabel.OBAtomAtomIter(obatom):
            #OB    bond = obatom.GetBond(nb_atom)
            #OB    bond1 = api.bondType(
            #OB        id1='a' + str(obatom.GetId() + 1),
            #OB        id2='a' + str(nb_atom.GetId() + 1))
            #OB    if bond.GetBondOrder() == 1:
            #OB        bond1.set_valueOf_('single')
            #OB    elif bond.GetBondOrder() == 2:
            #OB        bond1.set_valueOf_('double')
            #OB    elif bond.GetBondOrder() == 3:
            #OB        bond1.set_valueOf_('triple')
            #OB    elif bond.GetBondOrder() == 5:
            #OB        bond1.set_valueOf_('aromatic')
            #OB    else:
            #OB        print('wrong bond order')
            #OB    coord1.add_bond(bond1)
            #OB    ibond += 1
            #OBcoord1.set_bondCount(ibond)
            #OBatm.set_coordination(coord1)
            mol1.add_atom(atm)
        ms1.add_molecule(mol1)
        cs1.set_molecularSystem(ms1)

        # molCalculation section: 1.5
        mc1 = api.mcalType(id='c1')
        qm1 = api.qmCalcType()
        srs1 = api.srsMethodType()
        psivars = psi4.get_variables()

        def form_ene(mandatoryPsivars, optionalPsivars={}, excessPsivars={}):
            """

            """
            ene = api.energiesType(unit='gc:hartree')
            for pv, csx in mandatoryPsivars.iteritems():
                term = api.energyType(type_=csx)
                term.set_valueOf_(psivars.pop(pv))
                ene.add_energy(term)
            for pv, csx in optionalPsivars.iteritems():
                if pv in psivars:
                    term = api.energyType(type_=csx)
                    term.set_valueOf_(psivars.pop(pv))
                    ene.add_energy(term)
            for pv in excessPsivars:
                if pv in psivars:
                    psivars.pop(pv)
            return ene

        # Reference stage- every calc has one
        if 'CCSD TOTAL ENERGY' in psivars or 'CCSD(T) TOTAL ENERGY' in psivars \
                or 'CISD TOTAL ENERGY' in psivars or 'FCI TOTAL ENERGY' in psivars \
                or 'QCISD TOTAL ENERGY' in psivars or 'QCISD(T) TOTAL ENERGY' in psivars:
            mdm1 = api.srsmdMethodType()
            # CCSD(T): 1.5
            if 'CCSD(T) TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'CCSD(T) CORRELATION ENERGY': 'gc:correlation',
                    'CCSD(T) TOTAL ENERGY': 'gc:electronic'}
                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed CCSD(T) computation""")

                block = api.resultType(  # TODO should be pointing to HF for correlation, maybe to MP2 for guess
                    methodology='gc:normal',  # TODO handle dfcc
                    spinType='gc:' + molSpin,  # TODO could have a closed-shell corl mtd atop open-shell scf?
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars))
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                mdm1.set_ccsd_t(block)
            # CCSD: 1.5
            elif 'CCSD TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'CCSD CORRELATION ENERGY': 'gc:correlation',
                    'CCSD TOTAL ENERGY': 'gc:electronic'}
                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed CCSD computation""")

                block = api.resultType(  # TODO should be pointing to HF for correlation, maybe to MP2 for guess
                    methodology='gc:normal',  # TODO handle dfcc
                    spinType='gc:' + molSpin,  # TODO could have a closed-shell corl mtd atop open-shell scf?
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars))
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                mdm1.set_ccsd(block)
            # CISD: 1.5
            elif 'CISD TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'CISD CORRELATION ENERGY': 'gc:correlation',
                    'CISD TOTAL ENERGY': 'gc:electronic'}
                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed CISD computation""")

                block = api.resultType(  # TODO should be pointing to HF for correlation, maybe to MP2 for guess
                    methodology='gc:normal',  # TODO handle dfcc
                    spinType='gc:' + molSpin,  # TODO could have a closed-shell corl mtd atop open-shell scf?
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars))
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                mdm1.set_cisd(block)
            # FCI: 1.5
            elif 'FCI TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'FCI CORRELATION ENERGY': 'gc:correlation',
                    'FCI TOTAL ENERGY': 'gc:electronic'}
                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed FCI computation""")

                block = api.resultType(  # TODO should be pointing to HF for correlation, maybe to MP2 for guess
                    methodology='gc:normal',  # TODO handle dfcc
                    spinType='gc:' + molSpin,  # TODO could have a closed-shell corl mtd atop open-shell scf?
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars))
                mdm1.set_fci(block)
            # QCISD(T): 1.5
            elif 'QCISD(T) TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'QCISD(T) CORRELATION ENERGY': 'gc:correlation',
                    'QCISD(T) TOTAL ENERGY': 'gc:electronic'}
                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed QCISD(T) computation""")

                block = api.resultType(  # TODO should be pointing to HF for correlation, maybe to MP2 for guess
                    methodology='gc:normal',  # TODO handle dfcc
                    spinType='gc:' + molSpin,  # TODO could have a closed-shell corl mtd atop open-shell scf?
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars))
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                mdm1.set_qcisd_t(block)
            # QCISD: 1.5
            elif 'QCISD TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'QCISD CORRELATION ENERGY': 'gc:correlation',
                    'QCISD TOTAL ENERGY': 'gc:electronic'}
                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed QCISD computation""")

                block = api.resultType(  # TODO should be pointing to HF for correlation, maybe to MP2 for guess
                    methodology='gc:normal',  # TODO handle dfcc
                    spinType='gc:' + molSpin,  # TODO could have a closed-shell corl mtd atop open-shell scf?
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars))
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                mdm1.set_qcisd(block)
            srs1.set_multipleDeterminant(mdm1)

        elif 'DFT TOTAL ENERGY' in psivars or 'HF TOTAL ENERGY' in psivars \
                or 'MP2 TOTAL ENERGY' in psivars or 'MP3 TOTAL ENERGY' in psivars \
                or 'MP4 TOTAL ENERGY' in psivars:
            sdm1 = api.srssdMethodType()
            # DFT 1.5
            if 'DFT TOTAL ENERGY' in psivars:  # TODO robust enough to avoid MP2C, etc.?
                mandatoryPsivars = {
                    'NUCLEAR REPULSION ENERGY': 'gc:nuclearRepulsion',
                    'DFT FUNCTIONAL TOTAL ENERGY': 'gc:dftFunctional',
                    'DFT TOTAL ENERGY': 'gc:electronic'}
                optionalPsivars = {
                    'DOUBLE-HYBRID CORRECTION ENERGY': 'gc:doubleHybrid correction',
                    'DISPERSION CORRECTION ENERGY': 'gc:dispersion correction'}
                excessPsivars = [
                    'MP2 TOTAL ENERGY',
                    'MP2 CORRELATION ENERGY',
                    'MP2 SAME-SPIN CORRELATION ENERGY']

                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed DFT computation""")

                block = api.resultType(
                    methodology='gc:normal',  # TODO handle dfhf, dfmp
                    spinType='gc:' + molSpin,
                    basisSet='bse:' + molBasis,
                    dftFunctional=name)  # TODO this'll need to be exported
                block.set_energies(form_ene(mandatoryPsivars, optionalPsivars, excessPsivars))
                if wfn:
                    block.set_waveFunction(wfn1)
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                block.set_properties(prop1)
                sdm1.set_dft(block)


            # post-reference block
            # MP4: 1.5
            elif 'MP4 TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'MP4 CORRELATION ENERGY': 'gc:correlation',
                    'MP4 TOTAL ENERGY': 'gc:electronic'}
                optionalPsivars = {
                    'MP4 SAME-SPIN CORRELATION ENERGY': 'gc:sameSpin correlation'}
                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed MP4 computation""")

                block = api.resultType(  # TODO should be pointing to HF for correlation
                    methodology='gc:normal',  # TODO handle dfmp
                    spinType='gc:' + molSpin,  # TODO could have a closed-shell corl mtd atop open-shell scf?
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars, optionalPsivars))
                if wfn:
                    block.set_waveFunction(wfn1)
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                block.set_properties(prop1)
                sdm1.set_mp4(block)

            # MP3: 1.5
            elif 'MP3 TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'MP3 CORRELATION ENERGY': 'gc:correlation',
                    'MP3 TOTAL ENERGY': 'gc:electronic'}
                optionalPsivars = {
                    'MP3 SAME-SPIN CORRELATION ENERGY': 'gc:sameSpin correlation'}
                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed MP3 computation""")

                block = api.resultType(  # TODO should be pointing to HF for correlation
                    methodology='gc:normal',  # TODO handle dfmp
                    spinType='gc:' + molSpin,  # TODO could have a closed-shell corl mtd atop open-shell scf?
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars, optionalPsivars))
                if wfn:
                    block.set_waveFunction(wfn1)
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                block.set_properties(prop1)
                sdm1.set_mp3(block)

            # MP2: 1.5
            elif 'MP2 TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'MP2 CORRELATION ENERGY': 'gc:correlation',
                    'MP2 TOTAL ENERGY': 'gc:electronic'}
                optionalPsivars = {
                    'MP2 SAME-SPIN CORRELATION ENERGY': 'gc:sameSpin correlation'}
                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed MP2 computation""")

                block = api.resultType(  # TODO should be pointing to HF for correlation
                    methodology='gc:normal',  # TODO handle dfmp
                    spinType='gc:' + molSpin,  # TODO could have a closed-shell corl mtd atop open-shell scf?
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars, optionalPsivars))
                if wfn:
                    block.set_waveFunction(wfn1)
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                block.set_properties(prop1)
                sdm1.set_mp2(block)

            # SCF: 1.5
            elif 'HF TOTAL ENERGY' in psivars:
                mandatoryPsivars = {
                    'NUCLEAR REPULSION ENERGY': 'gc:nuclearRepulsion',
                    'HF TOTAL ENERGY': 'gc:electronic'}

                if not all([pv in psivars for pv in mandatoryPsivars.keys()]):
                    raise CSXError("""Malformed HF computation""")

                block = api.resultType(
                    methodology='gc:normal',  # TODO handle dfhf, dfmp
                    spinType='gc:' + molSpin,
                    basisSet='bse:' + molBasis)
                block.set_energies(form_ene(mandatoryPsivars))
                if wfn:
                    block.set_waveFunction(wfn1)
                if hasFreq:
                    block.set_vibrationalAnalysis(vib1)
                block.set_properties(prop1)
                sdm1.set_abinitioScf(block)
            else:
                psi4.print_out("""\nCSX version {0} does not support """
                               """method {1} for {2}\n""".format(
                               csxVer, lowername, 'energies'))

            srs1.set_singleDeterminant(sdm1)

        #print('CSX not harvesting: ', ', '.join(psivars))

        qm1.set_singleReferenceState(srs1)
        mc1.set_quantumMechanics(qm1)
        cs1.set_molecularCalculation(mc1)

    else:
        print('The future CSX file is here')

    csxfile.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    cs1.export(csxfile, 0)
    csxfile.close()
Пример #48
0
P 4 1.00
        34.8564630000           0.0156480000
         7.8431310000           0.0981970000
         2.3062490000           0.3077680000
         0.7231640000           0.4924700000
P 1 1.00
         0.2148820000           1.0000000000
P 1 1.00
         0.0638500000           1.0000000000
D 2 1.00
         2.3062000000           0.2027000000
         0.7232000000           0.5791000000
D 2 1.00
         0.2149000000           0.7854500000
         0.0639000000           0.5338700000
****
""")

ccsd_e, wfn = psi4.properties('ccsd',properties=['dipole'],return_wfn=True)
psi4.oeprop(wfn,"DIPOLE", "QUADRUPOLE", title="(OEPROP)CC")
psi4.compare_values(psi4.get_variable("(OEPROP)CC DIPOLE X"), 0.000000000000,6,"CC DIPOLE X")             #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC DIPOLE Y"), 0.000000000000,6,"CC DIPOLE Y")             #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC DIPOLE Z"),-1.840334899884,6,"CC DIPOLE Z")             #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE XX"),-7.864006962064,6,"CC QUADRUPOLE XX")   #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE XY"), 0.000000000000,6,"CC QUADRUPOLE XY")   #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE XZ"), 0.000000000000,6,"CC QUADRUPOLE XZ")   #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE YY"),-4.537386915305,6,"CC QUADRUPOLE YY")   #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE YZ"), 0.000000000000,6,"CC QUADRUPOLE YZ")   #TEST
psi4.compare_values(psi4.get_variable("(OEPROP)CC QUADRUPOLE ZZ"),-6.325836255265,6,"CC QUADRUPOLE ZZ")   #TEST
psi4.core.print_variables()