Ejemplo n.º 1
0
def test_aci1():
    import math
    import psi4
    import forte
    from forte import forte_options

    ref_aci = -75.010199198896
    rel_tol = 1e-9
    abs_tol = 1e-8

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

    psi4.set_options({'basis': "sto-3g"})
    E_scf, wfn = psi4.energy('scf', return_wfn=True)
    state = forte.StateInfo(na=5, nb=5, multiplicity=1, twice_ms=0, irrep=0)
    dim = psi4.core.Dimension([4, 0, 1, 2])

    options = psi4.core.get_options()
    options.set_current_module('FORTE')
    forte_options.update_psi_options(options)

    forte.startup()
    forte.banner()
    mo_space_info = forte.make_mo_space_info(wfn, forte_options)
    ints = forte.make_forte_integrals(wfn, options, mo_space_info)

    scf_info = forte.SCFInfo(wfn)

    solver = forte.make_active_space_solver('ACI', state, scf_info,
                                            mo_space_info, ints, forte_options)
    energy = solver.compute_energy()

    assert math.isclose(energy, ref_aci, abs_tol=abs_tol, rel_tol=rel_tol)

    print("\n\nACI Energy = {}".format(energy))
    forte.cleanup()
Ejemplo n.º 2
0
def test_aci1():
    import math
    import psi4
    import forte
    from forte import forte_options

    ref_aci = -75.010199198896
    rel_tol = 1e-9
    abs_tol = 1e-8

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

    psi4.set_options({'basis': "sto-3g"})
    E_scf, wfn = psi4.energy('scf', return_wfn=True)
    state = forte.StateInfo(na=5, nb=5, multiplicity=1, twice_ms=0, irrep=0)
    dim = psi4.core.Dimension([4, 0, 1, 2])

    options = psi4.core.get_options()
    options.set_current_module('FORTE')
    forte_options.update_psi_options(options)

    forte.startup()
    forte.banner()
    mo_space_info = forte.make_mo_space_info(wfn, forte_options)    
    ints = forte.make_forte_integrals(wfn, options, mo_space_info)

    scf_info = forte.SCFInfo(wfn)

    solver = forte.make_active_space_solver('ACI',state,scf_info,mo_space_info, ints, forte_options)
    energy = solver.compute_energy()

    assert math.isclose(energy,ref_aci,abs_tol=abs_tol, rel_tol=rel_tol)

    print("\n\nACI Energy = {}".format(energy))
    forte.cleanup()
Ejemplo n.º 3
0
def prepare_forte_objects(wfn):
    """
    Take a psi4 wavefunction object and prepare the ForteIntegrals, SCFInfo, and MOSpaceInfo objects

    Parameters
    ----------
    wfn : psi4Wavefunction
        A psi4 Wavefunction object

    Returns
    -------
    tuple(ForteIntegrals, SCFInfo, MOSpaceInfo)
        a tuple containing the ForteIntegrals, SCFInfo, and MOSpaceInfo objects
    """
    # fill in the options object
    psi4_options = psi4.core.get_options()
    psi4_options.set_current_module('FORTE')
    options = forte.forte_options
    options.get_options_from_psi4(psi4_options)

    if ('DF' in options.get_str('INT_TYPE')):
        aux_basis = psi4.core.BasisSet.build(
            wfn.molecule(), 'DF_BASIS_MP2',
            psi4.core.get_global_option('DF_BASIS_MP2'), 'RIFIT',
            psi4.core.get_global_option('BASIS'))
        wfn.set_basisset('DF_BASIS_MP2', aux_basis)

    if (options.get_str('MINAO_BASIS')):
        minao_basis = psi4.core.BasisSet.build(
            wfn.molecule(), 'MINAO_BASIS', psi4_options.get_str('MINAO_BASIS'))
        wfn.set_basisset('MINAO_BASIS', minao_basis)

    # Prepare base objects
    scf_info = forte.SCFInfo(wfn)
    mo_space_info = forte.make_mo_space_info(wfn, options)
    ints = forte.make_forte_integrals(wfn, options, mo_space_info)

    return (ints, scf_info, mo_space_info)
Ejemplo n.º 4
0
def run_forte(name, **kwargs):
    r"""Function encoding sequence of PSI module and plugin calls so that
    forte can be called via :py:func:`~driver.energy`. For post-scf plugins.

    >>> energy('forte')

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

    # Compute a SCF reference, a wavefunction is return which holds the molecule used, orbitals
    # Fock matrices, and more
    ref_wfn = kwargs.get('ref_wfn', None)
    if ref_wfn is None:
        ref_wfn = psi4.driver.scf_helper(name, **kwargs)

    # Get the option object
    options = psi4.core.get_options()
    options.set_current_module('FORTE')
    forte.forte_options.update_psi_options(options)

    if ('DF' in options.get_str('INT_TYPE')):
        aux_basis = psi4.core.BasisSet.build(
            ref_wfn.molecule(), 'DF_BASIS_MP2',
            psi4.core.get_global_option('DF_BASIS_MP2'), 'RIFIT',
            psi4.core.get_global_option('BASIS'))
        ref_wfn.set_basisset('DF_BASIS_MP2', aux_basis)

    if (options.get_str('MINAO_BASIS')):
        minao_basis = psi4.core.BasisSet.build(ref_wfn.molecule(),
                                               'MINAO_BASIS',
                                               options.get_str('MINAO_BASIS'))
        ref_wfn.set_basisset('MINAO_BASIS', minao_basis)

    # Start Forte, initialize ambit
    my_proc_n_nodes = forte.startup()
    my_proc, n_nodes = my_proc_n_nodes

    # Print the banner
    forte.banner()

    # Create the MOSpaceInfo object
    mo_space_info = forte.make_mo_space_info(ref_wfn, forte.forte_options)

    # Create the AO subspace projector
    ps = forte.make_aosubspace_projector(ref_wfn, options)

    state = forte.make_state_info_from_psi_wfn(ref_wfn)
    scf_info = forte.SCFInfo(ref_wfn)
    state_weights_map = forte.make_state_weights_map(forte.forte_options,
                                                     ref_wfn)

    # Run a method
    job_type = options.get_str('JOB_TYPE')

    energy = 0.0
    if job_type != 'NONE':
        start = timeit.timeit()

        # Make an integral object
        ints = forte.make_forte_integrals(ref_wfn, options, mo_space_info)

        # Rotate orbitals before computation
        orb_type = options.get_str("ORBITAL_TYPE")
        if orb_type != 'CANONICAL':
            orb_t = forte.make_orbital_transformation(orb_type, scf_info,
                                                      forte.forte_options,
                                                      ints, mo_space_info)
            orb_t.compute_transformation()
            Ua = orb_t.get_Ua()
            Ub = orb_t.get_Ub()

            ints.rotate_orbitals(Ua, Ub)

        # Run a method
        if (job_type == 'NEWDRIVER'):
            energy = forte_driver(state_weights_map, scf_info,
                                  forte.forte_options, ints, mo_space_info)
        else:
            energy = forte.forte_old_methods(ref_wfn, options, ints,
                                             mo_space_info)

        end = timeit.timeit()
        #print('\n\n  Your calculation took ', (end - start), ' seconds');

    # Close ambit, etc.
    forte.cleanup()

    psi4.core.set_scalar_variable('CURRENT ENERGY', energy)
    return ref_wfn
Ejemplo n.º 5
0
def test_sparse_ci2():
    import math
    import psi4
    import forte
    import itertools
    import numpy as np
    import pytest
    from forte import forte_options

    ref_fci = -5.623851783330647

    psi4.core.clean()
    # need to clean the options otherwise this job will interfere
    forte.clean_options()

    h2o = psi4.geometry("""
     He
     He 1 1.0
    """)

    psi4.set_options({'basis': 'cc-pVDZ'})
    _, wfn = psi4.energy('scf', return_wfn=True)
    na = wfn.nalpha()
    nb = wfn.nbeta()
    nirrep = wfn.nirrep()
    wfn_symmetry = 0

    forte.startup()
    forte.banner()

    psi4_options = psi4.core.get_options()
    psi4_options.set_current_module('FORTE')
    forte_options.get_options_from_psi4(psi4_options)

    # Setup forte and prepare the active space integral class
    nmopi = wfn.nmopi()
    point_group = wfn.molecule().point_group().symbol()
    mo_space_info = forte.make_mo_space_info(nmopi, point_group, forte_options)
    ints = forte.make_ints_from_psi4(wfn, forte_options, mo_space_info)
    as_ints = forte.make_active_space_ints(mo_space_info, ints, 'ACTIVE', ['RESTRICTED_DOCC'])

    print('\n\n  => Sparse FCI Test <=')
    print('  Number of irreps: {}'.format(nirrep))
    nmo = wfn.nmo()
    nmopi = [wfn.nmopi()[h] for h in range(nirrep)]
    nmopi_str = [str(wfn.nmopi()[h]) for h in range(nirrep)]
    mo_sym = []
    for h in range(nirrep):
        for i in range(nmopi[h]):
            mo_sym.append(h)

    print('  Number of orbitals per irreps: [{}]'.format(','.join(nmopi_str)))
    print('  Symmetry of the MOs: ', mo_sym)

    hf_reference = forte.Determinant()
    hf_reference.create_alfa_bit(0)
    hf_reference.create_beta_bit(0)
    print('  Hartree-Fock determinant: {}'.format(hf_reference.str(10)))

    # Compute the HF energy
    hf_energy = as_ints.nuclear_repulsion_energy() + as_ints.slater_rules(hf_reference, hf_reference)
    print('  Nuclear repulsion energy: {}'.format(as_ints.nuclear_repulsion_energy()))
    print('  Reference energy: {}'.format(hf_energy))

    # Build a list of determinants
    orblist = [i for i in range(nmo)]
    dets = []
    for astr in itertools.combinations(orblist, na):
        for bstr in itertools.combinations(orblist, nb):
            sym = 0
            d = forte.Determinant()
            for a in astr:
                d.create_alfa_bit(a)
                sym = sym ^ mo_sym[a]
            for b in bstr:
                d.create_beta_bit(b)
                sym = sym ^ mo_sym[b]
            if (sym == wfn_symmetry):
                dets.append(d)
                print('  Determinant {} has symmetry {}'.format(d.str(nmo), sym))

    print(f'\n  Size of the derminant basis: {len(dets)}')

    energy, evals, evecs, spin = forte.diag(dets, as_ints, 1, 1, "FULL")

    print(energy)

    efci = energy[0] + as_ints.nuclear_repulsion_energy()

    print('\n  FCI Energy: {}\n'.format(efci))

    assert efci == pytest.approx(ref_fci, abs=1e-9)

    # Clean up forte (necessary)
    forte.cleanup()
Ejemplo n.º 6
0
def prepare_forte_objects(wfn,
                          mo_spaces=None,
                          active_space='ACTIVE',
                          core_spaces=['RESTRICTED_DOCC'],
                          localize=False,
                          localize_spaces=[]):
    """Take a psi4 wavefunction object and prepare the ForteIntegrals, SCFInfo, and MOSpaceInfo objects

    Parameters
    ----------
    wfn : psi4 Wavefunction
        A psi4 Wavefunction object
    mo_spaces : dict
        A dictionary with the size of each space (e.g., {'ACTIVE' : [3]})
    active_space : str
        The MO space treated as active (default: 'ACTIVE')
    core_spaces : list(str)
        The MO spaces treated as active (default: ['RESTRICTED_DOCC'])
    localize : bool
        Do localize the orbitals? (defaul: False)
    localize_spaces : list(str)
        A list of spaces to localize (default: [])
    Returns
    -------
    tuple(ForteIntegrals, ActiveSpaceIntegrals, SCFInfo, MOSpaceInfo, map(StateInfo : list)
        a tuple containing the ForteIntegrals, SCFInfo, and MOSpaceInfo objects and a map of states and weights
    """
    # fill in the options object
    psi4_options = psi4.core.get_options()
    psi4_options.set_current_module('FORTE')
    options = forte.forte_options
    options.get_options_from_psi4(psi4_options)

    if ('DF' in options.get_str('INT_TYPE')):
        aux_basis = psi4.core.BasisSet.build(
            wfn.molecule(), 'DF_BASIS_MP2',
            psi4.core.get_global_option('DF_BASIS_MP2'), 'RIFIT',
            psi4.core.get_global_option('BASIS'))
        wfn.set_basisset('DF_BASIS_MP2', aux_basis)

    if (options.get_str('MINAO_BASIS')):
        minao_basis = psi4.core.BasisSet.build(
            wfn.molecule(), 'MINAO_BASIS', psi4_options.get_str('MINAO_BASIS'))
        wfn.set_basisset('MINAO_BASIS', minao_basis)

    # Prepare base objects
    scf_info = forte.SCFInfo(wfn)

    nmopi = wfn.nmopi()
    point_group = wfn.molecule().point_group().symbol()

    if mo_spaces == None:
        mo_space_info = forte.make_mo_space_info(nmopi, point_group, options)
    else:
        mo_space_info = forte.make_mo_space_info_from_map(
            nmopi, point_group, mo_spaces, [])

    state_weights_map = forte.make_state_weights_map(options, mo_space_info)

    ints = forte.make_ints_from_psi4(wfn, options, mo_space_info)

    if localize:
        localizer = forte.Localize(forte.forte_options, ints, mo_space_info)
        localizer.set_orbital_space(localize_spaces)
        localizer.compute_transformation()
        Ua = localizer.get_Ua()
        ints.rotate_orbitals(Ua, Ua)

    # the space that defines the active orbitals. We select only the 'ACTIVE' part
    # the space(s) with non-active doubly occupied orbitals

    as_ints = forte.make_active_space_ints(mo_space_info, ints, active_space,
                                           core_spaces)

    return (ints, as_ints, scf_info, mo_space_info, state_weights_map)
Ejemplo n.º 7
0
def gradient_forte(name, **kwargs):
    r"""Function encoding sequence of PSI module and plugin calls so that
    forte can be called via :py:func:`~driver.energy`. For post-scf plugins.

    >>> gradient('forte') 
        available for : CASSCF

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

    # Compute a SCF reference, a wavefunction is return which holds the molecule used, orbitals
    # Fock matrices, and more
    ref_wfn = kwargs.get('ref_wfn', None)
    if ref_wfn is None:
        ref_wfn = psi4.driver.scf_helper(name, **kwargs)

    # Get the psi4 option object
    optstash = p4util.OptionsState(['GLOBALS', 'DERTYPE'])
    psi4_options = psi4.core.get_options()
    psi4_options.set_current_module('FORTE')

    # Get the forte option object
    options = forte.forte_options
    options.get_options_from_psi4(psi4_options)

    if ('DF' in options.get_str('INT_TYPE')):
        raise Exception('analytic gradient is not implemented for density fitting')

    if (options.get_str('MINAO_BASIS')):
        minao_basis = psi4.core.BasisSet.build(ref_wfn.molecule(), 'MINAO_BASIS',
                                               options.get_str('MINAO_BASIS'))
        ref_wfn.set_basisset('MINAO_BASIS', minao_basis)

    # Start Forte, initialize ambit
    my_proc_n_nodes = forte.startup()
    my_proc, n_nodes = my_proc_n_nodes

    # Print the banner
    forte.banner()

    # Create the MOSpaceInfo object
    mo_space_info = forte.make_mo_space_info(ref_wfn, options)

    # Call methods that project the orbitals (AVAS, embedding)
    mo_space_info = orbital_projection(ref_wfn, options, mo_space_info)

    state = forte.make_state_info_from_psi_wfn(ref_wfn)
    scf_info = forte.SCFInfo(ref_wfn)
    state_weights_map = forte.make_state_weights_map(options,ref_wfn)

    # Run a method
    job_type = options.get_str('JOB_TYPE')

    energy = 0.0

    if not job_type == 'CASSCF':
        raise Exception('analytic gradient is only implemented for CASSCF')

    start = time.time()

    # Make an integral object
    ints = forte.make_forte_integrals(ref_wfn, options, mo_space_info)

    # Rotate orbitals before computation
    orb_type = options.get_str("ORBITAL_TYPE")
    if orb_type != 'CANONICAL':
        orb_t = forte.make_orbital_transformation(orb_type, scf_info, options, ints, mo_space_info)
        orb_t.compute_transformation()
        Ua = orb_t.get_Ua()
        Ub = orb_t.get_Ub()

        ints.rotate_orbitals(Ua,Ub)

    # Run gradient computation
    energy = forte.forte_old_methods(ref_wfn, options, ints, mo_space_info)
    derivobj = psi4.core.Deriv(ref_wfn)
    derivobj.set_deriv_density_backtransformed(True)
    derivobj.set_ignore_reference(True)
    grad = derivobj.compute() #psi4.core.DerivCalcType.Correlated
    ref_wfn.set_gradient(grad)    
    optstash.restore()        

    end = time.time()
    #print('\n\n  Your calculation took ', (end - start), ' seconds');

    # Close ambit, etc.
    forte.cleanup()

    return ref_wfn
Ejemplo n.º 8
0
def run_forte(name, **kwargs):
    r"""Function encoding sequence of PSI module and plugin calls so that
    forte can be called via :py:func:`~driver.energy`. For post-scf plugins.

    >>> energy('forte')

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

    # Compute a SCF reference, a wavefunction is return which holds the molecule used, orbitals
    # Fock matrices, and more
    ref_wfn = kwargs.get('ref_wfn', None)
    if ref_wfn is None:
        ref_wfn = psi4.driver.scf_helper(name, **kwargs)

    # Get the option object
    psi4_options = psi4.core.get_options()
    psi4_options.set_current_module('FORTE')

    # Get the forte option object
    options = forte.forte_options
    options.get_options_from_psi4(psi4_options)

    if ('DF' in options.get_str('INT_TYPE')):
        aux_basis = psi4.core.BasisSet.build(ref_wfn.molecule(), 'DF_BASIS_MP2',
                                         options.get_str('DF_BASIS_MP2'),
                                         'RIFIT', options.get_str('BASIS'))
        ref_wfn.set_basisset('DF_BASIS_MP2', aux_basis)

    if (options.get_str('MINAO_BASIS')):
        minao_basis = psi4.core.BasisSet.build(ref_wfn.molecule(), 'MINAO_BASIS',
                                               options.get_str('MINAO_BASIS'))
        ref_wfn.set_basisset('MINAO_BASIS', minao_basis)

    # Start Forte, initialize ambit
    my_proc_n_nodes = forte.startup()
    my_proc, n_nodes = my_proc_n_nodes

    # Print the banner
    forte.banner()

    # Create the MOSpaceInfo object
    mo_space_info = forte.make_mo_space_info(ref_wfn, options)

    # Call methods that project the orbitals (AVAS, embedding)
    mo_space_info = orbital_projection(ref_wfn, options, mo_space_info)

    # Averaging spin multiplets if doing spin-adapted computation
    if options.get_str('CORRELATION_SOLVER') == 'SA-MRDSRG':
        options_dict = options.dict()
        options_dict['SPIN_AVG_DENSITY']['value'] = True
        options.set_dict(options_dict)

    state = forte.make_state_info_from_psi_wfn(ref_wfn)
    scf_info = forte.SCFInfo(ref_wfn)
    state_weights_map = forte.make_state_weights_map(options,ref_wfn)

    # Run a method
    job_type = options.get_str('JOB_TYPE')

    energy = 0.0

    if job_type == 'NONE':
        forte.cleanup()
        return ref_wfn

    start_pre_ints = time.time()

    # Make an integral object
    ints = forte.make_forte_integrals(ref_wfn, options, mo_space_info)

    start = time.time()

    # Rotate orbitals before computation (e.g. localization, MP2 natural orbitals, etc.)
    orb_type = options.get_str("ORBITAL_TYPE")
    if orb_type != 'CANONICAL':
        orb_t = forte.make_orbital_transformation(orb_type, scf_info, options, ints, mo_space_info)
        orb_t.compute_transformation()
        Ua = orb_t.get_Ua()
        Ub = orb_t.get_Ub()
        ints.rotate_orbitals(Ua,Ub)

    # Run a method
    if (job_type == 'NEWDRIVER'):
        energy = forte_driver(state_weights_map, scf_info, options, ints, mo_space_info)
    else:
        energy = forte.forte_old_methods(ref_wfn, options, ints, mo_space_info)

    end = time.time()

    # Close ambit, etc.
    forte.cleanup()

    psi4.core.set_scalar_variable('CURRENT ENERGY', energy)

    psi4.core.print_out(f'\n\n  Time to prepare integrals: {start - start_pre_ints:12.3f} seconds')
    psi4.core.print_out(f'\n  Time to run job          : {end - start:12.3f} seconds')
    psi4.core.print_out(f'\n  Total                    : {end - start:12.3f} seconds')
    return ref_wfn
Ejemplo n.º 9
0
def test_sparse_ci():
    import math
    import psi4
    import forte
    import itertools
    import numpy as np
    import pytest
    from forte import forte_options

    ref_fci = -1.101150330132956

    psi4.core.clean()

    h2o = psi4.geometry("""
     H
     H 1 1.0
    """)

    psi4.set_options({'basis': 'sto-3g'})
    E_scf, wfn = psi4.energy('scf', return_wfn=True)
    na = wfn.nalpha()
    nb = wfn.nbeta()
    nirrep = wfn.nirrep()
    wfn_symmetry = 0

    forte.startup()
    forte.banner()

    psi4_options = psi4.core.get_options()
    psi4_options.set_current_module('FORTE')
    forte_options.get_options_from_psi4(psi4_options)

    # Setup forte and prepare the active space integral class
    mo_space_info = forte.make_mo_space_info(wfn, forte_options)
    ints = forte.make_forte_integrals(wfn, forte_options, mo_space_info)
    as_ints = forte.make_active_space_ints(mo_space_info, ints, 'ACTIVE',
                                           ['RESTRICTED_DOCC'])
    as_ints.print()

    print('\n\n  => Sparse FCI Test <=')
    print('  Number of irreps: {}'.format(nirrep))
    nmo = wfn.nmo()
    nmopi = [wfn.nmopi()[h] for h in range(nirrep)]
    nmopi_str = [str(wfn.nmopi()[h]) for h in range(nirrep)]
    mo_sym = []
    for h in range(nirrep):
        for i in range(nmopi[h]):
            mo_sym.append(h)

    print('  Number of orbitals per irreps: [{}]'.format(','.join(nmopi_str)))
    print('  Symmetry of the MOs: ', mo_sym)

    hf_reference = forte.Determinant()
    hf_reference.create_alfa_bit(0)
    hf_reference.create_beta_bit(0)
    print('  Hartree-Fock determinant: {}'.format(hf_reference.str(2)))

    # Compute the HF energy
    hf_energy = as_ints.nuclear_repulsion_energy() + as_ints.slater_rules(
        hf_reference, hf_reference)
    print('  Nuclear repulsion energy: {}'.format(
        as_ints.nuclear_repulsion_energy()))
    print('  Reference energy: {}'.format(hf_energy))

    # Build a list of determinants
    orblist = [i for i in range(nmo)]
    dets = []
    for astr in itertools.combinations(orblist, na):
        for bstr in itertools.combinations(orblist, nb):
            sym = 0
            d = forte.Determinant()
            for a in astr:
                d.create_alfa_bit(a)
                sym = sym ^ mo_sym[a]
            for b in bstr:
                d.create_beta_bit(b)
                sym = sym ^ mo_sym[b]
            if (sym == wfn_symmetry):
                dets.append(d)
                print('  Determinant {} has symmetry {}'.format(
                    d.str(nmo), sym))

    # Build the Hamiltonian matrix using 'slater_rules'
    nfci = len(dets)
    H = np.ndarray((nfci, nfci))
    for I in range(nfci):
        # off-diagonal terms
        for J in range(I + 1, nfci):
            HIJ = as_ints.slater_rules(dets[I], dets[J])
            H[I][J] = H[J][I] = HIJ
        # diagonal term
        H[I][I] = as_ints.nuclear_repulsion_energy() + as_ints.slater_rules(
            dets[I], dets[I])

    # Find the lowest eigenvalue
    efci = np.linalg.eigh(H)[0][0]

    print('\n  FCI Energy: {}\n'.format(efci))

    assert efci == pytest.approx(ref_fci, 1.0e-9)

    # Clean up forte (necessary)
    forte.cleanup()
Ejemplo n.º 10
0
def prepare_forte_objects_from_fcidump(options, path='.'):
    fcidump_file = options.get_str('FCIDUMP_FILE')
    filename = pathlib.Path(path) / fcidump_file
    psi4.core.print_out(
        f'\n  Reading integral information from FCIDUMP file {filename}')
    fcidump = forte.proc.fcidump_from_file(filename, convert_to_psi4=True)

    irrep_size = {
        'c1': 1,
        'ci': 2,
        'c2': 2,
        'cs': 2,
        'd2': 4,
        'c2v': 4,
        'c2h': 4,
        'd2h': 8
    }

    nmo = len(fcidump['orbsym'])
    if 'pntgrp' in fcidump:
        nirrep = irrep_size[fcidump['pntgrp'].lower()]
        nmopi_list = [fcidump['orbsym'].count(h) for h in range(nirrep)]
    else:
        fcidump['pntgrp'] = 'C1'  # set the point group to C1
        fcidump['isym'] = 0  # shift by -1
        nirrep = 1
        nmopi_list = [nmo]

    nmopi_offset = [sum(nmopi_list[0:h]) for h in range(nirrep)]

    nmopi = psi4.core.Dimension(nmopi_list)

    # Create the MOSpaceInfo object
    mo_space_info = forte.make_mo_space_info(nmopi, fcidump['pntgrp'], options)

    # Call methods that project the orbitals (AVAS, embedding)
    # skipped due to lack of functionality

    # manufacture a SCFInfo object from the FCIDUMP file (this assumes C1 symmetry)
    nel = fcidump['nelec']
    ms2 = fcidump['ms2']
    na = (nel + ms2) // 2
    nb = nel - na
    if fcidump['pntgrp'] == 'C1':
        doccpi = psi4.core.Dimension([nb])
        soccpi = psi4.core.Dimension([ms2])
    else:
        doccpi = options.get_int_list('FCIDUMP_DOCC')
        soccpi = options.get_int_list('FCIDUMP_SOCC')
        if len(doccpi) + len(soccpi) == 0:
            print(
                'Reading a FCIDUMP file that uses symmetry but no DOCC and SOCC is specified.'
            )
            print(
                'Use the FCIDUMP_DOCC and FCIDUMP_SOCC options to specify the number of occupied orbitals per irrep.'
            )
            doccpi = psi4.core.Dimension([0] * nirrep)
            soccpi = psi4.core.Dimension([0] * nirrep)

    if 'epsilon' in fcidump:
        epsilon_a = psi4.core.Vector.from_array(fcidump['epsilon'])
        epsilon_b = psi4.core.Vector.from_array(fcidump['epsilon'])
    else:
        # manufacture Fock matrices
        epsilon_a = psi4.core.Vector(nmo)
        epsilon_b = psi4.core.Vector(nmo)
        hcore = fcidump['hcore']
        eri = fcidump['eri']
        nmo = fcidump['norb']
        for i in range(nmo):
            val = hcore[i, i]
            for h in range(nirrep):
                for j in range(nmopi_offset[h],
                               nmopi_offset[h] + doccpi[h] + soccpi[h]):
                    val += eri[i, i, j, j] - eri[i, j, i, j]
                for j in range(nmopi_offset[h], nmopi_offset[h] + doccpi[h]):
                    val += eri[i, i, j, j]
            epsilon_a.set(i, val)

            val = hcore[i, i]
            for h in range(nirrep):
                for j in range(nmopi_offset[h],
                               nmopi_offset[h] + doccpi[h] + soccpi[h]):
                    val += eri[i, i, j, j]
                for j in range(nmopi_offset[h], nmopi_offset[h] + doccpi[h]):
                    val += eri[i, i, j, j] - eri[i, j, i, j]
            epsilon_b.set(i, val)

    scf_info = forte.SCFInfo(nmopi, doccpi, soccpi, 0.0, epsilon_a, epsilon_b)

    state_info = make_state_info_from_fcidump(fcidump, options)
    state_weights_map = {state_info: [1.0]}
    return (state_weights_map, mo_space_info, scf_info, fcidump)
Ejemplo n.º 11
0
def prepare_psi4_ref_wfn(options, **kwargs):
    """
    Prepare a Psi4 Wavefunction as reference for Forte.
    :param options: a ForteOptions object for options
    :param kwargs: named arguments associated with Psi4
    :return: (the processed Psi4 Wavefunction, a Forte MOSpaceInfo object)

    Notes:
        We will create a new Psi4 Wavefunction (wfn_new) if necessary.

        1. For an empty ref_wfn, wfn_new will come from Psi4 SCF or MCSCF.

        2. For a valid ref_wfn, we will test the orbital orthonormality against molecule.
           If the orbitals from ref_wfn are consistent with the active geometry,
           wfn_new will simply be a link to ref_wfn.
           If not, we will rerun a Psi4 SCF and orthogonalize orbitals, where
           wfn_new comes from this new Psi4 SCF computation.
    """
    p4print = psi4.core.print_out

    # grab reference Wavefunction and Molecule from kwargs
    kwargs = p4util.kwargs_lower(kwargs)

    ref_wfn = kwargs.get('ref_wfn', None)

    molecule = kwargs.pop('molecule', psi4.core.get_active_molecule())
    point_group = molecule.point_group().symbol()

    # try to read orbitals from file
    Ca = read_orbitals() if options.get_bool('READ_ORBITALS') else None

    need_orbital_check = True
    fresh_ref_wfn = True if ref_wfn is None else False

    if ref_wfn is None:
        ref_type = options.get_str('REF_TYPE')
        p4print('\n  No reference wave function provided for Forte.'
                f' Computing {ref_type} orbitals using Psi4 ...\n')

        # no warning printing for MCSCF
        job_type = options.get_str('JOB_TYPE')
        do_mcscf = (job_type in ["CASSCF", "MCSCF_TWO_STEP"]
                    or options.get_bool("CASSCF_REFERENCE"))

        # run Psi4 SCF or MCSCF
        ref_wfn = run_psi4_ref(ref_type, molecule, not do_mcscf, **kwargs)

        need_orbital_check = False if Ca is None else True
    else:
        # Ca from file has higher priority than that of ref_wfn
        Ca = ref_wfn.Ca().clone() if Ca is None else Ca

    # build Forte MOSpaceInfo
    nmopi = ref_wfn.nmopi()
    mo_space_info = forte.make_mo_space_info(nmopi, point_group, options)

    # do we need to check MO overlap?
    if not need_orbital_check:
        wfn_new = ref_wfn
    else:
        # test if input Ca has the correct dimension
        if Ca.rowdim() != nmopi or Ca.coldim() != nmopi:
            raise ValueError(
                "Invalid orbitals: different basis set / molecule")

        new_S = psi4.core.Wavefunction.build(molecule,
                                             options.get_str("BASIS")).S()

        if check_MO_orthonormality(new_S, Ca):
            wfn_new = ref_wfn
            wfn_new.Ca().copy(Ca)
        else:
            if fresh_ref_wfn:
                wfn_new = ref_wfn
                wfn_new.Ca().copy(ortho_orbs_forte(wfn_new, mo_space_info, Ca))
            else:
                p4print("\n  Perform new SCF at current geometry ...\n")

                kwargs_copy = {
                    k: v
                    for k, v in kwargs.items() if k != 'ref_wfn'
                }
                wfn_new = run_psi4_ref('scf', molecule, False, **kwargs_copy)

                # orthonormalize orbitals
                wfn_new.Ca().copy(ortho_orbs_forte(wfn_new, mo_space_info, Ca))

                # copy wfn_new to ref_wfn
                ref_wfn.shallow_copy(wfn_new)

    # set DF and MINAO basis
    if 'DF' in options.get_str('INT_TYPE'):
        aux_basis = psi4.core.BasisSet.build(molecule, 'DF_BASIS_MP2',
                                             options.get_str('DF_BASIS_MP2'),
                                             'RIFIT', options.get_str('BASIS'))
        wfn_new.set_basisset('DF_BASIS_MP2', aux_basis)

    if options.get_str('MINAO_BASIS'):
        minao_basis = psi4.core.BasisSet.build(molecule, 'MINAO_BASIS',
                                               options.get_str('MINAO_BASIS'))
        wfn_new.set_basisset('MINAO_BASIS', minao_basis)

    return wfn_new, mo_space_info
Ejemplo n.º 12
0
def run_forte(name, **kwargs):
    r"""Function encoding sequence of PSI module and plugin calls so that
    forte can be called via :py:func:`~driver.energy`. For post-scf plugins.

    >>> energy('forte')

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

    # Compute a SCF reference, a wavefunction is return which holds the molecule used, orbitals
    # Fock matrices, and more
    ref_wfn = kwargs.get('ref_wfn', None)
    if ref_wfn is None:
        ref_wfn = psi4.driver.scf_helper(name, **kwargs)

    # Get the option object
    options = psi4.core.get_options()
    options.set_current_module('FORTE')
    forte.forte_options.update_psi_options(options)

    if ('DF' in options.get_str('INT_TYPE')):
        aux_basis = psi4.core.BasisSet.build(ref_wfn.molecule(), 'DF_BASIS_MP2',
                                         psi4.core.get_global_option('DF_BASIS_MP2'),
                                         'RIFIT', psi4.core.get_global_option('BASIS'))
        ref_wfn.set_basisset('DF_BASIS_MP2', aux_basis)

    if (options.get_str('MINAO_BASIS')):
        minao_basis = psi4.core.BasisSet.build(ref_wfn.molecule(), 'MINAO_BASIS',
                                               options.get_str('MINAO_BASIS'))
        ref_wfn.set_basisset('MINAO_BASIS', minao_basis)

    # Start Forte, initialize ambit
    my_proc_n_nodes = forte.startup()
    my_proc, n_nodes = my_proc_n_nodes

    # Print the banner
    forte.banner()

    # Create the MOSpaceInfo object
    mo_space_info = forte.make_mo_space_info(ref_wfn, forte.forte_options)

    # Call methods that project the orbitals (AVAS, embedding)
    orbital_projection(ref_wfn, options)

    state = forte.make_state_info_from_psi_wfn(ref_wfn)
    scf_info = forte.SCFInfo(ref_wfn)
    state_weights_map = forte.make_state_weights_map(forte.forte_options,ref_wfn)

    # Run a method
    job_type = options.get_str('JOB_TYPE')

    energy = 0.0

    if job_type == 'NONE':
        forte.cleanup()
        return ref_wfn

    start = timeit.timeit()

    # Make an integral object
    ints = forte.make_forte_integrals(ref_wfn, options, mo_space_info)

    # Rotate orbitals before computation
    orb_type = options.get_str("ORBITAL_TYPE")
    if orb_type != 'CANONICAL':
        orb_t = forte.make_orbital_transformation(orb_type, scf_info, forte.forte_options, ints, mo_space_info)
        orb_t.compute_transformation()
        Ua = orb_t.get_Ua()
        Ub = orb_t.get_Ub()

        ints.rotate_orbitals(Ua,Ub)

    # Run a method
    if (job_type == 'NEWDRIVER'):
        energy = forte_driver(state_weights_map, scf_info, forte.forte_options, ints, mo_space_info)
    else:
        energy = forte.forte_old_methods(ref_wfn, options, ints, mo_space_info)

    end = timeit.timeit()
    #print('\n\n  Your calculation took ', (end - start), ' seconds');

    # Close ambit, etc.
    forte.cleanup()

    psi4.core.set_scalar_variable('CURRENT ENERGY', energy)
    return ref_wfn