Beispiel #1
0
def rohf_wag(atoms, noccsh=None, f=None, a=None, b=None, **kwargs):
    """\
    rohf(atoms,noccsh=None,f=None,a=None,b=None,**kwargs):
        Restricted open shell HF driving routine

    atoms      A Molecule object containing the system of interest
    """
    ConvCriteria = kwargs.get('ConvCriteria', settings.ConvergenceCriteria)
    MaxIter = kwargs.get('MaxIter', settings.MaxIter)
    DoAveraging = kwargs.get('DoAveraging', settings.Averaging)
    verbose = kwargs.get('verbose')

    bfs = getbasis(atoms, **kwargs)

    S, h, Ints = getints(bfs, atoms, **kwargs)

    nel = atoms.get_nel()

    orbs = kwargs.get('orbs')
    if orbs is None:
        orbe, orbs = geigh(h, nS)

    nclosed, nopen = atoms.get_closedopen()
    nocc = nopen + nclosed
    if not noccsh: noccsh = get_noccsh(nclosed, nopen)
    nsh = len(noccsh)
    nbf = norb = len(bfs)
    if not f:
        f, a, b = get_fab(nclosed, nopen)

    if verbose:
        print "ROHF calculation"
        print "nsh = ", nsh
        print "noccsh = ", noccsh
        print "f = ", f
        print "a_ij: "
        for i in xrange(nsh):
            for j in xrange(i + 1):
                print a[i, j],
            print
        print "b_ij: "
        for i in xrange(nsh):
            for j in xrange(i + 1):
                print b[i, j],
            print
    enuke = atoms.get_enuke()
    energy = eold = 0.
    for i in xrange(MaxIter):
        Ds = get_os_dens(orbs, f, noccsh)
        Hs = get_os_hams(Ints, Ds)
        orbs = rotion(orbs, h, Hs, f, a, b, noccsh)
        orbe, orbs = ocbse(orbs, h, Hs, f, a, b, noccsh)
        orthogonalize(orbs, S)
        # Compute the energy
        eone = sum(f[ish] * trace2(Ds[ish], h) for ish in xrange(nsh))
        energy = enuke + eone + sum(orbe[:nocc])
        print energy, eone
        if abs(energy - eold) < ConvCriteria: break
        eold = energy
    return energy, orbe, orbs
Beispiel #2
0
def gamess_basisInfo(mol, basis_set):
    atom_types = [atno2type(atom.atno) for atom in mol.atoms]
    bfs = getbasis(mol, basis_set)
    currentId = -1
    basis_str = ""
    shell_id = 1
    gauss_id = 1
    for bfindx in range(len(bfs)):
        bf = bfs[bfindx]
        if bf.atid != currentId:
            currentId = bf.atid
            basis_str += '%s\n\n' % (atom_types[bf.atid])
        for prim in bf.prims:
            if prim.powers[1] == 0 and prim.powers[2] == 0:
                sym = power2sym(prim.powers)
                basis_str += "      {:d} {:s} {:d}".format(
                    shell_id, sym, gauss_id)
                basis_str += "      {:12.7f}    {:12.12f}\n".format(
                    prim.exp, prim.coef)
                gauss_id += 1
                count = True
        if count:
            shell_id += 1
            basis_str += '\n'
            count = False
    return basis_str, shell_id - 1
Beispiel #3
0
def rohf_wag(atoms,noccsh=None,f=None,a=None,b=None,**kwargs):
    """\
    rohf(atoms,noccsh=None,f=None,a=None,b=None,**kwargs):
        Restricted open shell HF driving routine

    atoms      A Molecule object containing the system of interest
    """
    ConvCriteria = kwargs.get('ConvCriteria',settings.ConvergenceCriteria)
    MaxIter = kwargs.get('MaxIter',settings.MaxIter)
    DoAveraging = kwargs.get('DoAveraging',settings.Averaging)
    verbose = kwargs.get('verbose')

    bfs = getbasis(atoms,**kwargs)

    S,h,Ints = getints(bfs,atoms,**kwargs)

    nel = atoms.get_nel()

    orbs = kwargs.get('orbs')
    if orbs is None:
        orbe,orbs = geigh(h,nS)

    nclosed,nopen = atoms.get_closedopen()
    nocc = nopen+nclosed
    if not noccsh: noccsh = get_noccsh(nclosed,nopen)
    nsh = len(noccsh)
    nbf = norb = len(bfs)
    if not f:
        f,a,b = get_fab(nclosed,nopen)

    if verbose:
        print "ROHF calculation"
        print "nsh = ",nsh
        print "noccsh = ",noccsh
        print "f = ",f
        print "a_ij: "
        for i in xrange(nsh):
            for j in xrange(i+1):
                print a[i,j],
            print
        print "b_ij: "
        for i in xrange(nsh):
            for j in xrange(i+1):
                print b[i,j],
            print
    enuke = atoms.get_enuke()
    energy = eold = 0.
    for i in xrange(MaxIter):
        Ds = get_os_dens(orbs,f,noccsh)
        Hs = get_os_hams(Ints,Ds)
        orbs = rotion(orbs,h,Hs,f,a,b,noccsh)
        orbe,orbs = ocbse(orbs,h,Hs,f,a,b,noccsh)
        orthogonalize(orbs,S)
        # Compute the energy
        eone = sum(f[ish]*trace2(Ds[ish],h) for ish in xrange(nsh))
        energy = enuke+eone+sum(orbe[:nocc])
        print energy,eone
        if abs(energy-eold) < ConvCriteria: break
        eold = energy
    return energy,orbe,orbs
Beispiel #4
0
    def __init__(self,molecule,**kwargs):
        from PyQuante.Ints import getbasis
        from PyQuante.Basis.Tools import get_basis_data

        self.bfs = getbasis(molecule,**kwargs)
        logging.info("%d basis functions" % len(self.bfs))
        return
Beispiel #5
0
def test_mol(mol, **opts):
    basis_data = opts.get('basis_data', None)
    do_python_tests = opts.get('do_python_tests', True)

    make_hf_driver(mol, basis_data=basis_data)
    if do_python_tests:
        bfs = getbasis(mol, basis_data)
        S = getS(bfs)
        T = getT(bfs)
        V = getV(bfs, mol)
        Ints = get2ints(bfs)
        nclosed, nopen = mol.get_closedopen()
        enuke = mol.get_enuke()
        assert nopen == 0

        h = T + V

        orbe, orbs = GHeigenvectors(h, S)
        print "Eval of h: ",
        print orbe
        for i in range(10):
            D = mkdens(orbs, 0, nclosed)
            J = getJ(Ints, D)
            K = getK(Ints, D)
            orbe, orbs = GHeigenvectors(h + 2 * J - K, S)
            eone = TraceProperty(D, h)
            ej = TraceProperty(D, J)
            ek = TraceProperty(D, K)
            energy = enuke + 2 * eone + 2 * ej - ek
            print i, energy, enuke, eone, ej, ek
    return
Beispiel #6
0
def test_mol(mol,**opts):
    basis_data = opts.get('basis_data',None)
    do_python_tests = opts.get('do_python_tests',True)
    
    make_hf_driver(mol,basis_data=basis_data)
    if do_python_tests:
        bfs = getbasis(mol,basis_data)
        S= getS(bfs)
        T = getT(bfs)
        V = getV(bfs,mol)
        Ints = get2ints(bfs)
        nclosed,nopen = mol.get_closedopen()
        enuke = mol.get_enuke()
        assert nopen==0
  
        h = T+V

        orbe,orbs = GHeigenvectors(h,S)
        print "Eval of h: ",
        print orbe
        for i in range(10):
            D = mkdens(orbs,0,nclosed)
            J = getJ(Ints,D)
            K = getK(Ints,D)
            orbe,orbs = GHeigenvectors(h+2*J-K,S)
            eone = TraceProperty(D,h)
            ej = TraceProperty(D,J)
            ek = TraceProperty(D,K)
            energy = enuke+2*eone+2*ej-ek
            print i,energy,enuke,eone,ej,ek
    return
Beispiel #7
0
    def __init__(self, molecule, **kwargs):
        from PyQuante.Ints import getbasis
        from PyQuante.Basis.Tools import get_basis_data

        self.bfs = getbasis(molecule, **kwargs)
        logging.info("%d basis functions" % len(self.bfs))
        return
Beispiel #8
0
def get_orbitalList(mol, basis_set):

    bfs = getbasis(mol, basis_set)
    g_basis = [[] for i in mol.atoms]
    # check for duplicates
    last_sym = 'N'
    last_pair = (0.0, 0.0)
    last_atid = -1
    # iterate bfs
    for i_bf in range(len(bfs)):
        bf = bfs[i_bf]
        sym = power2sym(bf.powers)
        cgbf = (sym, [])

        for prim in bf.prims:
            pair = (prim.exp, prim.coef)
            cgbf[1].append(pair)

        if (last_sym != sym) or (pair != last_pair) or (last_atid != bf.atid):
            g_basis[bf.atid].append(cgbf)
            last_sym = sym
            last_pair = pair
            last_atid = bf.atid

    return g_basis
Beispiel #9
0
def main():
    atoms = Molecule('h2',[(1,(1.,0,0)),(1,(-1.,0,0))])
    bfs = getbasis(atoms)
    S,h,Ints = getints(bfs,atoms)
    en,orbe,orbs = rhf(atoms,integrals=(S,h,Ints))
    occs = [1.]+[0.]*9

    Ecis = CIS(Ints,orbs,orbe,1,9,en)
    return Ecis[0]
Beispiel #10
0
def main():
    dirname = os.path.dirname(os.path.abspath(__file__))
    filename = os.path.join(dirname, 'LiH.xyz')

    mol = Molecule.from_file(filename, format='xyz')
    bfs = getbasis(mol.atoms, 'sto-3g')

    print(der_overlap_matrix(0, bfs))

    return
Beispiel #11
0
def main():
    dirname = os.path.dirname(os.path.abspath(__file__))
    filename = os.path.join(dirname, 'LiH.xyz')

    mol = Molecule.from_file(filename, format='xyz')
    bfs = getbasis(mol.atoms, 'sto-3g')

    print(der_overlap_matrix(0, bfs))

    return
Beispiel #12
0
def main():
    atoms = Molecule('h2',[(1,(1.,0,0)),(1,(-1.,0,0))])
    bfs = getbasis(atoms)
    nel = atoms.get_nel()
    nbf = len(bfs)
    nocc = nel/2
    S,h,Ints = getints(bfs,atoms)
    en,orbe,orbs = rhf(atoms,integrals=(S,h,Ints),)

    emp2 = MP2(Ints,orbs,orbe,nocc,nbf-nocc)  
    return en+emp2
Beispiel #13
0
def gamess_orbInfo(mol, basis_set):
    atom_types = [atno2type(atom.atno) for atom in mol.atoms]
    bfs = getbasis(mol, basis_set)
    bfs_atids = []
    bfs_atypes = []
    bfs_sym = []
    for bfindx in range(len(bfs)):
        bf = bfs[bfindx]
        bfs_atids.append(bf.atid + 1)
        bfs_atypes.append(atom_types[bf.atid])
        bfs_sym.append(gamess_power2xyz(bf.powers))
    return bfs_atids, bfs_atypes, bfs_sym
Beispiel #14
0
def test_exx():
    logging.basicConfig(filename='test_exx.log',
                        level=logging.INFO,
                        format="%(message)s",
                        filemode='w')
    logging.info("Testing EXX functions")
    logging.info(time.asctime())

    h2o = Molecule('H2O',
                   atomlist = [(8,(0,0,0)),    # the geo corresponds to the 
                               (1,(0.959,0,0)),# one that Yang used
                               (1,(-.230,0.930,0))],
                   units = 'Angstrom')

    h2 = Molecule('H2',
                   atomlist = [(1,(0.,0.,0.7)),(1,(0.,0.,-0.7))],
                   units = 'Bohr')
    he = Molecule('He',atomlist = [(2,(0,0,0))])
    ne = Molecule('Ne',atomlist = [(10,(0,0,0))])
    ohm = Molecule('OH-',atomlist = [(8,(0.0,0.0,0.0)),
                                     (1,(0.971,0.0,0.0))],
                   units = 'Angstrom',
                   charge = -1)
    be = Molecule('Be',atomlist = [(4,(0.0,0.0,0.0))],
                  units = 'Angstrom')
    lih = Molecule('LiH',
                   atomlist = [(1,(0,0,1.5)),(3,(0,0,-1.5))],
                   units = 'Bohr')
    #for atoms in [h2,he,be,lih,ohm,ne,h2o]:
    for atoms in [h2,lih]:
        logging.info("--%s--" % atoms.name)

        # Caution: the rydberg molecules (He, Ne) will need a
        #  much much larger basis set than the default returned
        # by getbasis (which is 6-31G**)
        bfs = getbasis(atoms)
        S,h,Ints = getints(bfs,atoms)

        enhf,orbehf,orbshf = rhf(atoms,integrals=(S,h,Ints))
        logging.info("HF  total energy = %f"% enhf)

        enlda,orbelda,orbslda = dft(atoms,
                                   integrals=(S,h,Ints),
                                   bfs = bfs)
        logging.info("LDA total energy = %f" % enlda)

        energy,orbe_exx,orbs_exx = exx(atoms,orbslda,
                                       integrals=(S,h,Ints),
                                       bfs = bfs,
                                       verbose=True,
                                       opt_method="BFGS")
        logging.info("EXX total energy = %f" % energy)
    return
Beispiel #15
0
def create_Orbital_file(
    filename,
    mol,
    basis_set,
    orbitals,
    orb_e,
):
    '''
    Creates a orbital file with extension .out
    that can be used with Avogadro
    for 3D orbital viewing.
    Based on a dummy GAMESS file.
    INPUTS:
     filename --> a string to be used for the name of the file, duh
      mol --> a PyQuante Molecule object
      basis_set -> a string indicating the basis_set used
      orbitals -> a matrix that containts the coefficients for the orbitals
      orb_e -> an array of orbital energies
    '''
    template_file = 'files/template_mo.out'
    new_file = '%s.out' % filename
    replaceDict = {}

    # general mol info

    replaceDict['{#Molname}'] = mol.name
    replaceDict['{#XYZ}'] = xyz_text(mol)
    replaceDict['{#Natoms}'] = len(mol.atoms)
    replaceDict['{#Nelectrons}'] = mol.get_nel()
    (nalpha, nbeta) = mol.get_alphabeta()
    replaceDict['{#Nalpha}'] = nalpha
    replaceDict['{#Nbeta}'] = nbeta
    replaceDict['{#Charge}'] = mol.charge
    replaceDict['{#Multiplicity}'] = mol.multiplicity

    # Basis set info
    basis_str, nshells = gamess_basisInfo(mol, basis_set)
    replaceDict['{#BasisInfo}'] = basis_str
    replaceDict['{#Nbfs}'] = len(getbasis(mol, basis_set))
    replaceDict['{#Nshells}'] = nshells

    # Orbital Info

    replaceDict['{#Orbitals}'] = gamess_orbStr(mol, basis_set, orbitals, orb_e)

    # create file

    replace_allnew(template_file, new_file, replaceDict)
    print('======================')
    print('Created %s successfully!' % new_file)
    print('View it now with Avogadro!')
    return
Beispiel #16
0
def main():
    atoms = Molecule('He',
                     [(2,( .0000000000, .0000000000, .0000000000))],
                     units='Angstroms')
    bfs = getbasis(atoms)
    nel = atoms.get_nel()
    nbf = len(bfs)
    nocc = nel/2
    S,h,Ints = getints(bfs,atoms)
    en,orbe,orbs = rhf(atoms,integrals=(S,h,Ints))

    emp2 = MP2(Ints,orbs,orbe,nocc,nbf-nocc)
    return en+emp2
Beispiel #17
0
def main():
    atoms = Molecule('h2', [(1, (1., 0, 0)), (1, (-1., 0, 0))])
    bfs = getbasis(atoms)
    nel = atoms.get_nel()
    nbf = len(bfs)
    nocc = nel / 2
    S, h, Ints = getints(bfs, atoms)
    en, orbe, orbs = rhf(
        atoms,
        integrals=(S, h, Ints),
    )

    emp2 = MP2(Ints, orbs, orbe, nocc, nbf - nocc)
    return en + emp2
Beispiel #18
0
def make_hf_driver(atoms, **opts):
    basis_data = opts.get('basis_data', None)
    do_print_one = opts.get('do_print_one', False)
    do_print_two = opts.get('do_print_two', False)
    maxiter = opts.get('maxiter', 5)

    nat = len(atoms)
    bfs = getbasis(atoms, basis_data)
    nbf = len(bfs)
    nbf2 = nbf * nbf
    nint = nbf * (nbf + 1) * (nbf * nbf + nbf + 2) / 8
    nclosed, nopen = atoms.get_closedopen()
    enuke = atoms.get_enuke()
    assert nopen == 0, "code only works for closed-shell systems"

    nprim = 0
    for bf in bfs:
        nprim += len(bf._prims)

    atnos, xs, ys, zs = get_adat(atoms)
    atno_array = output_elements_table(atnos, 'atno', 'int')
    x_array = output_elements_table(xs, 'x', 'double')
    y_array = output_elements_table(ys, 'y', 'double')
    z_array = output_elements_table(zs, 'z', 'double')

    # Print out data over contracted bfs:
    xcenter, ycenter, zcenter, lpower, mpower, npower, normcs, istarts, nprims = get_cdat(
        bfs)
    xcenter_array = output_elements_table(xcenter, 'xcenter', 'double')
    ycenter_array = output_elements_table(ycenter, 'ycenter', 'double')
    zcenter_array = output_elements_table(zcenter, 'zcenter', 'double')
    lpower_array = output_elements_table(lpower, 'lpower', 'int')
    mpower_array = output_elements_table(mpower, 'mpower', 'int')
    npower_array = output_elements_table(npower, 'npower', 'int')
    normc_array = output_elements_table(normcs, 'normc', 'double')
    istart_array = output_elements_table(istarts, 'istart', 'int')
    nprim_array = output_elements_table(nprims, 'nprim', 'int')

    # print out data over primitive bfs:
    alpha, coef, normp = get_pdat(bfs)
    alpha_array = output_elements_table(alpha, 'alpha', 'double')
    coef_array = output_elements_table(coef, 'coef', 'double')
    normp_array = output_elements_table(normp, 'normp', 'double')

    template = open("main_template.c").read()

    open("%s.c" % atoms.name, 'w').write(template % locals())

    return
Beispiel #19
0
def main(**opts):
    do_oep_an = opts.get('do_oep_an',True)
    mol = Molecule('LiH',[(1,(0,0,1.5)),(3,(0,0,-1.5))],units = 'Bohr')

    bfs = getbasis(mol)
    S,h,Ints = getints(bfs,mol)
    E_hf,orbe_hf,orbs_hf = rhf(mol,bfs=bfs,integrals=(S,h,Ints),
                               DoAveraging=True)
    if do_oep_an:
        E_exx,orbe_exx,orbs_exx = oep_hf_an(mol,orbs_hf,bfs=bfs,
                                            integrals=(S,h,Ints))
    else:
        E_exx,orbe_exx,orbs_exx = oep_hf(mol,orbs_hf,bfs=bfs,
                                         integrals=(S,h,Ints))
    return E_exx
Beispiel #20
0
    def __init__(self, molecule, **opts):
        from PyQuante.Ints import getbasis
        from PyQuante.Basis.Tools import get_basis_data

        basis_data = opts.get('basis_data')
        bfs = opts.get('bfs')
        if bfs:
            self.bfs = bfs
        else:
            if not basis_data:
                basis = opts.get('basis')
                if basis:
                    basis_data = get_basis_data(basis)
            self.bfs = getbasis(molecule, basis_data)
        logger.info("%d basis functions" % len(self.bfs))
        return
Beispiel #21
0
    def __init__(self,molecule,**opts):
        from PyQuante.Ints import getbasis
        from PyQuante.Basis.Tools import get_basis_data

        basis_data = opts.get('basis_data')
        bfs = opts.get('bfs')
        if bfs:
            self.bfs = bfs
        else:
            if not basis_data:
                basis = opts.get('basis')
                if basis:
                    basis_data = get_basis_data(basis)
            self.bfs = getbasis(molecule,basis_data)
        logging.info("%d basis functions" % len(self.bfs))
        return
Beispiel #22
0
def main():
    LiH = Molecule('lih', [(3, (.0000000000, .0000000000, .0000000000)),
                           (1, (.0000000000, .0000000000, 1.629912))],
                   units='Angstroms')
    bfs = getbasis(LiH)
    nbf = len(bfs)
    nocc, nopen = LiH.get_closedopen()
    assert nopen == 0
    S, h, Ints = getints(bfs, LiH)
    en, orbe, orbs = rhf(LiH, integrals=(S, h, Ints))
    print "SCF completed, E = ", en

    emp2 = MP2(Ints, orbs, orbe, nocc, nbf - nocc)
    print "MP2 correction = ", emp2
    print "Final energy = ", en + emp2
    return en + emp2
Beispiel #23
0
	def __init__(self,natom, R, basis_input="ccpvtz",LDA=False):
		if basis_input =='2dp':
			basis_data='6-311g++(2d,2p)'
		elif basis_input =='3dp':
			basis_data='6-311g++(3d,3p)'
		elif basis_input =='3df':
			basis_data='6-311g++(3df,3pd)'
		elif basis_input =='ccpvtz':
			basis_data="ccpvtz"
		elif basis_input =='631ss':
			basis_data =  '6-31g**++'
		elif basis_input =='ccpvdz':
			basis_data="ccpvdz"
		elif basis_input =='p6311ss':
			basis_data =  '6-311g**'
		elif basis_input =='juho_':
			basis_data =  'juho_'
		elif basis_input =='1s':
			basis_data =  'sto-6g'

		atoms = Molecule('H2',atomlist=[(natom,(0,0,0)),(natom,(R,0,0))])
		self.bfs  = getbasis(atoms,basis_data)
		self.S, self.h, self.Ints = getints(self.bfs, atoms)

		M = len(self.S)
		
		ist, dict_ist = index_double(M)
		
		M2 = len(ist)
		UH_g = zeros((M2,M2),float)
		UF_g = zeros((M2,M2),float)
		for il,(i,j) in enumerate(ist):
			UH_g[il] = fetch_jints(self.Ints,i,j,M)
			UF_g[il] = fetch_kints(self.Ints,i,j,M)
		
		#Diagonalize GTO: H2+ basis
		self.eival, self.eivec = geigh(self.h,self.S) 
		
		#h0 within H2+ basis
		h0 = trans_2matrix(self.h,self.eivec)
		#UH and UF within H2+ basis:  T1[ad,il]*UH_g(ijkl)*T1.T[jk,bc]
		UH = trans_4matrix(UH_g, self.eivec)
		UF = trans_4matrix(UF_g, self.eivec)
		self.inputs = (2*h0,2*UH,2*UF)

		if LDA:
			self.gr = gto_lda_inputs(self.bfs,atoms)
Beispiel #24
0
def make_hf_driver(atoms,**opts):
    basis_data = opts.get('basis_data',None)
    do_print_one = opts.get('do_print_one',False)
    do_print_two = opts.get('do_print_two',False)
    maxiter = opts.get('maxiter',5)
    
    nat = len(atoms)
    bfs = getbasis(atoms,basis_data)
    nbf = len(bfs)
    nbf2 = nbf*nbf
    nint = nbf*(nbf+1)*(nbf*nbf+nbf+2)/8
    nclosed,nopen = atoms.get_closedopen()
    enuke = atoms.get_enuke()
    assert nopen==0, "code only works for closed-shell systems"

    nprim = 0
    for bf in bfs: nprim += len(bf._prims)

    atnos,xs,ys,zs = get_adat(atoms)
    atno_array = output_elements_table(atnos,'atno','int')
    x_array = output_elements_table(xs,'x','double')
    y_array = output_elements_table(ys,'y','double')
    z_array = output_elements_table(zs,'z','double')

    # Print out data over contracted bfs:
    xcenter,ycenter,zcenter,lpower,mpower,npower,normcs,istarts,nprims = get_cdat(bfs)
    xcenter_array = output_elements_table(xcenter,'xcenter','double')
    ycenter_array = output_elements_table(ycenter,'ycenter','double')
    zcenter_array = output_elements_table(zcenter,'zcenter','double')
    lpower_array = output_elements_table(lpower,'lpower','int')
    mpower_array = output_elements_table(mpower,'mpower','int')
    npower_array = output_elements_table(npower,'npower','int')
    normc_array = output_elements_table(normcs,'normc','double')
    istart_array = output_elements_table(istarts,'istart','int')
    nprim_array = output_elements_table(nprims,'nprim','int')

    # print out data over primitive bfs:
    alpha,coef,normp = get_pdat(bfs)
    alpha_array = output_elements_table(alpha,'alpha','double')
    coef_array = output_elements_table(coef,'coef','double')
    normp_array = output_elements_table(normp,'normp','double')

    template = open("main_template.c").read()

    open("%s.c" % atoms.name,'w').write(template % locals())

    return
Beispiel #25
0
def main():
    LiH = Molecule('lih',
                     [(3,( .0000000000, .0000000000, .0000000000)),
                      (1,( .0000000000, .0000000000,1.629912))],
                     units='Angstroms')
    bfs = getbasis(LiH)
    nbf = len(bfs)
    nocc,nopen = LiH.get_closedopen()
    assert nopen==0
    S,h,Ints = getints(bfs,LiH)
    en,orbe,orbs = rhf(LiH,integrals=(S,h,Ints))
    print "SCF completed, E = ",en 

    emp2 = MP2(Ints,orbs,orbe,nocc,nbf-nocc)
    print "MP2 correction = ",emp2 
    print "Final energy = ",en+emp2 
    return en+emp2
Beispiel #26
0
def get_orbitalInfo(mol, basis_set):

    if isinstance(basis_set, basestring):
        bfs = getbasis(mol, basis_set)
    else:
        bfs = basis_set

    g_basis = [[] for i in mol.atoms]

    for i_bf in range(len(bfs)):
        bf = bfs[i_bf]
        cgbf = (power2sym(bf.powers), power2xyz(bf.powers), [])
        for prim in bf.prims:
            cgbf[2].append((prim.exp, prim.coef))
        g_basis[bf.atid].append(cgbf)

    return g_basis, len(bfs)
Beispiel #27
0
def test_old():
    from PyQuante.Molecule import Molecule
    from PyQuante.Ints import getbasis,getints
    from PyQuante.hartree_fock import rhf

    logging.basicConfig(level=logging.DEBUG,format="%(message)s")

    #mol = Molecule('HF',[('H',(0.,0.,0.)),('F',(0.,0.,0.898369))],
    #              units='Angstrom')
    mol = Molecule('LiH',[(1,(0,0,1.5)),(3,(0,0,-1.5))],units = 'Bohr')
    
    bfs = getbasis(mol)
    S,h,Ints = getints(bfs,mol)
    print "after integrals"
    E_hf,orbe_hf,orbs_hf = rhf(mol,bfs=bfs,integrals=(S,h,Ints),DoAveraging=True)
    print "RHF energy = ",E_hf
    E_exx,orbe_exx,orbs_exx = exx(mol,orbs_hf,bfs=bfs,integrals=(S,h,Ints))
    return
Beispiel #28
0
def test_grad(atoms,**opts):
    basis = opts.get('basis',None)
    verbose = opts.get('verbose',False)

    bfs = getbasis(atoms,basis)
    S,h,Ints = getints(bfs,atoms)

    nel = atoms.get_nel()
    enuke = atoms.get_enuke()

    energy, orbe, orbs = dft(atoms,return_flag=1)

    nclosed,nopen = atoms.get_closedopen()
    D = mkdens_spinavg(orbs,nclosed,nopen)

    # Now set up a minigrid on which to evaluate the density and gradients:
    npts = opts.get('npts',1)
    d = opts.get('d',1e-4)
    # generate any number of random points, and compute
    # analytical and numeric gradients:
    print "Computing Grad Rho for Molecule %s" % atoms.name
    maxerr = -1
    for i in range(npts):
        x,y,z = rand_xyz()
        rho = get_rho(x,y,z,D,bfs)
        rho_px = get_rho(x+d,y,z,D,bfs)
        rho_mx = get_rho(x-d,y,z,D,bfs)
        rho_py = get_rho(x,y+d,z,D,bfs)
        rho_my = get_rho(x,y-d,z,D,bfs)
        rho_pz = get_rho(x,y,z+d,D,bfs)
        rho_mz = get_rho(x,y,z-d,D,bfs)
        gx,gy,gz = get_grad_rho(x,y,z,D,bfs)
        gx_num = (rho_px-rho_mx)/2/d
        gy_num = (rho_py-rho_my)/2/d
        gz_num = (rho_pz-rho_mz)/2/d

        dx,dy,dz = gx-gx_num,gy-gy_num,gz-gz_num
        error = sqrt(dx*dx+dy*dy+dz*dz)
        maxerr = max(error,maxerr)
        print " Point  %10.6f %10.6f %10.6f %10.6f" % (x,y,z,error)
        print "  Numerical %10.6f %10.6f %10.6f" % (gx_num,gy_num,gz_num)
        print "  Analytic  %10.6f %10.6f %10.6f" % (gx,gy,gz)
    print "The maximum error in the gradient calculation is ",maxerr
    return
Beispiel #29
0
def main():
    atoms = Molecule('ch4', [(6, (.0000000000, .0000000000, .0000000000)),
                             (1, (.0000000000, .0000000000, 1.0836058890)),
                             (1, (1.0216334297, .0000000000, -.3612019630)),
                             (1, (-.5108167148, .8847605034, -.3612019630)),
                             (1, (-.5108167148, -.8847605034, -.3612019630))],
                     units='Angstroms')
    bfs = getbasis(atoms)
    nel = atoms.get_nel()
    nbf = len(bfs)
    nocc = nel / 2
    S, h, Ints = getints(bfs, atoms)
    en, orbe, orbs = rhf(atoms, integrals=(S, h, Ints))
    print "SCF completed, E = ", en

    emp2 = MP2(Ints, orbs, orbe, nocc, nbf - nocc)
    print "MP2 correction = ", emp2
    print "Final energy = ", en + emp2
    return en + emp2
Beispiel #30
0
def main():
    atoms = Molecule('ch4',
                     [(6,( .0000000000, .0000000000, .0000000000)),
                      (1,( .0000000000, .0000000000,1.0836058890)),
                      (1,(1.0216334297, .0000000000,-.3612019630)),
                      (1,(-.5108167148, .8847605034,-.3612019630)),
                      (1,(-.5108167148,-.8847605034,-.3612019630))],
                     units='Angstroms')
    bfs = getbasis(atoms)
    nel = atoms.get_nel()
    nbf = len(bfs)
    nocc = nel/2
    S,h,Ints = getints(bfs,atoms)
    en,orbe,orbs = rhf(atoms,integrals=(S,h,Ints))
    print "SCF completed, E = ",en 

    emp2 = MP2(Ints,orbs,orbe,nocc,nbf-nocc)
    print "MP2 correction = ",emp2 
    print "Final energy = ",en+emp2 
    return en+emp2
Beispiel #31
0
def test():
    #from PyQuante.Basis.sto3g import basis_data
    from PyQuante.Basis.p631ss import basis_data
    r = 1/0.52918
    atoms=Molecule('h2o',atomlist = [(8,(0,0,0)),(1,(r,0,0)),(1,(0,r,0))])

    inttol = 1e-6 # Tolerance to which integrals must be equal
    
    bfs = getbasis(atoms,basis_data)
    print "Int times: "
    t0 = time()

    int0 = get2ints(bfs,chgpcc)
    t1 = time()
    print "CHGP Ints:    ",t1-t0

    int1 = get2ints(bfs,cryscc)
    t2 = time()
    print "CRys Ints:   ",t2-t1
    assert maxdiff(int0,int1)<inttol
    

    int1 = get2ints(bfs,ccc)
    t3 = time()
    print "CINTS Ints:   ",t3-t2
    assert maxdiff(int0,int1)<inttol

    ints1 = get2ints(bfs,hgpcc)
    t4 = time()
    print "HGP Ints:     ",t4-t3
    assert maxdiff(int0,int1)<inttol

    int1 = get2ints(bfs,ryscc)
    t5 = time()
    print "Rys Ints:  ",t5-t4
    assert maxdiff(int0,int1)<inttol

    int1 = get2ints(bfs,pycc)
    t6 = time()
    print "Py Ints:  ",t6-t5
    assert maxdiff(int0,int1)<inttol
Beispiel #32
0
def test():
    #from PyQuante.Basis.sto3g import basis_data
    from PyQuante.Basis.p631ss import basis_data
    r = 1 / 0.52918
    atoms = Molecule('h2o',
                     atomlist=[(8, (0, 0, 0)), (1, (r, 0, 0)), (1, (0, r, 0))])

    inttol = 1e-6  # Tolerance to which integrals must be equal

    bfs = getbasis(atoms, basis_data)
    print "Int times: "
    t0 = time()

    int0 = get2ints(bfs, chgpcc)
    t1 = time()
    print "CHGP Ints:    ", t1 - t0

    int1 = get2ints(bfs, cryscc)
    t2 = time()
    print "CRys Ints:   ", t2 - t1
    assert maxdiff(int0, int1) < inttol

    int1 = get2ints(bfs, ccc)
    t3 = time()
    print "CINTS Ints:   ", t3 - t2
    assert maxdiff(int0, int1) < inttol

    ints1 = get2ints(bfs, hgpcc)
    t4 = time()
    print "HGP Ints:     ", t4 - t3
    assert maxdiff(int0, int1) < inttol

    int1 = get2ints(bfs, ryscc)
    t5 = time()
    print "Rys Ints:  ", t5 - t4
    assert maxdiff(int0, int1) < inttol

    int1 = get2ints(bfs, pycc)
    t6 = time()
    print "Py Ints:  ", t6 - t5
    assert maxdiff(int0, int1) < inttol
Beispiel #33
0
def test(file):

    # Make a test molecule for the calculation
    p = QMFile(file,mol=1)
    h2 = p.get_mol()
    #h2 = Molecule('h2',[(1,(1.,0,0)),(1,(-1.,0,0))])

    # Get a basis set and compute the integrals.
    # normally the routine will do this automatically, but we
    # do it explicitly here so that we can pass the same set
    # of integrals into the CI code and thus not recompute them.
    bfs = getbasis(h2)
    S,h,Ints = getints(bfs,h2)

    # Compute the HF wave function for our molecule
    en,orbe,orbs = rhf(h2,
                       integrals=(S,h,Ints)
                       )
    print "SCF completed, E = ",en
    print " orbital energies "
    PRINT (orbe)

    # Compute the occupied and unoccupied orbitals, used in the
    # CIS program to generate the excitations
    nclosed,nopen = h2.get_closedopen()
    nbf = len(bfs)
    nocc = nclosed+nopen
    nvirt = nbf-nocc

    # Call the CI program:
    #Ecis = CIS(Ints,orbs,orbe,nocc,nvirt,en)
    #print "Ecis = ",Ecis
    print orbs
    
    CIS_H = CISMatrix(Ints, orbs, en, orbe, nocc, nvirt)
    EN, U = linalg.eig(CIS_H)
    EE = EN; EE.sort()
    print " CIS Energies [eV]"
    PRINT ( EE )#* UNITS.HartreeToElectronVolt)
    print " First excited state energy = %20.4f" % min(EN)
    return
Beispiel #34
0
def bfs_filter(natom, atoms, basis_data):
	symlist = {
	    'S' : [1],
	    'P' : [1,0,0],
	    #'P' : [1,1,1],
	    'D' : [1,0,0,1,0,1],
	    'F' : [0,0,0,0,0,0,0,0,0,0],
	    }
	import PyQuante.Basis.Tools as tools
	basis_info = tools.get_basis_data(basis_data)[natom]
	bfs_sym = []
	for sym in basis_info:
		bfs_sym += symlist[sym[0]]
	bfs_sym = 2*bfs_sym
	bfs0 = getbasis(atoms,basis_data)
	M = len(bfs0)
	bfs = []
	for il in range(M):
		if bfs_sym[il]==1:
			bfs.append(bfs0[il])
	return bfs
Beispiel #35
0
def main(**opts):
    do_oep_an = opts.get('do_oep_an', True)
    mol = Molecule('LiH', [(1, (0, 0, 1.5)), (3, (0, 0, -1.5))], units='Bohr')

    bfs = getbasis(mol)
    S, h, Ints = getints(bfs, mol)
    E_hf, orbe_hf, orbs_hf = rhf(mol,
                                 bfs=bfs,
                                 integrals=(S, h, Ints),
                                 DoAveraging=True)
    if do_oep_an:
        E_exx, orbe_exx, orbs_exx = oep_hf_an(mol,
                                              orbs_hf,
                                              bfs=bfs,
                                              integrals=(S, h, Ints))
    else:
        E_exx, orbe_exx, orbs_exx = oep_hf(mol,
                                           orbs_hf,
                                           bfs=bfs,
                                           integrals=(S, h, Ints))
    return E_exx
Beispiel #36
0
 def __init__(self, name='molecule', atomlist=[], **opts):
     self.name = name
     self.atoms = []
     self.basis = []
     self.grid = None
     units = opts.get('units', 'bohr')
     units = units.lower()[:4]
     assert units in allowed_units
     self.units = units
     if atomlist: self.add_atuples(atomlist)
     self.charge = int(opts.get('charge', 0))
     self.multiplicity = int(opts.get('multiplicity', 1))
     # basis set
     self.bfs = None
     self.basis_name = None
     if 'basis' in opts.keys():
         self.bfs = getbasis(self, opts['basis'])
         self.basis_name = opts['basis']
     # method
     self.method = None
     if 'method' in opts.keys():
         self.method = opts['method']
     return
Beispiel #37
0
 def __init__(self,name='molecule',atomlist=[],**opts):
     self.name = name
     self.atoms = []
     self.basis = []
     self.grid = None
     units = opts.get('units','bohr')
     units = units.lower()[:4]
     assert units in allowed_units
     self.units = units
     if atomlist: self.add_atuples(atomlist)
     self.charge = int(opts.get('charge',0))
     self.multiplicity = int(opts.get('multiplicity',1))
     # basis set
     self.bfs = None
     self.basis_name = None
     if 'basis' in opts.keys(): 
         self.bfs = getbasis(self,opts['basis'])
         self.basis_name = opts['basis']
     # method 
     self.method = None
     if 'method' in opts.keys():
         self.method = opts['method']
     return
Beispiel #38
0
def test_old():
    from PyQuante.Molecule import Molecule
    from PyQuante.Ints import getbasis, getints
    from PyQuante.hartree_fock import rhf

    logging.basicConfig(level=logging.DEBUG, format="%(message)s")

    #mol = Molecule('HF',[('H',(0.,0.,0.)),('F',(0.,0.,0.898369))],
    #              units='Angstrom')
    mol = Molecule('LiH', [(1, (0, 0, 1.5)), (3, (0, 0, -1.5))], units='Bohr')

    bfs = getbasis(mol)
    S, h, Ints = getints(bfs, mol)
    print "after integrals"
    E_hf, orbe_hf, orbs_hf = rhf(mol,
                                 bfs=bfs,
                                 integrals=(S, h, Ints),
                                 DoAveraging=True)
    print "RHF energy = ", E_hf
    E_exx, orbe_exx, orbs_exx = exx(mol,
                                    orbs_hf,
                                    bfs=bfs,
                                    integrals=(S, h, Ints))
    return
Beispiel #39
0
def new_grid_tester():
    from PyQuante.TestMolecules import he,h2
    from PyQuante.MolecularGrid import MolecularGrid
    from PyQuante.Ints import getbasis
    from PyQuante import SCF
    mol = h2
    gr = MolecularGrid(mol,do_grad_dens=True)
    gr2 = MG2(mol,do_grad_dens=True)
    print "test_length: ",test_length(gr,gr2)
    print "test_distance: ",test_distance(gr,gr2)

    bfs = getbasis(mol)
    gr.set_bf_amps(bfs)
    gr2.add_basis(bfs)
    print "test_bfgrid: ",test_bfgrid(gr,gr2)

    # This is a little weird, but now use the hf density matrix to
    #  test whether the densities are the same
    hf = SCF(mol)
    hf.iterate()
    gr.setdens(hf.dmat)
    gr2.set_density(hf.dmat)
    print "test_density: ",test_density(gr,gr2)
    print "test_gamma: ",test_gamma(gr,gr2)
Beispiel #40
0
def new_grid_tester():
    from PyQuante.TestMolecules import he,h2
    from PyQuante.MolecularGrid import MolecularGrid
    from PyQuante.Ints import getbasis
    from PyQuante import SCF
    mol = h2
    gr = MolecularGrid(mol,do_grad_dens=True)
    gr2 = MG2(mol,do_grad_dens=True)
    print "test_length: ",test_length(gr,gr2)
    print "test_distance: ",test_distance(gr,gr2)

    bfs = getbasis(mol)
    gr.set_bf_amps(bfs)
    gr2.add_basis(bfs)
    print "test_bfgrid: ",test_bfgrid(gr,gr2)

    # This is a little weird, but now use the hf density matrix to
    #  test whether the densities are the same
    hf = SCF(mol)
    hf.iterate()
    gr.setdens(hf.dmat)
    gr2.set_density(hf.dmat)
    print "test_density: ",test_density(gr,gr2)
    print "test_gamma: ",test_gamma(gr,gr2)
Beispiel #41
0
def oep_uhf_an(atoms,orbsa,orbsb,**opts):
    """oep_hf - Form the optimized effective potential for HF exchange.

    Implementation of Wu and Yang's Approximate Newton Scheme
    from J. Theor. Comp. Chem. 2, 627 (2003).

    oep_uhf(atoms,orbs,**opts)

    atoms       A Molecule object containing a list of the atoms
    orbs        A matrix of guess orbitals

    Options
    -------
    bfs           None    The basis functions to use for the wfn
    pbfs          None    The basis functions to use for the pot
    basis_data    None    The basis data to use to construct bfs
    integrals     None    The one- and two-electron integrals to use
                          If not None, S,h,Ints
    """
    maxiter = opts.get('maxiter',100)
    tol = opts.get('tol',1e-5)
    ETemp = opts.get('ETemp',False)
    bfs = opts.get('bfs',None)
    if not bfs:
        basis = opts.get('basis',None)
        bfs = getbasis(atoms,basis)

    # The basis set for the potential can be set different from
    #  that used for the wave function
    pbfs = opts.get('pbfs',None) 
    if not pbfs: pbfs = bfs
    npbf = len(pbfs)

    integrals = opts.get('integrals',None)
    if integrals:
        S,h,Ints = integrals
    else:
        S,h,Ints = getints(bfs,atoms)

    nel = atoms.get_nel()
    nclosed,nopen = atoms.get_closedopen()
    nalpha,nbeta = nclosed+nopen,nclosed

    Enuke = atoms.get_enuke()

    # Form the OEP using Yang/Wu, PRL 89 143002 (2002)
    nbf = len(bfs)
    norb = nbf

    ba = zeros(npbf,'d')
    bb = zeros(npbf,'d')

    # Form and store all of the three-center integrals
    # we're going to need.
    # These are <ibf|gbf|jbf> (where 'bf' indicates basis func,
    #                          as opposed to MO)
    # N^3 storage -- obviously you don't want to do this for
    #  very large systems
    Gij = []
    for g in range(npbf):
        gmat = zeros((nbf,nbf),'d')
        Gij.append(gmat)
        gbf = pbfs[g]
        for i in range(nbf):
            ibf = bfs[i]
            for j in range(i+1):
                jbf = bfs[j]
                gij = three_center(ibf,gbf,jbf)
                gmat[i,j] = gij
                gmat[j,i] = gij

    # Compute the Fermi-Amaldi potential based on the LDA density.
    # We're going to form this matrix from the Coulombic matrix that
    # arises from the input orbitals. D0 and J0 refer to the density
    # matrix and corresponding Coulomb matrix
    
    D0 = mkdens(orbsa,0,nalpha)+mkdens(orbsb,0,nbeta)
    J0 = getJ(Ints,D0)
    Vfa = ((nel-1.)/nel)*J0
    H0 = h + Vfa

    eold = 0

    for iter in range(maxiter):
        Hoepa = get_Hoep(ba,H0,Gij)
        Hoepb = get_Hoep(ba,H0,Gij)

        orbea,orbsa = geigh(Hoepa,S)
        orbeb,orbsb = geigh(Hoepb,S)

        if ETemp:
            efermia = get_efermi(2*nalpha,orbea,ETemp)
            occsa = get_fermi_occs(efermia,orbea,ETemp)
            Da = mkdens_occs(orbsa,occsa)
            efermib = get_efermi(2*nbeta,orbeb,ETemp)
            occsb = get_fermi_occs(efermib,orbeb,ETemp)
            Db = mkdens_occs(orbsb,occsb)
            entropy = 0.5*(get_entropy(occsa,ETemp)+get_entropy(occsb,ETemp))
        else:
            Da = mkdens(orbsa,0,nalpha)
            Db = mkdens(orbsb,0,nbeta)

        J = getJ(Ints,Da) + getJ(Ints,Db)
        Ka = getK(Ints,Da)
        Kb = getK(Ints,Db)

        energy = (trace2(2*h+J-Ka,Da)+trace2(2*h+J-Kb,Db))/2\
                 +Enuke
        if ETemp: energy += entropy
        
        if abs(energy-eold) < tol:
            break
        else:
            eold = energy
        
        logging.debug("OEP AN Opt: %d %f" % (iter,energy))

        # Do alpha and beta separately
        # Alphas
        dV_ao = J-Ka-Vfa
        dV = matrixmultiply(orbsa,matrixmultiply(dV_ao,transpose(orbsa)))
        X = zeros((nbf,nbf),'d')
        c = zeros(nbf,'d')
        for k in range(nbf):
            Gk = matrixmultiply(orbsa,matrixmultiply(Gij[k],
                                                    transpose(orbsa)))
            for i in range(nalpha):
                for a in range(nalpha,norb):
                    c[k] += dV[i,a]*Gk[i,a]/(orbea[i]-orbea[a])
            for l in range(nbf):
                Gl = matrixmultiply(orbsa,matrixmultiply(Gij[l],
                                                        transpose(orbsa)))
                for i in range(nalpha):
                    for a in range(nalpha,norb):
                        X[k,l] += Gk[i,a]*Gl[i,a]/(orbea[i]-orbea[a])
        # This should actually be a pseudoinverse...
        ba = solve(X,c)
        # Betas
        dV_ao = J-Kb-Vfa
        dV = matrixmultiply(orbsb,matrixmultiply(dV_ao,transpose(orbsb)))
        X = zeros((nbf,nbf),'d')
        c = zeros(nbf,'d')
        for k in range(nbf):
            Gk = matrixmultiply(orbsb,matrixmultiply(Gij[k],
                                                    transpose(orbsb)))
            for i in range(nbeta):
                for a in range(nbeta,norb):
                    c[k] += dV[i,a]*Gk[i,a]/(orbeb[i]-orbeb[a])
            for l in range(nbf):
                Gl = matrixmultiply(orbsb,matrixmultiply(Gij[l],
                                                        transpose(orbsb)))
                for i in range(nbeta):
                    for a in range(nbeta,norb):
                        X[k,l] += Gk[i,a]*Gl[i,a]/(orbeb[i]-orbeb[a])
        # This should actually be a pseudoinverse...
        bb = solve(X,c)

    logging.info("Final OEP energy = %f" % energy)
    return energy,(orbea,orbeb),(orbsa,orbsb)
Beispiel #42
0
def oep_hf_an(atoms,orbs,**opts):
    """oep_hf - Form the optimized effective potential for HF exchange.

    Implementation of Wu and Yang's Approximate Newton Scheme
    from J. Theor. Comp. Chem. 2, 627 (2003).

    oep_hf(atoms,orbs,**opts)

    atoms       A Molecule object containing a list of the atoms
    orbs        A matrix of guess orbitals

    Options
    -------
    bfs           None    The basis functions to use for the wfn
    pbfs          None    The basis functions to use for the pot
    basis_data    None    The basis data to use to construct bfs
    integrals     None    The one- and two-electron integrals to use
                          If not None, S,h,Ints
    """
    maxiter = opts.get('maxiter',100)
    tol = opts.get('tol',1e-5)
    bfs = opts.get('bfs',None)
    if not bfs:
        basis = opts.get('basis',None)
        bfs = getbasis(atoms,basis)

    # The basis set for the potential can be set different from
    #  that used for the wave function
    pbfs = opts.get('pbfs',None) 
    if not pbfs: pbfs = bfs
    npbf = len(pbfs)

    integrals = opts.get('integrals',None)
    if integrals:
        S,h,Ints = integrals
    else:
        S,h,Ints = getints(bfs,atoms)

    nel = atoms.get_nel()
    nocc,nopen = atoms.get_closedopen()

    Enuke = atoms.get_enuke()

    # Form the OEP using Yang/Wu, PRL 89 143002 (2002)
    nbf = len(bfs)
    norb = nbf
    bp = zeros(nbf,'d')

    bvec = opts.get('bvec',None)
    if bvec:
        assert len(bvec) == npbf
        b = array(bvec)
    else:
        b = zeros(npbf,'d')


    # Form and store all of the three-center integrals
    # we're going to need.
    # These are <ibf|gbf|jbf> (where 'bf' indicates basis func,
    #                          as opposed to MO)
    # N^3 storage -- obviously you don't want to do this for
    #  very large systems
    Gij = []
    for g in range(npbf):
        gmat = zeros((nbf,nbf),'d')
        Gij.append(gmat)
        gbf = pbfs[g]
        for i in range(nbf):
            ibf = bfs[i]
            for j in range(i+1):
                jbf = bfs[j]
                gij = three_center(ibf,gbf,jbf)
                gmat[i,j] = gij
                gmat[j,i] = gij

    # Compute the Fermi-Amaldi potential based on the LDA density.
    # We're going to form this matrix from the Coulombic matrix that
    # arises from the input orbitals. D0 and J0 refer to the density
    # matrix and corresponding Coulomb matrix
    
    D0 = mkdens(orbs,0,nocc)
    J0 = getJ(Ints,D0)
    Vfa = (2*(nel-1.)/nel)*J0
    H0 = h + Vfa

    b = zeros(nbf,'d')
    eold = 0

    for iter in range(maxiter):
        Hoep = get_Hoep(b,H0,Gij)
        orbe,orbs = geigh(Hoep,S)
        
        D = mkdens(orbs,0,nocc)
        Vhf = get2JmK(Ints,D)

        energy = trace2(2*h+Vhf,D)+Enuke
        if abs(energy-eold) < tol:
            break
        else:
            eold = energy
        
        logging.debug("OEP AN Opt: %d %f" % (iter,energy))
        dV_ao = Vhf-Vfa
        dV = matrixmultiply(transpose(orbs),matrixmultiply(dV_ao,orbs))

        X = zeros((nbf,nbf),'d')
        c = zeros(nbf,'d')
        Gkt = zeros((nbf,nbf),'d')

        for k in range(nbf):
            # This didn't work; in fact, it made things worse:
            Gk = matrixmultiply(transpose(orbs),matrixmultiply(Gij[k],orbs))
            for i in range(nocc):
                for a in range(nocc,norb):
                    c[k] += dV[i,a]*Gk[i,a]/(orbe[i]-orbe[a])
                    
            for l in range(nbf):
                Gl = matrixmultiply(transpose(orbs),matrixmultiply(Gij[l],orbs))
                for i in range(nocc):
                    for a in range(nocc,norb):
                        X[k,l] += Gk[i,a]*Gl[i,a]/(orbe[i]-orbe[a])
        # This should actually be a pseudoinverse...
        b = solve(X,c)

    logging.info("Final OEP energy = %f" % energy)
    return energy,orbe,orbs
Beispiel #43
0
def oep(atoms,orbs,energy_func,grad_func=None,**opts):
    """oep - Form the optimized effective potential for a given energy expression

    oep(atoms,orbs,energy_func,grad_func=None,**opts)

    atoms       A Molecule object containing a list of the atoms
    orbs        A matrix of guess orbitals
    energy_func The function that returns the energy for the given method
    grad_func   The function that returns the force for the given method

    Options
    -------
    verbose       False   Output terse information to stdout (default)
                  True    Print out additional information 
    ETemp         False   Use ETemp value for finite temperature DFT (default)
                  float   Use (float) for the electron temperature
    bfs           None    The basis functions to use. List of CGBF's
    basis_data    None    The basis data to use to construct bfs
    integrals     None    The one- and two-electron integrals to use
                          If not None, S,h,Ints
    """
    verbose = opts.get('verbose',False)
    ETemp = opts.get('ETemp',False)
    opt_method = opts.get('opt_method','BFGS')

    bfs = opts.get('bfs',None)
    if not bfs:
        basis = opts.get('basis',None)
        bfs = getbasis(atoms,basis)

    # The basis set for the potential can be set different from
    #  that used for the wave function
    pbfs = opts.get('pbfs',None) 
    if not pbfs: pbfs = bfs
    npbf = len(pbfs)

    integrals = opts.get('integrals',None)
    if integrals:
        S,h,Ints = integrals
    else:
        S,h,Ints = getints(bfs,atoms)

    nel = atoms.get_nel()
    nocc,nopen = atoms.get_closedopen()

    Enuke = atoms.get_enuke()

    # Form the OEP using Yang/Wu, PRL 89 143002 (2002)
    nbf = len(bfs)
    norb = nbf
    bp = zeros(nbf,'d')

    bvec = opts.get('bvec',None)
    if bvec:
        assert len(bvec) == npbf
        b = array(bvec)
    else:
        b = zeros(npbf,'d')

    # Form and store all of the three-center integrals
    # we're going to need.
    # These are <ibf|gbf|jbf> (where 'bf' indicates basis func,
    #                          as opposed to MO)
    # N^3 storage -- obviously you don't want to do this for
    #  very large systems
    Gij = []
    for g in range(npbf):
        gmat = zeros((nbf,nbf),'d')
        Gij.append(gmat)
        gbf = pbfs[g]
        for i in range(nbf):
            ibf = bfs[i]
            for j in range(i+1):
                jbf = bfs[j]
                gij = three_center(ibf,gbf,jbf)
                gmat[i,j] = gij
                gmat[j,i] = gij

    # Compute the Fermi-Amaldi potential based on the LDA density.
    # We're going to form this matrix from the Coulombic matrix that
    # arises from the input orbitals. D0 and J0 refer to the density
    # matrix and corresponding Coulomb matrix
    
    D0 = mkdens(orbs,0,nocc)
    J0 = getJ(Ints,D0)
    Vfa = (2*(nel-1.)/nel)*J0
    H0 = h + Vfa

    b = fminBFGS(energy_func,b,grad_func,
                 (nbf,nel,nocc,ETemp,Enuke,S,h,Ints,H0,Gij),
                 logger=logging)

    energy,orbe,orbs = energy_func(b,nbf,nel,nocc,ETemp,Enuke,
                                   S,h,Ints,H0,Gij,return_flag=1)
    return energy,orbe,orbs
Beispiel #44
0
        energy = get_energy(h,F,D,enuke)
        print "%d %f" % (i,energy)
        if abs(energy-eold) < 1e-4: break
        eold = energy
    print "Final HF energy for system %s is %f" % (atoms.name,energy)
    return energy,orbe,orbs

# Data
Li_x1 = -0.200966
H_x1 = 1.399033
Li_x2 = -0.351691
H_x2 = 2.448309

# Construct a molecule:
LiH1 = Molecule('LiH1',[('Li',(Li_x1,0,0)),('H',(H_x1,0,0))],units='Angs')
bfs1 = getbasis(LiH1)
S1,h1,Ints1 = getints(bfs1,LiH1)
simple_hf(LiH1,S1,h1,Ints1)

# Make another molecule
LiH2 = Molecule('LiH2',[('Li',(Li_x2,0,0)),('H',(H_x2,0,0))],units='Angs')
bfs2 = getbasis(LiH2)
S2,h2,Ints2 = getints(bfs2,LiH2)
simple_hf(LiH2,S2,h2,Ints2)


# Make a superset of the two basis sets:
bfs_big = bfs1 + bfs2
# and make a basis set with it:
S1a,h1a,Ints1a = getints(bfs_big,LiH1)
simple_hf(LiH1,S1a,h1a,Ints1a)
Beispiel #45
0
from PyQuante import Molecule
from PyQuante.Ints import getbasis

h2 = Molecule('h2',[('H',(0,0,-0.5)),('H',(0,0,0.5))],units='Angs')
basis = getbasis(h2,basis_data='sto-3g')
nbf = len(basis)

h2.inertial()

print "STO-3G z"
for i in range(nbf):
    for j in range(nbf):
        print i,j,basis[i].multipole(basis[j],0,0,1)

# Sheesh! I don't have 6-31g in PyQuante

print '6-31G CH4 1'
ch4 = Molecule('ch4',
               [('C',(0.0, 0.0, 0.0)),
                ('H',(0.0, 0.0, 1.083658)),
                ('H',(1.021683, 0.0, -0.361219)),
                ('H',(-0.510841, 0.884804, -0.361219)),
                ('H',(-0.510841,-0.884804, -0.361219)),],
               units='Angs')
ch4.inertial()

# This should give the same results, but without the inertial coordinate
# transformation
#ch4 = Molecule('ch4',
#               [(6,( 0.0000000000,-0.0000000781, 0.0000001487)),
#                (1,( 0.0000000000,-0.6085461813,-1.9553066848)),
Beispiel #46
0
molec = Molecule('mol',[(K,(0,0,0))])

# Create a basis for this molecule
# Access the CGBF atributes of the CGBF number n by doing 
# basis.bfs[CGBF_n].atribute (or, since it has some operator overloading defined, 
# basis[n] = basis.bfs[n])
# E.g. basis.bfs[0].powers (basis[0].powers)
# One can also access the contraction coefficients and the exponents of the 
# PGBF making up the CGBF by doing
# basis[CGBF_n].pcoefs[PGBF_i]
# basis[CGBF_n].pexps[PGBF_i]


# Use "6-31g**" for "best" results
# Use "STO-3G" for debbuging
bas = getbasis(molec,basis_data="6-31g**")


# Grab length of basis and number of electrons and print - some of this 
# obviously will not make sense if there's more than one type of atom
lenBasis        = 2*len(bas)
nEle            = molec.get_nel()
nucNum          = nEle # Nuclear number - one of the reasons this only works 
                       # for atoms. 
                       # If we want molecules, we must be able to change this 
                       # according to the molecule
lenNPartBasis   = math.factorial(lenBasis)/(math.factorial(nEle) * \
                  math.factorial(lenBasis-nEle) )
print "\n"
print "Using a single particle spatial basis consisting of", lenBasis/2, \
      "contracted gaussians."
Beispiel #47
0
def test():

    from PyQuante import Molecule
    from mpi4py import MPI

    ############################
    # Initialize MPI
    ############################
    comm = MPI.COMM_WORLD
    rank = comm.rank
    ############################

    if rank == 0:
        print '\n'
        print '#' * 60
        print '# Parallel PyQuante'
        print '# Integral calculation with MPI'
        print '#' * 60
        tinit = time.time()
        print '\n'

    #####################################
    #	Creates the molecule
    #####################################
    mol = 'benzene.xyz'
    units = 'angs'
    basis_set = '6-31g'

    # read the xyz file of the molecule
    if rank == 0:
        print '\t Read molecule position'

    f = open(mol, 'r')
    data = f.readlines()
    f.close

    # create the molecule object
    xyz = []
    for i in range(2, len(data)):
        d = data[i].split()
        xyz.append((d[0], (float(d[1]), float(d[2]), float(d[3]))))

    natom = len(xyz)
    mol = Molecule(name='molecule', units=units)
    mol.add_atuples(xyz)
    nelec = mol.get_nel()

    #####################################
    # get the basis function
    #####################################
    basis = getbasis(mol, basis_set)
    nbfs = len(basis)
    nclosed, nopen = mol.get_closedopen()
    nocc = nclosed

    #####################################
    # Print for debug
    #####################################
    if rank == 0:
        print '\t Basis %s' % basis_set
        print '\t %d basis functions' % (nbfs)
        print '\t %d shells\n ' % (len(basis.shells))

        if 0:
            for i in range(nbfs):
                print basis[i]

    comm.barrier()

    #####################################
    # compute  all the integrals
    #####################################
    S, h, Ints = getints_mpi(basis, mol, rank, comm, _debug_=True)

    comm.barrier()
    if rank == 0:
        tfinal = time.time()
        print '\n\t Total computation time %f ' % (tfinal - tinit)
Beispiel #48
0
def EN2(molecule, **kwargs):  #
    "General wrapper for the simple CI method"
    nalpha, nbeta = molecule.get_alphabeta()
    bfs = getbasis(molecule)
    S, h, Ints = getints(bfs, molecule)
    energy, (orbea, orbeb), (orbsa, orbsb) = uhf(molecule,
                                                 integrals=(S, h, Ints),
                                                 bfs=bfs,
                                                 **kwargs)
    EHF = energy
    print "The Hatree-Fock energy is ", EHF
    #compute the transformed molecular orbital integrals

    aamoints, nbf = TransformInts(Ints, orbsa, orbsa, nalpha)
    bbmoints, nbf = TransformInts(Ints, orbsb, orbsb, nbeta)
    abmoints, nbf = TransformInts(Ints, orbsa, orbsb, nalpha)

    #Initialize the fractional occupations:
    Yalpha = zeros((nbf), 'd')
    Ybeta = zeros((nbf), 'd')

    #set up the occupied and virtual orbitals
    aoccs = range(nalpha)
    boccs = range(nbeta)
    avirt = range(nalpha, nbf)  #numbers of alpha virtual orbitals
    bvirt = range(nbeta, nbf)  #numbers of beta virtual orbitals

    ########  Computation of the primary energy correction  #########
    #Set initial correction terms to zero
    Ec1 = 0.
    sum = 0.
    z = 1.

    #compute correction term for two alpha electrons

    for a in aoccs:
        for b in xrange(a):
            for r in avirt:
                for s in xrange(nalpha, r):
                    arbs = aamoints[ijkl2intindex(a, r, b, s)]
                    asbr = aamoints[ijkl2intindex(a, s, b, r)]
                    rraa = aamoints[ijkl2intindex(r,r,a,a)] - \
                           aamoints[ijkl2intindex(r,a,a,r)]
                    rrbb = aamoints[ijkl2intindex(r,r,b,b)] - \
                           aamoints[ijkl2intindex(r,b,b,r)]
                    ssaa = aamoints[ijkl2intindex(s,s,a,a)] - \
                           aamoints[ijkl2intindex(s,a,a,s)]
                    ssbb = aamoints[ijkl2intindex(s,s,b,b)] - \
                           aamoints[ijkl2intindex(s,b,b,s)]
                    rrss = aamoints[ijkl2intindex(r,r,s,s)] - \
                           aamoints[ijkl2intindex(r,s,s,r)]
                    aabb = aamoints[ijkl2intindex(a,a,b,b)] - \
                           aamoints[ijkl2intindex(a,b,b,a)]

                    eigendif = (orbea[r] + orbea[s] - orbea[a] - orbea[b])
                    delcorr = (-rraa - rrbb - ssaa - ssbb + rrss + aabb)
                    delta = eigendif + delcorr * z

                    Eio = (arbs - asbr)

                    x = -Eio / delta
                    if abs(x) > 1:
                        print "Warning a large x value has been ",\
                              "discovered with x = ",x
                    x = choose(x < 1, (1, x))
                    x = choose(x > -1, (-1, x))
                    sum += x * x
                    Yalpha[a] -= x * x
                    Yalpha[b] -= x * x
                    Yalpha[r] += x * x
                    Yalpha[s] += x * x
                    Ec1 += x * Eio

    #compute correction term for two beta electrons

    for a in boccs:
        for b in xrange(a):
            for r in bvirt:
                for s in xrange(nbeta, r):
                    arbs = bbmoints[ijkl2intindex(a, r, b, s)]
                    asbr = bbmoints[ijkl2intindex(a, s, b, r)]
                    rraa = bbmoints[ijkl2intindex(r,r,a,a)] - \
                           bbmoints[ijkl2intindex(r,a,a,r)]
                    rrbb = bbmoints[ijkl2intindex(r,r,b,b)] - \
                           bbmoints[ijkl2intindex(r,b,b,r)]
                    ssaa = bbmoints[ijkl2intindex(s,s,a,a)] - \
                           bbmoints[ijkl2intindex(s,a,a,s)]
                    ssbb = bbmoints[ijkl2intindex(s,s,b,b)] - \
                           bbmoints[ijkl2intindex(s,b,b,s)]
                    rrss = bbmoints[ijkl2intindex(r,r,s,s)] - \
                           bbmoints[ijkl2intindex(r,s,s,r)]
                    aabb = bbmoints[ijkl2intindex(a,a,b,b)] - \
                           bbmoints[ijkl2intindex(a,b,b,a)]

                    eigendif = (orbeb[r] + orbeb[s] - orbeb[a] - orbeb[b])
                    delcorr = (-rraa - rrbb - ssaa - ssbb + rrss + aabb)
                    delta = eigendif + delcorr * z

                    Eio = (arbs - asbr)

                    x = -Eio / delta
                    if abs(x) > 1:                        print "Warning a large x value has ",\
            "been discovered with x = ",x
                    x = choose(x < 1, (1, x))
                    x = choose(x > -1, (-1, x))
                    sum += x * x
                    Ybeta[a] -= x * x
                    Ybeta[b] -= x * x
                    Ybeta[r] += x * x
                    Ybeta[s] += x * x
                    Ec1 += x * Eio

    #compute correction term for one alpha and one beta electron

    for a in aoccs:
        for b in boccs:
            for r in avirt:
                for s in bvirt:
                    arbs = abmoints[ijkl2intindex(a, r, b, s)]
                    rraa = aamoints[ijkl2intindex(r,r,a,a)] - \
                           aamoints[ijkl2intindex(r,a,a,r)]
                    rrbb = abmoints[ijkl2intindex(r, r, b, b)]
                    aass = abmoints[ijkl2intindex(a, a, s, s)]
                    ssbb = bbmoints[ijkl2intindex(s,s,b,b)] - \
                           bbmoints[ijkl2intindex(s,b,b,s)]
                    rrss = abmoints[ijkl2intindex(r, r, s, s)]
                    aabb = abmoints[ijkl2intindex(a, a, b, b)]

                    eigendif = (orbea[r] + orbeb[s] - orbea[a] - orbeb[b])
                    delcorr = (-rraa - rrbb - aass - ssbb + rrss + aabb)
                    delta = eigendif + delcorr * z

                    Eio = arbs

                    x = -Eio / delta
                    if abs(x) > 1:                        print "Warning a large x value has ",\
            "been discovered with x = ",x
                    x = choose(x < 1, (1, x))
                    x = choose(x > -1, (-1, x))
                    sum += x * x
                    Yalpha[a] -= x * x
                    Ybeta[b] -= x * x
                    Yalpha[r] += x * x
                    Ybeta[s] += x * x
                    Ec1 += x * Eio

    #compute the fractional occupations of the occupied orbitals
    for a in aoccs:
        Yalpha[a] = 1 + Yalpha[a]
    for b in boccs:
        Ybeta[b] = 1 + Ybeta[b]
    #for a in xrange(nbf):
    #print "For alpha = ",a,"the fractional occupation is ",Yalpha[a]
    #print "For beta  = ",a,"the fractional occupation is ",Ybeta[a]

    #print the energy and its corrections
    E = energy + Ec1
    print "The total sum of excitations is ", sum
    print "The primary correlation correction is ", Ec1
    print "The total energy is ", E
    return E
Beispiel #49
0
def rohf(atoms,**opts):
    """\
    rohf(atoms,**opts) - Restriced Open Shell Hartree Fock
    atoms       A Molecule object containing the molecule
    """

    ConvCriteria = opts.get('ConvCriteria',1e-5)
    MaxIter = opts.get('MaxIter',40)
    DoAveraging = opts.get('DoAveraging',True)
    averaging = opts.get('averaging',0.95)
    verbose = opts.get('verbose',True)

    bfs = opts.get('bfs',None)
    if not bfs:
        basis_data = opts.get('basis_data',None)
        bfs = getbasis(atoms,basis_data)
    nbf = len(bfs)

    integrals = opts.get('integrals', None)
    if integrals:
        S,h,Ints = integrals
    else:
        S,h,Ints = getints(bfs,atoms)

    nel = atoms.get_nel()

    nalpha,nbeta = atoms.get_alphabeta()
    S,h,Ints = getints(bfs,atoms)

    orbs = opts.get('orbs',None)
    if orbs is None:
        orbe,orbs = geigh(h,S)
    norbs = nbf

    enuke = atoms.get_enuke()
    eold = 0.

    if verbose: print "ROHF calculation on %s" % atoms.name
    if verbose: print "Nbf = %d" % nbf
    if verbose: print "Nalpha = %d" % nalpha
    if verbose: print "Nbeta = %d" % nbeta
    if verbose: print "Averaging = %s" % DoAveraging
    print "Optimization of HF orbitals"

    for i in xrange(MaxIter):
        if verbose: print "SCF Iteration:",i,"Starting Energy:",eold
        Da = mkdens(orbs,0,nalpha)
        Db = mkdens(orbs,0,nbeta)
        if DoAveraging:
            if i: 
                Da = averaging*Da + (1-averaging)*Da0
                Db = averaging*Db + (1-averaging)*Db0
            Da0 = Da
            Db0 = Db

        Ja = getJ(Ints,Da)
        Jb = getJ(Ints,Db)
        Ka = getK(Ints,Da)
        Kb = getK(Ints,Db)

        Fa = h+Ja+Jb-Ka
        Fb = h+Ja+Jb-Kb
        energya = get_energy(h,Fa,Da)
        energyb = get_energy(h,Fb,Db)
        eone = (trace2(Da,h) + trace2(Db,h))/2
        etwo = (trace2(Da,Fa) + trace2(Db,Fb))/2
        energy = (energya+energyb)/2 + enuke
        print i,energy,eone,etwo,enuke
        if abs(energy-eold) < ConvCriteria: break
        eold = energy

        Fa = ao2mo(Fa,orbs)
        Fb = ao2mo(Fb,orbs)

        # Building the approximate Fock matrices in the MO basis
        F = 0.5*(Fa+Fb)
        K = Fb-Fa

        # The Fock matrix now looks like
        #      F-K    |  F + K/2  |    F
        #   ---------------------------------
        #    F + K/2  |     F     |  F - K/2
        #   ---------------------------------
        #       F     |  F - K/2  |  F + K

        # Make explicit slice objects to simplify this
        do = slice(0,nbeta)
        so = slice(nbeta,nalpha)
        uo = slice(nalpha,norbs)
        F[do,do] -= K[do,do]
        F[uo,uo] += K[uo,uo]
        F[do,so] += 0.5*K[do,so]
        F[so,do] += 0.5*K[so,do]
        F[so,uo] -= 0.5*K[so,uo]
        F[uo,so] -= 0.5*K[uo,so]

        orbe,mo_orbs = eigh(F)
        orbs = matrixmultiply(orbs,mo_orbs)
        
    if verbose:
        print "Final ROHF energy for system %s is %f" % (atoms.name,energy)
    return energy,orbe,orbs
Beispiel #50
0
def main(argv):

    parser = argparse.ArgumentParser(
        description='Hartree Fock Calculation from scratch')

    # molecule information
    parser.add_argument('mol', help='xyz file of the molecule', type=str)
    parser.add_argument('-basis',
                        default='sto-3g',
                        help='basis set to be used in the calculation',
                        type=str)
    parser.add_argument('-charge',
                        default=0,
                        help='Charge of the system',
                        type=float)
    parser.add_argument('-units',
                        default='angs',
                        help='Units in the xyz file',
                        type=str)

    # HF calculations
    parser.add_argument('-MaxIter',
                        default=100,
                        help='Maximum number of SCF iterations',
                        type=int)
    parser.add_argument('-eps_SCF',
                        default=1E-4,
                        help='Criterion for SCF termination',
                        type=float)

    # field information
    parser.add_argument('-ffreq',
                        default=0.1,
                        help='Frequency of the field',
                        type=float)
    parser.add_argument('-fint',
                        default=0.05,
                        help='Intensity of the field',
                        type=float)
    parser.add_argument('-ft0',
                        default=0.5,
                        help='center of the field for gsin',
                        type=float)
    parser.add_argument('-fsigma',
                        default=0.25,
                        help='sigma of the field for gsin',
                        type=float)
    parser.add_argument('-fform', default='sin', help='field form', type=str)
    parser.add_argument('-fdir',
                        default='x',
                        help='direction of the field',
                        type=str)

    # Propagation
    parser.add_argument('-tmax',
                        default=200,
                        help='maximum evolution time',
                        type=float)
    parser.add_argument('-nT',
                        default=200,
                        help='number of time step',
                        type=int)
    parser.add_argument('-time_unit',
                        default='au',
                        help='unit of tmax',
                        type=str)

    # export
    parser.add_argument('-nb_print_mo',
                        default=10,
                        help='Number of orbitals to be written',
                        type=int)
    '''
	Possible basis
	'3-21g' 'sto3g' 'sto-3g' 'sto-6g'
	'6-31g' '6-31g**' '6-31g(d,p)' '6-31g**++' '6-31g++**' '6-311g**' '6-311g++(2d,2p)'
    '6-311g++(3d,3p)' '6-311g++(3df,3pd)'
    'lacvp'
    
    'ccpvdz' 'cc-pvdz' 'ccpvtz' 'cc-pvtz' 'ccpvqz' 'cc-pvqz' 'ccpv5z' 'cc-pv5z' 'ccpv6z' 'cc-pv6z'

    'augccpvdz' 'aug-cc-pvdz' 'augccpvtz' 'aug-cc-pvtz' 'augccpvqz'
    'aug-cc-pvqz' 'augccpv5z' 'aug-cc-pv5z' 'augccpv6z' 'aug-cc-pv6z'    
    'dzvp':'dzvp',

	'''

    # done
    args = parser.parse_args()

    print '\n\n=================================================='
    print '== PyQuante - Time-dependent hartree-fock       =='
    print '==================================================\n'

    #-------------------------------------------------------------------------------------------
    #
    #									PREPARE SIMULATIONS
    #
    #-------------------------------------------------------------------------------------------

    ##########################################################
    ##					Read Molecule
    ##########################################################

    # read the xyz file of the molecule
    print '\t Read molecule position'

    f = open(args.mol, 'r')
    data = f.readlines()
    f.close

    # get the molecule name
    name_mol = re.split(r'\.|/', args.mol)[-2]

    # create the molecule object
    xyz = []
    for i in range(2, len(data)):
        d = data[i].split()
        xyz.append((d[0], (float(d[1]), float(d[2]), float(d[3]))))

    natom = len(xyz)
    mol = Molecule(name=name_mol, units=args.units)
    mol.add_atuples(xyz)
    mol.set_charge(args.charge)
    nelec = mol.get_nel()

    if np.abs(args.charge) == 1:
        mol.set_multiplicity(2)
    if args.charge > 1:
        print 'charge superior to one are not implemented'

    # get the basis function
    bfs = getbasis(mol, args.basis)
    nbfs = len(bfs)
    nclosed, nopen = mol.get_closedopen()
    nocc = nclosed
    print '\t\t Molecule %s' % args.mol
    print '\t\t Basis %s' % args.basis
    print '\t\t %d basis functions' % (nbfs)

    if _print_basis_:
        for i in range(nbfs):
            print bfs[i]

    # compute all the integrals
    print '\n\t Compute the integrals and form the matrices'
    S, Hcore, Ints = getints(bfs, mol)

    print '\t Compute the transition dipole moments'
    mu_at = compute_dipole_atoms(bfs, args.fdir)

    ##########################################################
    ##			Compute the HF GROUND STATE
    ##########################################################

    print '\n\t Compute the ground state HF Ground State\n\t',
    print '-' * 50
    L, C, Cp, F0, F0p, D, Dp, P, X = rhf(mol,
                                         bfs,
                                         S,
                                         Hcore,
                                         Ints,
                                         MaxIter=args.MaxIter,
                                         eps_SCF=args.eps_SCF)

    print '\t Energy of the HF orbitals\n\t',
    print '-' * 50
    index_homo = nocc - 1
    nb_print = int(min(nbfs, args.nb_print_mo) / 2)
    for ibfs in range(index_homo - nb_print + 1, index_homo + nb_print + 1):
        print '\t\t orb %02d \t occ %1.1f \t\t Energy %1.3f Ha' % (
            ibfs, np.abs(2 * P[ibfs, ibfs].real), L[ibfs].real)

    # store the field free eigenstates
    C0 = np.copy(C)
    C0p = np.copy(Cp)

    # invert of the X matrix
    Xm1 = np.linalg.inv(X)

    ##########################################################
    ##		Transform the matrices in the OB
    ##########################################################

    # pass the other matrices as well
    Hcore_p = simx(Hcore, X, 'T')
    mu_at_p = simx(mu_at, X, 'T')

    # copy the Fock matrix
    Fp = np.copy(F0p)

    # transtion matrix at t=0
    mup = mu_at_p

    # check if everythong is ok
    if _check_ortho_:
        w, u = np.linalg.eigh(F0p)
        if np.sum(np.abs(w - L)) > 1E-3:
            print '\t == Warning orthonormalisation issue'
            sys.exit()

    #-------------------------------------------------------------------------------------------
    #
    #						TEST IF EVERYTHING IS OF SO FAR
    #
    #-------------------------------------------------------------------------------------------

    # verify the basis transformation between
    # Atomic Orbitals and Orthonormal orbitals
    #
    if _test_:

        print '\n\t Run Check on the matrices'

        #print'\n'
        #print'='*40
        print '\t\t Verify the basis transformation from diagonal to AO basis ',

        x = np.dot(np.diag(L), np.linalg.inv(C))
        x = np.dot(C, x)
        x = np.dot(S, x)

        if np.abs(np.sum(x - F0)) < 1E-3:
            print '\t Check'
        else:
            print '\t NOT OK'
        #print'='*40

        if _verbose_:
            print '\t\t reconstructed Fock matrix'
            print x
            print '\t\t original Fock matrix'
            print F0

        #print'\n\t'
        #print'='*40
        print '\t\t Verify the basis transformation from AO to diagonal basis ',

        y = np.dot(F0, C)
        y = np.dot(np.linalg.inv(S), y)
        y = np.dot(np.linalg.inv(C), y)

        if np.abs(np.sum(y - np.diag(L))) < 1E-3:
            print '\t Check'
        else:
            print '\t NOT OK'

        #print'='*40

        if _verbose_:
            print '\t\t reconstructed eigenvalues'
            print y
            print '\t\t original eigenvalues'
            print L

    #
    # verify the basis transformation between
    # Atomic Orbitals and Orthonormal orbitals
    #
    if _test_:
        #print'\n'
        #print'='*40
        print '\t\t Verify the basis transformation from AO basis to ORTHO basis ',
        #print'='*40

        if np.abs(np.sum(D - np.dot(X, np.dot(Dp, X.T)))) < 1E-3:
            print '\t Check'
        else:
            print '\t NOT OK'

        if _verbose_:
            print '\t\t reconstructed density in the AO'
            print np.dot(X, np.dot(Dp, X.T))
            print '\t\t Original density in the AO'
            print D

    #
    # verify the basis transformation between
    # Atomic Orbitals and Orthonormal orbitals
    #
    if _test_:
        #print'\n'
        #print'='*40
        print '\t\t Verify the basis transformation from AO basis to ORTHO basis ',
        #print'='*40

        if np.abs(np.sum(Dp - np.dot(Xm1, np.dot(D, Xm1.T)))) < 1E-3:
            print '\t Check'
        else:
            print '\t NOT OK'

        if _verbose_:
            print '\t\t reconstructed density in the OB'
            print np.dot(Xm1, np.dot(D, Xm1.T))
            print '\t\t original density in the OB'
            print Dp

    # test if the Fock matrix and densitu matrix in OB
    # share the same eigenbasis
    # due to degeneracies in the density matrix only a few
    # eigenvectors might be the same
    if _verbose_:
        print '\t\t verify that the Fock matrix and the density matrix '
        print '\t\t in the ORTHOGONAL BASIS have the same eigenvector',

        lf, cf = scla.eigh(F0p)
        r = 1E-6 * np.random.rand(nbfs, nbfs)
        r += r.T
        ld, cd = scla.eigh(Dp + r)

        x1 = simx(Dp, cf, 'N')
        x2 = simx(F0p, cd, 'N')

        s1 = np.sum(np.abs(x1 - np.diag(np.diag(x1))))
        s2 = np.sum(np.abs(x2 - np.diag(np.diag(x2))))

        if s1 < 1E-6 and s2 < 1E-6:
            print '\t\t Check'
        else:
            print '\t\t NOT OK'
            if _verbose_:
                print '\t\tDensity matrix in eigenbasis of the Fock matrix'
                print np.array_str(x1, suppress_small=True)
                print '\t\t\Fock matrix in eigenbasis of the Density matrix'
                print np.array_str(x2, suppress_small=True)

        print '\n'
        print '\t\t',
        print '=' * 40
        print '\t\teigenvector/eigenvalues of the fock matrix'
        print lf
        print cf
        print ''
        print '\t\teigenvector/eigenvalues of the density matrix'
        print ld
        print cd
        print '\t\t',
        print '=' * 40

    #
    # check the initial population of the molecular orbital
    #
    if _verbose_:

        print '\t\t',
        print '=' * 40
        print '\t\t Initial population of the molecular orbitals'
        print '\t\t ',
        for i in range(len(P)):
            print '%1.3f ' % (P[i, i].real),
        print ''
        print '\t\t',
        print '=' * 40
    #

    #-------------------------------------------------------------------------------------------
    #
    #								SIMUALTIONS
    #
    #-------------------------------------------------------------------------------------------

    ##########################################################
    ##					Define time and outputs
    ##########################################################

    if args.time_unit == 'fs':
        tmax_convert = args.tmax * 1E-15 / au2s
    elif args.time_unit == 'ps':
        tmax_convert = args.tmax * 1E-12 / au2s
    elif args.time_unit == 'au':
        tmax_convert = args.tmax

    # a few shortcut
    ffreq = args.ffreq
    fint = args.fint
    ft0 = args.ft0 * tmax_convert
    fsigma = args.fsigma * tmax_convert
    fform = args.fform

    # readjust the frequency in case it is not specified
    if ffreq < 0:
        ffreq = L[nocc] - L[nocc - 1]
        print '\n\t Field frequency adjusted to %f' % (ffreq)

    T = np.linspace(0, tmax_convert, args.nT)
    Tplot = np.linspace(0, args.tmax, args.nT)
    FIELD = np.zeros(args.nT)
    N = np.zeros((nbfs, args.nT))
    Q = np.zeros((natom, args.nT))
    mu0 = 0
    for i in range(natom):
        Q[i, :] = mol[i].Z
        mu0 += mol[i].Z * mol.atoms[i].r[0]
    MU = mu0 * np.ones(args.nT)

    dt = T[1] - T[0]

    ##########################################################
    ##					Loop over time
    ##########################################################
    print '\n'
    print '\t Compute the TDHF dynamics'
    print '\t Simulation done at %d percent' % (0),
    for iT in range(0, args.nT):

        ################################################################
        ## 					TIMER
        ################################################################
        if iT * 10 % int(args.nT) == 0:
            sys.stdout.write('\r\t Simulation done at %d percent' %
                             (iT * 100 / args.nT))
            sys.stdout.flush()

        ################################################################
        ## Compute the observable
        ################################################################

        # compute the Lowdin atomic charges
        for iorb in range(nbfs):
            atid = bfs[iorb].atid
            Q[atid, iT] -= 2 * Dp[iorb, iorb].real

        # compute the population of the orbitals
        for iorb in range(nbfs):
            N[iorb,
              iT] = (np.dot(C0p[:, iorb], np.dot(Dp.real, C0p[:, iorb].T)) /
                     np.linalg.norm(C0p[:, iorb])**2).real

        # compute the instantaneous dipole
        MU[iT] -= np.trace(np.dot(mu_at, D)).real

        ######################################
        ##	Propagation
        ######################################

        if _predict_ and iT < args.nT - 1:

            # predict the density matrix
            dp = propagate_dm(Dp, Fp, dt, method='relax')

            #predicted dm in AO basis
            d = np.dot(X, np.dot(dp, X.T))

            # value of the field
            fp1 = compute_field(T[iT + 1],
                                ffreq=ffreq,
                                fint=fint,
                                t0=ft0,
                                s=fsigma,
                                fform=fform)
            mup_p1 = mu_at_p * fp1

            # predicted fock matrix
            fp = compute_F(d, Hcore_p, X, Ints, mup_p1)

            # form the intermediate fock matrix
            fm = 0.5 * (Fp + fp)

            # propagte the density matrix with that
            Dp = propagate_dm(Dp, fm, dt, method='relax')

        else:

            # propagte the density matrix with that
            Dp = propagate_dm(Dp, Fp, dt, method='relax')

        ######################################
        ##	New Density Matrix in AO
        ######################################

        # DM in AO basis
        D = np.dot(X, np.dot(Dp, X.T))

        ######################################
        ##	New Field
        ######################################

        # value of the field
        FIELD[iT] = compute_field(T[iT],
                                  ffreq=ffreq,
                                  fint=fint,
                                  t0=ft0,
                                  s=fsigma,
                                  fform=fform)
        mup = mu_at_p * FIELD[iT]

        ######################################
        ##	New Fock Matrix
        ######################################

        # new Fock matrix
        Fp = compute_F(D, Hcore_p, X, Ints, mup)

    sys.stdout.write('\r\t Simulation done at 100 percent')

    # save all the data
    print '\n\t Save data\n'
    np.savetxt('time.dat', Tplot)
    np.savetxt('orb_pops.dat', N)
    np.savetxt('charges.dat', Q)
    np.savetxt('dipole.dat', MU)
    np.savetxt('field.dat', FIELD)

    #-------------------------------------------------------------------------------------------
    #
    #						EXPORT THE RESULTS
    #
    #-------------------------------------------------------------------------------------------

    ##########################################################
    ##			PLOT THE DATA WITH MATPLOTLIB
    ##########################################################
    if _plot_:
        plot(Tplot, FIELD, N, Q, MU, cutlow=0.05, cuthigh=0.9)

    ##########################################################
    ##			Export the MO in VMD Format
    ##########################################################
    if _export_mo_:

        print '\t Export MO Gaussian Cube format'

        index_homo = nocc - 1
        nb_print = int(min(nbfs, args.nb_print_mo) / 2)
        fmo_names = []
        for ibfs in range(index_homo - nb_print + 1,
                          index_homo + nb_print + 1):
            if ibfs <= index_homo:
                motyp = 'occ'
            else:
                motyp = 'virt'
            file_name = mol.name + '_mo' + '_' + motyp + '_%01d.cube' % (index)
            xyz_min, nb_pts, spacing = mesh_orb(file_name, mol, bfs, C0, ibfs)
            fmo_names.append(file_name)

        ##########################################################
        ##					Export the MO
        ##				in bvox Blender format
        ##########################################################

        if _export_blender_:
            print '\t Export MO volumetric data for Blender'
            bvox_files_mo = []
            for fname in fmo_names:
                fn = cube2blender(fname)
                bvox_files_mo.append(fn)

            ##########################################################
            ##					Create the
            ##				Blender script to visualize the orbitals
            ##########################################################
            path_to_files = os.getcwd()
            pdb_file = name_mol + '.pdb'
            create_pdb(pdb_file, args.mol, args.units)

            # create the blender file
            blname = name_mol + '_mo_volumetric.py'
            create_blender_script_mo(blname, xyz_min, nb_pts, spacing,
                                     pdb_file, bvox_files_mo, path_to_files)

    ##########################################################
    ##			Export the MO DYNAMICS in VMD Format
    ##########################################################
    if _export_mo_dynamics_:

        # step increment
        nstep_mo = 4

        # resolution i.e. point per angstrom
        ppa = 1

        # just a test
        norm = 1 - np.min(N[0, :])

        # loop to create all the desired cube files
        fdyn_elec, fdyn_hole = [], []
        for iT in range(0, args.nT, nstep_mo):

            if iT * 10 % int(args.nT) == 0:
                sys.stdout.write(
                    '\r\t Export Cube File \t\t\t\t %d percent done' %
                    (iT * 100 / args.nT))
                sys.stdout.flush()

            felec, fhole, xyz_min, nb_pts, spacing = mesh_exc_dens(
                mol, bfs, N, C0, iT, nocc, resolution=ppa)
            fdyn_elec.append(felec)
            fdyn_hole.append(fhole)

        sys.stdout.write('\r\t Export Cube File \t\t\t\t 100 percent done\n')

        # create the vmd script to animate the voxel
        create_vmd_anim(mol.name, args.nT, nstep_mo)

        ##########################################################
        ##					Export the DYN
        ##				in bvox Blender format
        ##########################################################
        if _export_blender_:
            print '\t Export volumetric data for Blender'

            # create the bvox files for electron
            bvox_files_dyn_elec = []
            for fname in fdyn_elec:
                fn = cube2blender(fname)
                bvox_files_dyn_elec.append(fn)

            # create the bvox files for holes
            bvox_files_dyn_hole = []
            for fname in fdyn_hole:
                fn = cube2blender(fname)
                bvox_files_dyn_hole.append(fn)

            # create the pdb file
            pdb_file = name_mol + '.pdb'
            create_pdb(pdb_file, args.mol, args.units)

            # path to files
            path_to_files = os.getcwd()

            # create the blender script
            blname = name_mol + '_traj_volumetric.py'
            create_blender_script_traj(blname, xyz_min, nb_pts, spacing,
                                       pdb_file, bvox_files_dyn_elec,
                                       bvox_files_dyn_hole, path_to_files)

    print '\n\n=================================================='
    print '==                       Calculation done       =='
    print '==================================================\n'
from PyQuante.TestMolecules import h2
from PyQuante.LA2 import geigh,mkdens
from PyQuante.Ints import get2JmK,getbasis,getints
from PyQuante.Convergence import DIIS
from PyQuante.hartree_fock import get_energy

bfs = getbasis(h2,basis="3-21g")
nclosed,nopen = h2.get_closedopen()
nocc = nclosed
nel = h2.get_nel()
S,h,Ints = getints(bfs,h2)

orbe,orbs = geigh(h,S)

enuke = h2.get_enuke()
eold = 0

avg = DIIS(S)

for i in range(20):
    D = mkdens(orbs,0,nocc)
    G = get2JmK(Ints,D)
    F = h+G
    F = avg.getF(F,D)
    orbe,orbs = geigh(F,S)
    energy = get_energy(h,F,D,enuke)
    print i,energy,energy-eold
    if abs(energy-eold)<1e-5:
        break
    eold = energy
print "Converged"
Beispiel #52
0
def H2O_Molecule(tst, info, auX, auZ):
    H2O = Molecule('H2O', [('O', (0.0, 0.0, 0.0)), ('H', (auX, 0.0, auZ)),
                           ('H', (-auX, 0.0, auZ))],
                   units='Bohr')

    # Get a better energy estimate
    if dft:
        print "# info=%s A.U.=(%g,%g) " % (info, auX, auZ)
        edft, orbe2, orbs2 = dft(H2O, functional='SVWN')

    bfs = getbasis(H2O, basis_data=basis_data)
    #S is overlap of 2 basis funcs
    #h is (kinetic+nucl) 1 body term
    #ints is 2 body terms
    S, h, ints = getints(bfs, H2O)

    #enhf is the Hartee-Fock energy
    #orbe is the orbital energies
    #orbs is the orbital overlaps
    enhf, orbe, orbs = rhf(H2O, integrals=(S, h, ints))
    enuke = Molecule.get_enuke(H2O)

    # print "orbe=%d" % len(orbe)

    temp = matrixmultiply(h, orbs)
    hmol = matrixmultiply(transpose(orbs), temp)

    MOInts = TransformInts(ints, orbs)

    if single:
        print "h = \n", h
        print "S = \n", S
        print "ints = \n", ints
        print "orbe = \n", orbe
        print "orbs = \n", orbs
        print ""
        print "Index 0: 1 or 2 in the paper, Index 1: 3 or 4 in the paper (for pqrs)"
        print ""
        print "hmol = \n", hmol
        print "MOInts:"
        print "I,J,K,L = PQRS order: Cre1,Cre2,Ann1,Ann2"

    if 1:
        print "tst=%d info=%s nuc=%.9f Ehf=%.9f" % (tst, info, enuke, enhf),

    cntOrbs = 0
    maxOrb = 0
    npts = len(hmol[:])
    for i in xrange(npts):
        for j in range(i, npts):
            if abs(hmol[i, j]) > 1.0e-7:
                print "%d,%d=%.9f" % (i, j, hmol[i, j]),
        cntOrbs += 1
        if i > maxOrb: maxOrb = i
        if j > maxOrb: maxOrb = j

    nbf, nmo = orbs.shape
    mos = range(nmo)
    for i in mos:
        for j in xrange(i + 1):
            ij = i * (i + 1) / 2 + j
            for k in mos:
                for l in xrange(k + 1):
                    kl = k * (k + 1) / 2 + l
                    if ij >= kl:
                        ijkl = ijkl2intindex(i, j, k, l)
                        if abs(MOInts[ijkl]) > 1.0e-7:
                            print "%d,%d,%d,%d=%.9f" % (l, i, j, k,
                                                        MOInts[ijkl]),
            cntOrbs += 1
            if i > maxOrb: maxOrb = i
            if j > maxOrb: maxOrb = j
    print ""

    return (maxOrb, cntOrbs)
Beispiel #53
0
def H2O_Molecule(tst,info,auX,auZ):
    H2O = Molecule('H2O',
           [('O',  ( 0.0,  0.0, 0.0)),
            ('H',  ( auX,  0.0, auZ)),
            ('H',  (-auX,  0.0, auZ))],
           units='Bohr')

    # Get a better energy estimate
    if dft:
        print "# info=%s A.U.=(%g,%g) " % (info,auX,auZ)
        edft,orbe2,orbs2 = dft(H2O,functional='SVWN')

    bfs= getbasis(H2O,basis_data=basis_data) 
    #S is overlap of 2 basis funcs 
    #h is (kinetic+nucl) 1 body term 
    #ints is 2 body terms 
    S,h,ints=getints(bfs,H2O) 


    #enhf is the Hartee-Fock energy 
    #orbe is the orbital energies 
    #orbs is the orbital overlaps 
    enhf,orbe,orbs=rhf(H2O,integrals=(S,h,ints))
    enuke   = Molecule.get_enuke(H2O)

    # print "orbe=%d" % len(orbe)

    temp = matrixmultiply(h,orbs) 
    hmol = matrixmultiply(transpose(orbs),temp) 

    MOInts = TransformInts(ints,orbs) 

    if single:
         print "h = \n",h
         print "S = \n",S
         print "ints = \n",ints
         print "orbe = \n",orbe
         print "orbs = \n",orbs
         print ""
         print "Index 0: 1 or 2 in the paper, Index 1: 3 or 4 in the paper (for pqrs)"
         print ""
         print "hmol = \n",hmol
         print "MOInts:"
         print "I,J,K,L = PQRS order: Cre1,Cre2,Ann1,Ann2"

    if 1:
        print "tst=%d info=%s nuc=%.9f Ehf=%.9f" % (tst,info,enuke,enhf),

    cntOrbs    = 0
    maxOrb    = 0
    npts    = len(hmol[:])
    for i in xrange(npts):
        for j in range(i,npts):
            if abs(hmol[i,j]) > 1.0e-7:
                print "%d,%d=%.9f" % (i,j,hmol[i,j]),
        cntOrbs += 1
        if i > maxOrb: maxOrb = i
        if j > maxOrb: maxOrb = j

    nbf,nmo    = orbs.shape
    mos        = range(nmo)
    for i in mos:
        for j in xrange(i+1):
            ij      = i*(i+1)/2+j
            for k in mos:
                for l in xrange(k+1):
                    kl = k*(k+1)/2+l
                    if ij >= kl:
                        ijkl = ijkl2intindex(i,j,k,l)
                        if abs(MOInts[ijkl]) > 1.0e-7:
                            print "%d,%d,%d,%d=%.9f" % (l,i,j,k,MOInts[ijkl]),
            cntOrbs += 1
            if i > maxOrb: maxOrb = i
            if j > maxOrb: maxOrb = j
    print ""

    return (maxOrb,cntOrbs)