Exemple #1
0
def get_nuc_less_accurate(mydf, kpts=None):
    log = logger.Logger(mydf.stdout, mydf.verbose)
    t1 = t0 = (time.clock(), time.time())
    if kpts is None:
        kpts_lst = numpy.zeros((1, 3))
    else:
        kpts_lst = numpy.reshape(kpts, (-1, 3))
    nkpts = len(kpts_lst)
    if mydf._cderi is None:
        mydf.build()
    cell = mydf.cell
    fused_cell, fuse = fuse_auxcell_(mydf, mydf.auxcell)

    nao = cell.nao_nr()
    charge = -cell.atom_charges()
    j2c = pgto.intor_cross("cint2c2e_sph", fused_cell, _fake_nuc(cell))
    jaux = j2c.dot(charge)
    jaux -= charge.sum() * mydf.auxbar(fused_cell)
    Gv = cell.get_Gv(mydf.gs)
    SI = cell.get_SI(Gv)
    # The normal nuclues have been considered in function get_gth_vlocG_part1
    # The result vG is the potential in G-space for erf part of the pp nuclues and
    # "numpy.dot(charge, SI) * coulG" for normal nuclues.
    vpplocG = pgto.pseudo.pp_int.get_gth_vlocG_part1(cell, Gv)
    vG = -1.0 / cell.vol * numpy.einsum("ij,ij->j", SI, vpplocG)
    kpt_allow = numpy.zeros(3)

    if is_zero(kpts_lst):
        vj = numpy.zeros((nkpts, nao ** 2))
    else:
        vj = numpy.zeros((nkpts, nao ** 2), dtype=numpy.complex128)
    max_memory = max(2000, mydf.max_memory - lib.current_memory()[0])
    for k, pqkR, pqkI, p0, p1 in mydf.ft_loop(cell, mydf.gs, kpt_allow, kpts_lst, max_memory=max_memory):
        if not gamma_point(kpts_lst[k]):
            vj[k] += numpy.einsum("k,xk->x", vG.real, pqkI) * 1j
            vj[k] += numpy.einsum("k,xk->x", vG.imag, pqkR) * -1j
        vj[k] += numpy.einsum("k,xk->x", vG.real, pqkR)
        vj[k] += numpy.einsum("k,xk->x", vG.imag, pqkI)
        pqkR = pqkI = None

    Gv = cell.get_Gv(mydf.gs)
    aoaux = ft_ao.ft_ao(fused_cell, Gv)
    jaux -= numpy.einsum("x,xj->j", vG.real, aoaux.real)
    jaux -= numpy.einsum("x,xj->j", vG.imag, aoaux.imag)
    jaux = fuse(jaux)

    vj = vj.reshape(-1, nao, nao)
    for k, kpt in enumerate(kpts_lst):
        with mydf.load_Lpq((kpt, kpt)) as Lpq:
            v = 0
            for p0, p1 in lib.prange(0, jaux.size, mydf.blockdim):
                v += numpy.dot(jaux[p0:p1], numpy.asarray(Lpq[p0:p1]))
            if gamma_point(kpt):
                vj[k] += lib.unpack_tril(numpy.asarray(v.real, order="C"))
            else:
                vj[k] += lib.unpack_tril(v)

    if kpts is None or numpy.shape(kpts) == (3,):
        vj = vj[0]
    return vj
    def test_unpack(self):
        a = numpy.random.random((400, 400))
        a = a + a * .5j
        for i in range(400):
            a[i, i] = a[i, i].real
        b = a - a.T.conj()
        b = numpy.array((b, b))
        x = lib.hermi_triu(b[0].T, hermi=2, inplace=0)
        self.assertAlmostEqual(abs(b[0].T - x).max(), 0, 12)

        x = lib.hermi_triu(b[1], hermi=2, inplace=0)
        self.assertAlmostEqual(abs(b[1] - x).max(), 0, 12)
        self.assertAlmostEqual(
            abs(x - lib.unpack_tril(lib.pack_tril(x), 2)).max(), 0, 12)

        x = lib.hermi_triu(a, hermi=1, inplace=0)
        self.assertAlmostEqual(abs(x - x.T.conj()).max(), 0, 12)

        xs = numpy.asarray((x, x, x))
        self.assertAlmostEqual(
            abs(xs - lib.unpack_tril(lib.pack_tril(xs))).max(), 0, 12)

        numpy.random.seed(1)
        a = numpy.random.random((5050, 20))
        self.assertAlmostEqual(lib.fp(lib.unpack_tril(a, axis=0)),
                               -103.03970592075423, 10)

        a = numpy.zeros((5, 0))
        self.assertEqual(lib.unpack_tril(a, axis=-1).shape, (5, 0, 0))

        a = numpy.zeros((0, 5))
        self.assertEqual(lib.unpack_tril(a, axis=0).shape, (0, 0, 5))
Exemple #3
0
def _trans_aapp_(mo, ncore, ncas, fload, ao_loc=None):
    nmo = mo[0].shape[1]
    nocc = (ncore[0] + ncas, ncore[1] + ncas)
    c_nmo = ctypes.c_int(nmo)

    klshape = (0, nmo, 0, nmo)

    japcv = numpy.empty((ncas,nmo,ncore[0],nmo-ncore[0]))
    aapp = numpy.empty((ncas,ncas,nmo,nmo))
    aaPP = numpy.empty((ncas,ncas,nmo,nmo))
    appa = numpy.empty((ncas,nmo,nmo,ncas))
    apPA = numpy.empty((ncas,nmo,nmo,ncas))
    apCV = numpy.empty((ncas,nmo,ncore[1],nmo-ncore[1]))
    ppp = numpy.empty((nmo,nmo,nmo))
    for i in range(ncas):
        buf = _ao2mo.nr_e2(fload(ncore[0]+i), mo[0], klshape,
                            aosym='s4', mosym='s2', ao_loc=ao_loc)
        lib.unpack_tril(buf, out=ppp)
        aapp[i] = ppp[ncore[0]:nocc[0]]
        appa[i] = ppp[:,:,ncore[0]:nocc[0]]
        #japcp = avcp * 2 - acpv.transpose(0,2,1,3) - avcp.transpose(0,3,2,1)
        japcv[i] = ppp[:,:ncore[0],ncore[0]:] * 2 \
                 - ppp[:ncore[0],:,ncore[0]:].transpose(1,0,2) \
                 - ppp[ncore[0]:,:ncore[0],:].transpose(2,1,0)

        buf = _ao2mo.nr_e2(fload(ncore[0]+i), mo[1], klshape,
                            aosym='s4', mosym='s2', ao_loc=ao_loc)
        lib.unpack_tril(buf, out=ppp)
        aaPP[i] = ppp[ncore[0]:nocc[0]]
        apPA[i] = ppp[:,:,ncore[1]:nocc[1]]
        apCV[i] = ppp[:,:ncore[1],ncore[1]:]

    return aapp, aaPP, appa, apPA, japcv, apCV
Exemple #4
0
        def _get_jk(_rdm1, _eri):
            j = np.zeros((nphys * (nphys + 1) // 2), dtype=types.float64)
            k = np.zeros((nphys, nphys), dtype=types.float64)

            _rdm1_tril = lib.pack_tril(_rdm1 + np.tril(_rdm1, k=-1))
            c_int = ctypes.c_int
            args = (c_int(nphys), (c_int * 4)(0, nphys, 0, nphys),
                    lib.c_null_ptr(), c_int(0))
            buf = np.empty((2, maxblk, nphys, nphys))

            for p0 in range(0, naux, maxblk):
                s = slice(p0, min(p0 + maxblk, naux))

                eri1 = _eri[s]
                naux_block = eri1.shape[0]

                rho = np.dot(eri1, _rdm1_tril)
                j += np.dot(rho, eri1)

                buf1 = buf[0, :naux_block]
                _fdrv(to_ptr(buf1), to_ptr(eri1), to_ptr(_rdm1),
                      c_int(naux_block), *args)

                buf2 = lib.unpack_tril(eri1, out=buf[1])
                k = util.dgemm(buf1.reshape((-1, nphys)).T,
                               buf2.reshape((-1, nphys)),
                               c=k,
                               beta=1)

            j = lib.unpack_tril(j).reshape(_rdm1.shape)
            k = k.reshape(_rdm1.shape)

            return j, k
Exemple #5
0
def _trans_aapp_(mo, ncore, ncas, fload, ao_loc=None):
    nmo = mo[0].shape[1]
    nocc = (ncore[0] + ncas, ncore[1] + ncas)
    c_nmo = ctypes.c_int(nmo)

    klshape = (0, nmo, 0, nmo)

    japcv = numpy.empty((ncas,nmo,ncore[0],nmo-ncore[0]))
    aapp = numpy.empty((ncas,ncas,nmo,nmo))
    aaPP = numpy.empty((ncas,ncas,nmo,nmo))
    appa = numpy.empty((ncas,nmo,nmo,ncas))
    apPA = numpy.empty((ncas,nmo,nmo,ncas))
    apCV = numpy.empty((ncas,nmo,ncore[1],nmo-ncore[1]))
    ppp = numpy.empty((nmo,nmo,nmo))
    for i in range(ncas):
        buf = _ao2mo.nr_e2(fload(ncore[0]+i), mo[0], klshape,
                            aosym='s4', mosym='s2', ao_loc=ao_loc)
        lib.unpack_tril(buf, out=ppp)
        aapp[i] = ppp[ncore[0]:nocc[0]]
        appa[i] = ppp[:,:,ncore[0]:nocc[0]]
        #japcp = avcp * 2 - acpv.transpose(0,2,1,3) - avcp.transpose(0,3,2,1)
        japcv[i] = ppp[:,:ncore[0],ncore[0]:] * 2 \
                 - ppp[:ncore[0],:,ncore[0]:].transpose(1,0,2) \
                 - ppp[ncore[0]:,:ncore[0],:].transpose(2,1,0)

        buf = _ao2mo.nr_e2(fload(ncore[0]+i), mo[1], klshape,
                            aosym='s4', mosym='s2', ao_loc=ao_loc)
        lib.unpack_tril(buf, out=ppp)
        aaPP[i] = ppp[ncore[0]:nocc[0]]
        apPA[i] = ppp[:,:,ncore[1]:nocc[1]]
        apCV[i] = ppp[:,:ncore[1],ncore[1]:]

    return aapp, aaPP, appa, apPA, japcv, apCV
Exemple #6
0
def cc_Wvvvv(t1,t2,eris):
    ## Incore 
    #Wabcd = np.array(eris.vvvv).transpose(0,2,1,3)
    #Wabcd += -einsum('kdac,kb->abcd',eris.ovvv,t1)
    #Wabcd += -einsum('kcbd,ka->abcd',eris.ovvv,t1)

    ## HDF5
    if t1.dtype == np.complex: ds_type = 'c16'
    else: ds_type = 'f8'
    _tmpfile1 = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)
    fimd = h5py.File(_tmpfile1.name)
    nocc,nvir = t1.shape
    Wabcd = fimd.create_dataset('vvvv', (nvir,nvir,nvir,nvir), ds_type)
    # avoid transpose inside loop
    eris_ovvv = lib.unpack_tril(np.asarray(eris.ovvv).reshape(nocc*nvir,-1)).reshape(nocc,nvir,nvir,nvir)
    ovvv = np.array(eris_ovvv).transpose(0,2,1,3)
    for a in range(nvir):
#        Wabcd[a] = eris.vvvv[a].transpose(1,0,2)
#        Wabcd[a] += -einsum('kdc,kb->bcd',eris_ovvv[:,:,a,:],t1)
#        #Wabcd[a] += -einsum('kcbd,k->bcd',eris_ovvv,t1[:,a])
#        Wabcd[a] += -einsum('k,kbcd->bcd',t1[:,a],ovvv)
        w_vvv  = einsum('kdc,kb->bcd',eris_ovvv[:,:,a,:],-t1)
        w_vvv -= einsum('k,kbcd->bcd',t1[:,a],ovvv)
        a0 = a*(a+1)//2
        w_vvv[:,:a+1] += lib.unpack_tril(eris.vvvv[a0:a0+a+1]).transpose(1,0,2)
        for i in range(a+1,nvir):
            w_vvv[:,i] += lib.unpack_tril(eris.vvvv[i*(i+1)//2+a])
        Wabcd[a] = w_vvv
    return Wabcd
Exemple #7
0
    def test_aux_e2(self):
        cell = pgto.Cell()
        cell.unit = 'B'
        cell.a = numpy.eye(3) * 3.
        cell.gs = numpy.array([20,20,20])
        cell.atom = 'He 0 1 1; He 1 1 0'
        cell.basis = { 'He': [[0, (0.8, 1.0)],
                              [0, (1.2, 1.0)]] }
        cell.verbose = 0
        cell.build(0, 0)
        auxcell = incore.format_aux_basis(cell)
        cell.nimgs = auxcell.nimgs = [3,3,3]
        a1 = incore.aux_e2(cell, auxcell, 'cint3c1e_sph')
        self.assertAlmostEqual(finger(a1), 0.1208944790152819, 9)
        a2 = incore.aux_e2(cell, auxcell, 'cint3c1e_sph', aosym='s2ij')
        self.assertTrue(numpy.allclose(a1, lib.unpack_tril(a2, axis=0).reshape(a1.shape)))

        numpy.random.seed(3)
        kpti_kptj = [numpy.random.random(3)]*2
        a1 = incore.aux_e2(cell, auxcell, 'cint3c1e_sph', kpti_kptj=kpti_kptj)
        self.assertAlmostEqual(finger(a1), -0.073719031689332651-0.054002639392614758j, 9)
        a2 = incore.aux_e2(cell, auxcell, 'cint3c1e_sph', aosym='s2ij', kpti_kptj=kpti_kptj)
        self.assertTrue(numpy.allclose(a1, lib.unpack_tril(a2, 1, axis=0).reshape(a1.shape)))

        numpy.random.seed(1)
        kpti_kptj = numpy.random.random((2,3))
        a1 = incore.aux_e2(cell, auxcell, 'cint3c1e_sph', kpti_kptj=kpti_kptj)
        self.assertAlmostEqual(finger(a1), 0.039329191948685879-0.039836453846241987j, 9)
Exemple #8
0
 def save_occ_frac(p0, p1, eri):
     oo, ov, vv = sort_inplace(p0, p1, eri)
     self.oooo[p0:p1] = lib.unpack_tril(oo, out=buf).reshape(
         p1 - p0, nocc, nocc, nocc)
     self.ooov[p0:p1] = ov.reshape(p1 - p0, nocc, nocc, nvir)
     oovv[p0:p1] = lib.unpack_tril(vv, out=buf).reshape(
         p1 - p0, nocc, nvir, nvir)
Exemple #9
0
def _trans_cvcv_(mo, ncore, ncas, fload, ao_loc=None):
    nmo = mo[0].shape[1]
    c_nmo = ctypes.c_int(nmo)

    jc_pp = numpy.empty((ncore[0], nmo, nmo))
    jc_PP = numpy.zeros((nmo, nmo))
    kc_pp = numpy.empty((ncore[0], nmo, nmo))
    jcvcv = numpy.zeros((ncore[0], nmo - ncore[0], ncore[0], nmo - ncore[0]))
    cvCV = numpy.empty((ncore[0], nmo - ncore[0], ncore[1], nmo - ncore[1]))
    vcp = numpy.empty((nmo - ncore[0], ncore[0], nmo))
    cpp = numpy.empty((ncore[0], nmo, nmo))
    for i in range(ncore[0]):
        buf = fload(i)
        klshape = (0, ncore[1], ncore[1], nmo)
        _ao2mo.nr_e2(buf[ncore[0]:nmo],
                     mo[1],
                     klshape,
                     aosym='s4',
                     mosym='s1',
                     out=cvCV[i],
                     ao_loc=ao_loc)

        klshape = (0, nmo, 0, nmo)
        tmp = _ao2mo.nr_e2(buf[i:i + 1],
                           mo[1],
                           klshape,
                           aosym='s4',
                           mosym='s1',
                           ao_loc=ao_loc)
        jc_PP += tmp.reshape(nmo, nmo)

        klshape = (0, ncore[0], 0, nmo)
        _ao2mo.nr_e2(buf[ncore[0]:nmo],
                     mo[0],
                     klshape,
                     aosym='s4',
                     mosym='s1',
                     out=vcp,
                     ao_loc=ao_loc)
        kc_pp[i, ncore[0]:] = vcp[:, i]

        klshape = (0, nmo, 0, nmo)
        _ao2mo.nr_e2(buf[:ncore[0]],
                     mo[0],
                     klshape,
                     aosym='s4',
                     mosym='s2',
                     out=buf[:ncore[0]],
                     ao_loc=ao_loc)
        lib.unpack_tril(buf[:ncore[0]], out=cpp)
        jc_pp[i] = cpp[i]
        kc_pp[i, :ncore[0]] = cpp[:, i]

        #jcvcv = cvcv * 2 - cvcv.transpose(2,1,0,3) - ccvv.transpose(0,2,1,3)
        jcvcv[i] = vcp[:,:,ncore[0]:] * 2 \
                 - vcp[:,:,ncore[0]:].transpose(2,1,0) \
                 - cpp[:,ncore[0]:,ncore[0]:].transpose(1,0,2)

    return jc_pp, jc_PP, kc_pp, jcvcv, cvCV
Exemple #10
0
def get_jk(agf2, eri, rdm1, with_j=True, with_k=True):
    ''' Get the J/K matrices.

    Args:
        eri : ndarray or H5 dataset
            Electronic repulsion integrals (NOT as _ChemistsERIs)
        rdm1 : 2D array
            Reduced density matrix

    Kwargs:
        with_j : bool
            Whether to compute J. Default value is True
        with_k : bool
            Whether to compute K. Default value is True

    Returns:
        tuple of ndarrays corresponding to J and K, if either are
        not requested then they are set to None.
    '''

    if isinstance(eri, np.ndarray):
        vj, vk = _vhf.incore(eri, rdm1, with_j=with_j, with_k=with_k)

    else:
        nmo = rdm1.shape[0]
        npair = nmo * (nmo + 1) // 2
        vj = vk = None

        if with_j:
            rdm1_tril = lib.pack_tril(rdm1 + np.tril(rdm1, k=-1))
            vj = np.zeros_like(rdm1_tril)

        if with_k:
            vk = np.zeros_like(rdm1)

        blksize = _agf2.get_blksize(agf2.max_memory, (nmo * npair, nmo**3))
        blksize = min(1, max(BLKMIN, blksize))
        logger.debug1(agf2, 'blksize (ragf2.get_jk) = %d' % blksize)

        tril2sq = lib.square_mat_in_trilu_indices(nmo)
        for p0, p1 in lib.prange(0, nmo, blksize):
            idx = list(np.concatenate(tril2sq[p0:p1]))
            eri0 = eri[idx]

            # vj built in tril layout with scaled rdm1_tril
            if with_j:
                vj[idx] = np.dot(eri0, rdm1_tril)

            if with_k:
                eri0 = lib.unpack_tril(eri0, axis=-1)
                eri0 = eri0.reshape(p1 - p0, nmo, nmo, nmo)

                vk[p0:p1] = lib.einsum('ijkl,jk->il', eri0, rdm1)

        if with_j:
            vj = lib.unpack_tril(vj)

    return vj, vk
    def test_unpack_row(self):
        row = numpy.arange(28.)
        ref = lib.unpack_tril(row)[4]
        self.assertTrue(numpy.array_equal(ref, lib.unpack_row(row, 4)))

        row = numpy.arange(28, dtype=numpy.int32)
        ref = lib.unpack_tril(row)[4]
        a = lib.unpack_row(row, 4)
        self.assertTrue(numpy.array_equal(ref, a))
        self.assertTrue(a.dtype == numpy.int32)
Exemple #12
0
    def test_unpack_row(self):
        row = numpy.arange(28.)
        ref = lib.unpack_tril(row)[4]
        self.assertTrue(numpy.array_equal(ref, lib.unpack_row(row, 4)))

        row = numpy.arange(28, dtype=numpy.int32)
        ref = lib.unpack_tril(row)[4]
        a = lib.unpack_row(row, 4)
        self.assertTrue(numpy.array_equal(ref, a))
        self.assertTrue(a.dtype == numpy.int32)
Exemple #13
0
def _make_eris_incore(myci, mo_coeff=None):
    cput0 = (time.clock(), time.time())
    eris = _RCISD_ERIs(myci, mo_coeff)
    nocc = eris.nocc
    nmo = eris.fock.shape[0]
    nvir = nmo - nocc

    eri1 = ao2mo.incore.full(myci._scf._eri, eris.mo_coeff)
    #:eri1 = ao2mo.restore(1, eri1, nmo)
    #:eris.oooo = eri1[:nocc,:nocc,:nocc,:nocc].copy()
    #:eris.vooo = eri1[nocc:,:nocc,:nocc,:nocc].copy()
    #:eris.voov = eri1[nocc:,:nocc,:nocc,nocc:].copy()
    #:eris.vvoo = eri1[nocc:,nocc:,:nocc,:nocc].copy()
    #:vovv = eri1[nocc:,:nocc,nocc:,nocc:].copy()
    #:eris.vovv = lib.pack_tril(vovv.reshape(-1,nvir,nvir))
    #:eris.vvvv = ao2mo.restore(4, eri1[nocc:,nocc:,nocc:,nocc:], nvir)
    nvir_pair = nvir * (nvir + 1) // 2
    eris.oooo = numpy.empty((nocc, nocc, nocc, nocc))
    eris.vooo = numpy.empty((nvir, nocc, nocc, nocc))
    eris.voov = numpy.empty((nvir, nocc, nocc, nvir))
    eris.vovv = numpy.empty((nvir, nocc, nvir_pair))
    eris.vvvv = numpy.empty((nvir_pair, nvir_pair))

    ij = 0
    outbuf = numpy.empty((nmo, nmo, nmo))
    oovv = numpy.empty((nocc, nocc, nvir, nvir))
    for i in range(nocc):
        buf = lib.unpack_tril(eri1[ij:ij + i + 1], out=outbuf[:i + 1])
        for j in range(i + 1):
            eris.oooo[i, j] = eris.oooo[j, i] = buf[j, :nocc, :nocc]
            oovv[i, j] = oovv[j, i] = buf[j, nocc:, nocc:]
        ij += i + 1
    eris.vvoo = lib.transpose(oovv.reshape(nocc**2, -1)).reshape(
        nvir, nvir, nocc, nocc)
    oovv = None

    ij1 = 0
    for i in range(nocc, nmo):
        buf = lib.unpack_tril(eri1[ij:ij + i + 1], out=outbuf[:i + 1])
        eris.vooo[i - nocc] = buf[:nocc, :nocc, :nocc]
        eris.voov[i - nocc] = buf[:nocc, :nocc, nocc:]
        lib.pack_tril(_cp(buf[:nocc, nocc:, nocc:]), out=eris.vovv[i - nocc])
        dij = i - nocc + 1
        lib.pack_tril(_cp(buf[nocc:i + 1, nocc:, nocc:]),
                      out=eris.vvvv[ij1:ij1 + dij])
        ij += i + 1
        ij1 += dij
    logger.timer(myci, 'CISD integral transformation', *cput0)
    return eris
Exemple #14
0
 def load(Lpq, b0, b1, bufR, bufI):
     Lpq = numpy.asarray(Lpq[b0:b1])
     shape = Lpq.shape
     if unpack:
         tmp = numpy.ndarray(shape, buffer=buf)
         tmp[:] = Lpq.real
         LpqR = lib.unpack_tril(tmp, out=bufR).reshape(-1, nao ** 2)
         tmp[:] = Lpq.imag
         LpqI = lib.unpack_tril(tmp, lib.ANTIHERMI, out=bufI).reshape(-1, nao ** 2)
     else:
         LpqR = numpy.ndarray(shape, buffer=bufR)
         LpqR[:] = Lpq.real
         LpqI = numpy.ndarray(shape, buffer=bufI)
         LpqI[:] = Lpq.imag
     return LpqR, LpqI
Exemple #15
0
 def load(Lpq, b0, b1, bufR, bufI):
     Lpq = numpy.asarray(Lpq[b0:b1])
     shape = Lpq.shape
     if unpack:
         tmp = numpy.ndarray(shape, buffer=buf)
         tmp[:] = Lpq.real
         LpqR = lib.unpack_tril(tmp, out=bufR).reshape(-1,nao**2)
         tmp[:] = Lpq.imag
         LpqI = lib.unpack_tril(tmp, lib.ANTIHERMI, out=bufI).reshape(-1,nao**2)
     else:
         LpqR = numpy.ndarray(shape, buffer=bufR)
         LpqR[:] = Lpq.real
         LpqI = numpy.ndarray(shape, buffer=bufI)
         LpqI[:] = Lpq.imag
     return LpqR, LpqI
Exemple #16
0
def cosmo_fock_o1(cosmo, dm):
    mol = cosmo.mol
    nao = dm.shape[0]
    # phi
    cosmo.loadsegs()
    coords = cosmo.cosurf[:cosmo.nps*3].reshape(-1,3)
    fakemol = _make_fakemol(coords)
    j3c = df.incore.aux_e2(mol, fakemol, intor='cint3c2e_sph', aosym='s2ij')
    tril_dm = lib.pack_tril(dm) * 2
    diagidx = numpy.arange(nao)
    diagidx = diagidx*(diagidx+1)//2 + diagidx
    tril_dm[diagidx] *= .5
    cosmo.phi = -numpy.einsum('x,xk->k', tril_dm, j3c)
    for ia in range(mol.natm):
        cosmo.phi += mol.atom_charge(ia)/lib.norm(mol.atom_coord(ia)-coords, axis=1)
    cosmo.savesegs()
    # qk
    cosmo.charges()
    # vpot
    cosmo.loadsegs()
#X    fakemol = _make_fakemol(cosmo.cosurf[:cosmo.nps*3].reshape(-1,3))
#X    j3c = df.incore.aux_e2(mol, fakemol, intor='cint3c2e_sph', aosym='s2ij')
    fock = lib.unpack_tril(numpy.einsum('xk,k->x', j3c, -cosmo.qcos[:cosmo.nps]))
    fepsi = cosmo.fepsi() 
    fock = fepsi*fock
    return fock
Exemple #17
0
def get_mo_pairs_G(mydf, mo_coeffs, kpts=numpy.zeros((2,3)), q=None,
                   compact=getattr(__config__, 'pbc_df_mo_pairs_compact', False)):
    '''Calculate forward fourier transform (G|ij) of all MO pairs.

    Args:
        mo_coeff: length-2 list of (nao,nmo) ndarrays
            The two sets of MO coefficients to use in calculating the
            product |ij).

    Returns:
        mo_pairs_G : (ngrids, nmoi*nmoj) ndarray
            The FFT of the real-space MO pairs.
    '''
    if kpts is None: kpts = numpy.zeros((2,3))
    cell = mydf.cell
    kpts = numpy.asarray(kpts)
    q = kpts[1] - kpts[0]
    coords = cell.gen_uniform_grids(mydf.mesh)
    nmoi = mo_coeffs[0].shape[1]
    nmoj = mo_coeffs[1].shape[1]
    ngrids = len(coords)
    max_memory = max(2000, (mydf.max_memory - lib.current_memory()[0]) * .5)

    mo_pairs_G = numpy.empty((ngrids,nmoi,nmoj), dtype=numpy.complex128)
    nao = cell.nao
    for pqkR, pqkI, p0, p1 \
            in mydf.pw_loop(mydf.mesh, kpts, q,
                            max_memory=max_memory, aosym='s2'):
        pqk = lib.unpack_tril(pqkR + pqkI*1j, axis=0).reshape(nao,nao,-1)
        mo_pairs_G[p0:p1] = lib.einsum('pqk,pi,qj->kij', pqk, *mo_coeffs[:2])
    return mo_pairs_G.reshape(ngrids,nmoi*nmoj)
Exemple #18
0
def make_intermediates(mycc, t1, t2, eris):
    saved = ccsd_lambda.make_intermediates(mycc, t1, t2, eris)

    nocc, nvir = t1.shape
    eris_ovvv = _cp(eris.ovvv)
    eris_ovvv = lib.unpack_tril(eris_ovvv.reshape(nocc*nvir,-1))
    eris_ovvv = eris_ovvv.reshape(nocc,nvir,nvir,nvir)
    mo_e = mycc._scf.mo_energy
    eia = lib.direct_sum('i-a->ia',mo_e[:nocc], mo_e[nocc:])
    d3 = lib.direct_sum('ia,jb,kc->ijkabc', eia, eia, eia)
    eris_ovoo = eris.ovoo
    w =(numpy.einsum('iabf,kjcf->ijkabc', eris_ovvv, t2)
      - numpy.einsum('iajm,mkbc->ijkabc', eris_ovoo, t2)) / d3
    v = numpy.einsum('iajb,kc->ijkabc', eris.ovov, t1) / d3 * .5
    w = p6_(w)
    v = p6_(v)
    rwv = r6_(w*2+v)
    jov = numpy.einsum('jbkc,ijkabc->ia', eris.ovov, r6_(w))
    joovv = numpy.einsum('iabf,ijkabc->kjcf', eris_ovvv, rwv)
    joovv-= numpy.einsum('iajm,ijkabc->mkbc', eris.ovoo, rwv)
    joovv = joovv + joovv.transpose(1,0,3,2)

    saved.jov = jov
    saved.joovv = joovv
    return saved
Exemple #19
0
    def test_r_incore(self):
        j3c = df.r_incore.aux_e2(mol,
                                 auxmol,
                                 intor='int3c2e_spinor',
                                 aosym='s1')
        nao = mol.nao_2c()
        naoaux = auxmol.nao_nr()
        j3c = j3c.reshape(nao, nao, naoaux)

        eri0 = numpy.empty((nao, nao, naoaux), dtype=numpy.complex)
        pi = 0
        for i in range(mol.nbas):
            pj = 0
            for j in range(mol.nbas):
                pk = 0
                for k in range(mol.nbas, mol.nbas + auxmol.nbas):
                    shls = (i, j, k)
                    buf = gto.moleintor.getints_by_shell(
                        'int3c2e_spinor', shls, atm, bas, env)
                    di, dj, dk = buf.shape
                    eri0[pi:pi + di, pj:pj + dj, pk:pk + dk] = buf
                    pk += dk
                pj += dj
            pi += di
        self.assertTrue(numpy.allclose(eri0, j3c))
        eri1 = df.r_incore.aux_e2(mol,
                                  auxmol,
                                  intor='int3c2e_spinor',
                                  aosym='s2ij')
        for i in range(naoaux):
            j3c[:, :, i] = lib.unpack_tril(eri1[:, i])
        self.assertTrue(numpy.allclose(eri0, j3c))
Exemple #20
0
        def get_hcore(self, mol=None):
            if mol is None: mol = self.mol
            if getattr(scf_method, 'get_hcore', None):
                h1e = method_class.get_hcore(self, mol)
            else:  # DO NOT modify post-HF objects to avoid the MM charges applied twice
                raise RuntimeError('mm_charge function cannot be applied on post-HF methods')

            if pyscf.DEBUG:
                v = 0
                for i,q in enumerate(charges):
                    mol.set_rinv_origin(coords[i])
                    v += mol.intor('int1e_rinv') * -q
            else:
                if mol.cart:
                    intor = 'int3c2e_cart'
                else:
                    intor = 'int3c2e_sph'
                nao = mol.nao
                max_memory = self.max_memory - lib.current_memory()[0]
                blksize = int(min(max_memory*1e6/8/nao**2, 200))
                v = 0
                for i0, i1 in lib.prange(0, charges.size, blksize):
                    fakemol = gto.fakemol_for_charges(coords[i0:i1])
                    j3c = df.incore.aux_e2(mol, fakemol, intor=intor, aosym='s2ij')
                    v += numpy.einsum('xk,k->x', j3c, -charges[i0:i1])
                v = lib.unpack_tril(v)
            return h1e + v
Exemple #21
0
    def _run(self, **kwargs):
        if self.with_df:
            self._pyscf = self._pyscf.density_fit()
            self._pyscf.with_df.auxbasis = self.auxbasis

        self._pyscf.run(**kwargs)

        if self.check_stability:
            for niter in range(1, self.stability_cycles + 1):
                stability = self.stability()

                if isinstance(stability, tuple):
                    internal, external = stability
                else:
                    internal = stability

                if np.allclose(internal, self._pyscf.mo_coeff):
                    if niter == self.stability_cycles:
                        if mpi.rank:
                            log.warn('Internal stability in HF not resolved.')
                    break
                else:
                    rdm1 = self._pyscf.make_rdm1(internal, self._pyscf.mo_occ)

                self._pyscf.scf(dm0=rdm1)

        if not self.with_df:
            self._eri_ao = util.restore(1, self.mol._pyscf.intor('int2e'),
                                        self.nao)
        else:
            self._eri_ao = lib.unpack_tril(self._pyscf.with_df._cderi)
Exemple #22
0
def ecp_int(cell, kpts=None):
    if rank == 0:
        comm.bcast(cell.dumps())
    else:
        cell = pgto.loads(comm.bcast(None))

    if kpts is None:
        kpts_lst = numpy.zeros((1,3))
    else:
        kpts_lst = numpy.reshape(kpts, (-1,3))

    ecpcell = gto.Mole()
    ecpcell._atm = cell._atm
    # append a fictitious s function to mimic the auxiliary index in pbc.incore.
    # ptr2last_env_idx to force PBCnr3c_fill_* function to copy the entire "env"
    ptr2last_env_idx = len(cell._env) - 1
    ecpbas = numpy.vstack([[0, 0, 1, 1, 0, ptr2last_env_idx, 0, 0],
                           cell._ecpbas]).astype(numpy.int32)
    ecpcell._bas = ecpbas
    ecpcell._env = cell._env
    # In pbc.incore _ecpbas is appended to two sets of cell._bas and the
    # fictitious s function.
    cell._env[AS_ECPBAS_OFFSET] = cell.nbas * 2 + 1
    cell._env[AS_NECPBAS] = len(cell._ecpbas)

    kptij_lst = numpy.hstack((kpts_lst,kpts_lst)).reshape(-1,2,3)
    nkpts = len(kpts_lst)
    if abs(kpts_lst).sum() < 1e-9:  # gamma_point
        dtype = numpy.double
    else:
        dtype = numpy.complex128
    ao_loc = cell.ao_loc_nr()
    nao = ao_loc[-1]
    mat = numpy.zeros((nkpts,nao,nao), dtype=dtype)

    intor = cell._add_suffix('ECPscalar')
    int3c = incore.wrap_int3c(cell, ecpcell, intor, kptij_lst=kptij_lst)

    # shls_slice of auxiliary index (0,1) corresponds to the fictitious s function
    tasks = [(i, i+1, j, j+1, 0, 1) # shls_slice
             for i in range(cell.nbas) for j in range(i+1)]
    for shls_slice in mpi.work_stealing_partition(tasks):
        i0 = ao_loc[shls_slice[0]]
        i1 = ao_loc[shls_slice[1]]
        j0 = ao_loc[shls_slice[2]]
        j1 = ao_loc[shls_slice[3]]
        buf = numpy.empty((nkpts,i1-i0,j1-j0), dtype=dtype)
        mat[:,i0:i1,j0:j1] = int3c(shls_slice, buf)

    buf = mpi.reduce(mat)
    if rank == 0:
        mat = []
        for k, kpt in enumerate(kpts_lst):
            v = lib.unpack_tril(lib.pack_tril(buf[k]), lib.HERMITIAN)
            if abs(kpt).sum() < 1e-9:  # gamma_point:
                v = v.real
            mat.append(v)
        if kpts is None or numpy.shape(kpts) == (3,):
            mat = mat[0]
        return mat
Exemple #23
0
def gamma1_intermediates(mycc, t1, t2, l1, l2, eris=None):
    doo, dov, dvo, dvv = ccsd_rdm.gamma1_intermediates(mycc, t1, t2, l1, l2)

    if eris is None: eris = ccsd._ERIS(mycc)
    nocc, nvir = t1.shape
    eris_ovvv = _cp(eris.ovvv)
    eris_ovvv = lib.unpack_tril(eris_ovvv.reshape(nocc*nvir,-1))
    eris_ovvv = eris_ovvv.reshape(nocc,nvir,nvir,nvir)
    mo_e = mycc._scf.mo_energy
    eia = lib.direct_sum('i-a->ia',mo_e[:nocc], mo_e[nocc:])
    d3 = lib.direct_sum('ia,jb,kc->ijkabc', eia, eia, eia)
    eris_ovoo = eris.ovoo
    w =(numpy.einsum('iabf,kjcf->ijkabc', eris_ovvv, t2)
      - numpy.einsum('iajm,mkbc->ijkabc', eris_ovoo, t2)) / d3
    v = numpy.einsum('iajb,kc->ijkabc', eris.ovov, t1) / d3 * .5
    w = p6_(w)
    v = p6_(v)
    wv = w+v
    rw = r6_(w)
    goo =-numpy.einsum('iklabc,jklabc->ij', wv, rw) * .5
    gvv = numpy.einsum('ijkacd,ijkbcd->ab', wv, rw) * .5

    doo += goo
    dvv += gvv
    return doo, dov, dvo, dvv
Exemple #24
0
def vector_to_amplitudes(vector, nmo, nocc):
    nvir = nmo - nocc
    nov = nocc * nvir
    nocc2 = nocc * (nocc + 1) // 2
    vlocs = [_task_location(nvir, task_id) for task_id in range(mpi.pool.size)]
    vloc0, vloc1 = vlocs[rank]
    nvir_seg = vloc1 - vloc0

    if rank == 0:
        t1T = vector[:nov].copy().reshape((nvir, nocc))
        mpi.bcast(t1T)
        t2tril = vector[nov:].reshape(nvir_seg, nvir, nocc2)
    else:
        t1T = mpi.bcast(None)
        t2tril = vector.reshape(nvir_seg, nvir, nocc2)

    t2T = lib.unpack_tril(t2tril.reshape(nvir_seg * nvir, nocc2),
                          filltriu=lib.PLAIN)
    t2T = t2T.reshape(nvir_seg, nvir, nocc, nocc)
    t2tmp = mpi.alltoall([t2tril[:, p0:p1] for p0, p1 in vlocs],
                         split_recvbuf=True)
    idx, idy = numpy.tril_indices(nocc)
    for task_id, (p0, p1) in enumerate(vlocs):
        tmp = t2tmp[task_id].reshape(p1 - p0, nvir_seg, nocc2)
        t2T[:, p0:p1, idy, idx] = tmp.transpose(1, 0, 2)
    return t1T.T, t2T.transpose(2, 3, 0, 1)
Exemple #25
0
        def get_hcore(self, mol=None):
            if mol is None: mol = self.mol
            if hasattr(scf_method, 'get_hcore'):
                h1e = method_class.get_hcore(self, mol)
            else:  # DO NOT modify post-HF objects to avoid the MM charges applied twice
                raise RuntimeError('mm_charge function cannot be applied on post-HF methods')

            if pyscf.DEBUG:
                v = 0
                for i,q in enumerate(charges):
                    mol.set_rinv_origin(coords[i])
                    v += mol.intor('int1e_rinv') * -q
            else:
                if mol.cart:
                    intor = 'int3c2e_cart'
                else:
                    intor = 'int3c2e_sph'
                nao = mol.nao
                max_memory = self.max_memory - lib.current_memory()[0]
                blksize = int(max(max_memory*1e6/8/nao**2, 400))
                v = 0
                for i0, i1 in lib.prange(0, charges.size, blksize):
                    fakemol = gto.fakemol_for_charges(coords[i0:i1])
                    j3c = df.incore.aux_e2(mol, fakemol, intor=intor, aosym='s2ij')
                    v += numpy.einsum('xk,k->x', j3c, -charges[i0:i1])
                v = lib.unpack_tril(v)
            return h1e + v
Exemple #26
0
def gamma2_intermediates(mycc, t1, t2, l1, l2, eris=None):
    dovov, dvvvv, doooo, doovv, dovvo, dvvov, dovvv, dooov = \
            ccsd_rdm.gamma2_intermediates(mycc, t1, t2, l1, l2)
    if eris is None: eris = ccsd._ERIS(mycc)

    nocc, nvir = t1.shape
    eris_ovvv = _cp(eris.ovvv)
    eris_ovvv = lib.unpack_tril(eris_ovvv.reshape(nocc*nvir,-1))
    eris_ovvv = eris_ovvv.reshape(nocc,nvir,nvir,nvir)
    mo_e = mycc._scf.mo_energy
    eia = lib.direct_sum('i-a->ia',mo_e[:nocc], mo_e[nocc:])
    d3 = lib.direct_sum('ia,jb,kc->ijkabc', eia, eia, eia)
    eris_ovoo = eris.ovoo
    w =(numpy.einsum('iabf,kjcf->ijkabc', eris_ovvv, t2)
      - numpy.einsum('iajm,mkbc->ijkabc', eris_ovoo, t2)) / d3
    v = numpy.einsum('iajb,kc->ijkabc', eris.ovov, t1) / d3 * .5
    w = p6_(w)
    v = p6_(v)
    rw = r6_(w)
    rwv = r6_(w*2+v)
    dovov += numpy.einsum('kc,ijkabc->iajb', t1, rw) * .5
    dooov -= numpy.einsum('mkbc,ijkabc->jmia', t2, rwv)
    # Note "dovvv +=" also changes the value of dvvov
    dovvv += numpy.einsum('kjcf,ijkabc->iabf', t2, rwv)
    dvvov = dovvv.transpose(2,3,0,1)
    return dovov, dvvvv, doooo, doovv, dovvo, dvvov, dovvv, dooov
Exemple #27
0
def _make_eris_outcore(mycc, mo_coeff=None):
    cput0 = (logger.process_clock(), logger.perf_counter())
    log = logger.Logger(mycc.stdout, mycc.verbose)
    eris = _ChemistsERIs()
    eris._common_init_(mycc, mo_coeff)

    mol = mycc.mol
    mo_coeff = eris.mo_coeff
    nocc = eris.nocc
    nao, nmo = mo_coeff.shape
    nvir = nmo - nocc
    eris.feri1 = lib.H5TmpFile()
    eris.oooo = eris.feri1.create_dataset('oooo', (nocc, nocc, nocc, nocc),
                                          'f8')
    eris.ovoo = eris.feri1.create_dataset('ovoo', (nocc, nvir, nocc, nocc),
                                          'f8',
                                          chunks=(nocc, 1, nocc, nocc))
    eris.ovov = eris.feri1.create_dataset('ovov', (nocc, nvir, nocc, nvir),
                                          'f8',
                                          chunks=(nocc, 1, nocc, nvir))
    eris.ovvo = eris.feri1.create_dataset('ovvo', (nocc, nvir, nvir, nocc),
                                          'f8',
                                          chunks=(nocc, 1, nvir, nocc))
    eris.ovvv = eris.feri1.create_dataset('ovvv', (nocc, nvir, nvir, nvir),
                                          'f8')
    eris.oovv = eris.feri1.create_dataset('oovv', (nocc, nocc, nvir, nvir),
                                          'f8',
                                          chunks=(nocc, nocc, 1, nvir))
    max_memory = max(MEMORYMIN, mycc.max_memory - lib.current_memory()[0])

    ftmp = lib.H5TmpFile()
    ao2mo.full(mol, mo_coeff, ftmp, max_memory=max_memory, verbose=log)
    eri = ftmp['eri_mo']

    nocc_pair = nocc * (nocc + 1) // 2
    tril2sq = lib.square_mat_in_trilu_indices(nmo)
    oo = eri[:nocc_pair]
    eris.oooo[:] = ao2mo.restore(1, oo[:, :nocc_pair], nocc)
    oovv = lib.take_2d(oo, tril2sq[:nocc, :nocc].ravel(),
                       tril2sq[nocc:, nocc:].ravel())
    eris.oovv[:] = oovv.reshape(nocc, nocc, nvir, nvir)
    oo = oovv = None

    tril2sq = lib.square_mat_in_trilu_indices(nmo)
    blksize = min(nvir, max(BLKMIN, int(max_memory * 1e6 / 8 / nmo**3 / 2)))
    for p0, p1 in lib.prange(0, nvir, blksize):
        q0, q1 = p0 + nocc, p1 + nocc
        off0 = q0 * (q0 + 1) // 2
        off1 = q1 * (q1 + 1) // 2
        buf = lib.unpack_tril(eri[off0:off1])

        tmp = buf[tril2sq[q0:q1, :nocc] - off0]
        eris.ovoo[:, p0:p1] = tmp[:, :, :nocc, :nocc].transpose(1, 0, 2, 3)
        eris.ovvo[:, p0:p1] = tmp[:, :, nocc:, :nocc].transpose(1, 0, 2, 3)
        eris.ovov[:, p0:p1] = tmp[:, :, :nocc, nocc:].transpose(1, 0, 2, 3)
        eris.ovvv[:, p0:p1] = tmp[:, :, nocc:, nocc:].transpose(1, 0, 2, 3)

        buf = tmp = None
    log.timer('GW integral transformation', *cput0)
    return eris
Exemple #28
0
 def load(aux_slice):
     b0, b1 = aux_slice
     if is_real:
         LpqR = numpy.asarray(j3c[b0:b1])
         if unpack:
             LpqR = lib.unpack_tril(LpqR).reshape(-1,nao**2)
         LpqI = numpy.zeros_like(LpqR)
     else:
         Lpq = numpy.asarray(j3c[b0:b1])
         LpqR = numpy.asarray(Lpq.real, order='C')
         LpqI = numpy.asarray(Lpq.imag, order='C')
         Lpq = None
         if unpack:
             LpqR = lib.unpack_tril(LpqR).reshape(-1,nao**2)
             LpqI = lib.unpack_tril(LpqI, lib.ANTIHERMI).reshape(-1,nao**2)
     return LpqR, LpqI
Exemple #29
0
    def test_ccsd(self):
        mcc = cc.ccsd.CC(mf)
        mcc.conv_tol = 1e-9
        mcc.conv_tol_normt = 1e-7
        eris = mcc.ao2mo()
        emp2, t1, t2 = mcc.init_amps(eris)
        self.assertAlmostEqual(abs(t2).sum(), 4.9556571211255909, 6)
        self.assertAlmostEqual(emp2, -0.2040199672883385, 10)
        t1, t2 = cc.ccsd.update_amps(mcc, t1, t2, eris)
        self.assertAlmostEqual(abs(t1).sum(), 0.0475038989126, 8)
        self.assertAlmostEqual(abs(t2).sum(), 5.4018238455030, 6)
        self.assertAlmostEqual(cc.ccsd.energy(mcc, t1, t2, eris),
                               -0.208967840546667, 10)
        t1, t2 = cc.ccsd.update_amps(mcc, t1, t2, eris)
        self.assertAlmostEqual(cc.ccsd.energy(mcc, t1, t2, eris),
                               -0.212173678670510, 10)
        self.assertAlmostEqual(abs(t1).sum(), 0.05470123093500083, 8)
        self.assertAlmostEqual(abs(t2).sum(), 5.5605208386554716, 6)

        mcc.kernel()
        self.assertTrue(numpy.allclose(mcc.t2, mcc.t2.transpose(1, 0, 3, 2)))
        self.assertAlmostEqual(mcc.ecc, -0.2133432312951, 8)
        self.assertAlmostEqual(abs(mcc.t2).sum(), 5.63970279799556984, 6)

        nocc, nvir = t1.shape
        tau = t2 + numpy.einsum('ia,jb->ijab', t1, t1)
        ovvv = lib.unpack_tril(eris.ovvv).reshape(nocc, nvir, nvir, nvir)
        tmp = -numpy.einsum('ijcd,ka,kdcb->ijba', tau, t1, ovvv)
        t2a = tmp + tmp.transpose(1, 0, 3, 2)
        t2a = t2a[numpy.tril_indices(nocc)]
        t2a += mcc.add_wvvVV(t1, t2, eris)
        mcc.direct = True
        t2b = mcc.add_wvvVV(t1, t2, eris)
        self.assertTrue(numpy.allclose(t2a, t2b))
Exemple #30
0
def cosmo_fock_o1(cosmo, dm):
    mol = cosmo.mol
    nao = dm.shape[0]
    # phi
    cosmo.loadsegs()
    coords = cosmo.cosurf[:cosmo.nps*3].reshape(-1,3)
    fakemol = _make_fakemol(coords)
    j3c = df.incore.aux_e2(mol, fakemol, intor='cint3c2e_sph', aosym='s2ij')
    tril_dm = lib.pack_tril(dm) * 2
    diagidx = numpy.arange(nao)
    diagidx = diagidx*(diagidx+1)//2 + diagidx
    tril_dm[diagidx] *= .5
    cosmo.phi = -numpy.einsum('x,xk->k', tril_dm, j3c)
    for ia in range(mol.natm):
        cosmo.phi += mol.atom_charge(ia)/lib.norm(mol.atom_coord(ia)-coords, axis=1)
    cosmo.savesegs()
    # qk
    cosmo.charges()
    # vpot
    cosmo.loadsegs()
#X    fakemol = _make_fakemol(cosmo.cosurf[:cosmo.nps*3].reshape(-1,3))
#X    j3c = df.incore.aux_e2(mol, fakemol, intor='cint3c2e_sph', aosym='s2ij')
    fock = lib.unpack_tril(numpy.einsum('xk,k->x', j3c, -cosmo.qcos[:cosmo.nps]))
    fepsi = cosmo.fepsi() 
    fock = fepsi*fock
    return fock
Exemple #31
0
    def test_sort_eri(self):
        eris = mcc.ao2mo()
        nocc, nvir = mcc.t1.shape
        nmo = nocc + nvir
        vvop = numpy.empty((nvir, nvir, nocc, nmo))
        log = lib.logger.Logger(mcc.stdout, mcc.verbose)
        orbsym = ccsd_t._sort_eri(mcc, eris, nocc, nvir, vvop, log)

        o_sorted = numpy.hstack(
            [numpy.where(orbsym[:nocc] == i)[0] for i in range(8)])
        v_sorted = numpy.hstack(
            [numpy.where(orbsym[nocc:] == i)[0] for i in range(8)])
        eris_vvop = numpy.empty((nvir, nvir, nocc, nmo))
        eris_voov = numpy.asarray(eris.ovvo).transpose(1, 0, 3, 2)
        eris_voov = eris_voov[v_sorted][:, o_sorted][:, :, o_sorted][:, :, :,
                                                                     v_sorted]
        eris_vvop[:, :, :, :nocc] = eris_voov.transpose(0, 3, 1, 2)
        eris_vovv = lib.unpack_tril(
            numpy.asarray(eris.ovvv).transpose(1, 0,
                                               2).reshape(nocc * nvir, -1))
        eris_vovv = eris_vovv.reshape(nvir, nocc, nvir, nvir)
        eris_vovv = eris_vovv[v_sorted][:, o_sorted][:, :, v_sorted][:, :, :,
                                                                     v_sorted]
        eris_vvop[:, :, :, nocc:] = eris_vovv.transpose(0, 2, 1, 3)
        self.assertAlmostEqual(abs(eris_vvop - vvop).max(), 0, 9)
Exemple #32
0
    def from_pyscf(cls, hf):
        ''' Builds the RHF object from a pyscf.scf.hf.RHF object.

        Parameters
        ----------
        hf : pyscf.scf.hf.RHF
            Hartree-Fock object

        Returns
        -------
        hf : RHF
            Hartree-Fock object
        '''

        _hf = RHF(mol.Molecule.from_pyscf(hf.mol))

        _hf._pyscf = hf

        if not getattr(hf, 'with_df', False):
            _hf._eri_ao = util.restore(1, _hf.mol._pyscf.intor('int2e'),
                                       hf.mol.nao)
        else:
            if hf.with_df._cderi is None:
                hf.with_df.run()

            _hf._eri_ao = lib.unpack_tril(hf.with_df._cderi)

        return _hf
Exemple #33
0
def gamma2_intermediates(mycc, t1, t2, l1, l2, eris=None):
    dovov, dvvvv, doooo, doovv, dovvo, dvvov, dovvv, dooov = \
            ccsd_rdm.gamma2_intermediates(mycc, t1, t2, l1, l2)
    if eris is None: eris = ccsd._ERIS(mycc)

    nocc, nvir = t1.shape
    eris_ovvv = _cp(eris.ovvv)
    eris_ovvv = lib.unpack_tril(eris_ovvv.reshape(nocc * nvir, -1))
    eris_ovvv = eris_ovvv.reshape(nocc, nvir, nvir, nvir)
    mo_e = mycc._scf.mo_energy
    eia = lib.direct_sum('i-a->ia', mo_e[:nocc], mo_e[nocc:])
    d3 = lib.direct_sum('ia,jb,kc->ijkabc', eia, eia, eia)
    eris_ovoo = eris.ovoo
    w = (numpy.einsum('iabf,kjcf->ijkabc', eris_ovvv, t2) -
         numpy.einsum('iajm,mkbc->ijkabc', eris_ovoo, t2)) / d3
    v = numpy.einsum('iajb,kc->ijkabc', eris.ovov, t1) / d3 * .5
    w = p6_(w)
    v = p6_(v)
    rw = r6_(w)
    rwv = r6_(w * 2 + v)
    dovov += numpy.einsum('kc,ijkabc->iajb', t1, rw) * .5
    dooov -= numpy.einsum('mkbc,ijkabc->jmia', t2, rwv)
    # Note "dovvv +=" also changes the value of dvvov
    dovvv += numpy.einsum('kjcf,ijkabc->iabf', t2, rwv)
    dvvov = dovvv.transpose(2, 3, 0, 1)
    return dovov, dvvvv, doooo, doovv, dovvo, dvvov, dovvv, dooov
Exemple #34
0
def gamma1_intermediates(mycc, t1, t2, l1, l2, eris=None):
    doo, dov, dvo, dvv = ccsd_rdm.gamma1_intermediates(mycc, t1, t2, l1, l2)

    if eris is None: eris = ccsd._ERIS(mycc)
    nocc, nvir = t1.shape
    eris_ovvv = _cp(eris.ovvv)
    eris_ovvv = lib.unpack_tril(eris_ovvv.reshape(nocc * nvir, -1))
    eris_ovvv = eris_ovvv.reshape(nocc, nvir, nvir, nvir)
    mo_e = mycc._scf.mo_energy
    eia = lib.direct_sum('i-a->ia', mo_e[:nocc], mo_e[nocc:])
    d3 = lib.direct_sum('ia,jb,kc->ijkabc', eia, eia, eia)
    eris_ovoo = eris.ovoo
    w = (numpy.einsum('iabf,kjcf->ijkabc', eris_ovvv, t2) -
         numpy.einsum('iajm,mkbc->ijkabc', eris_ovoo, t2)) / d3
    v = numpy.einsum('iajb,kc->ijkabc', eris.ovov, t1) / d3 * .5
    w = p6_(w)
    v = p6_(v)
    wv = w + v
    rw = r6_(w)
    goo = -numpy.einsum('iklabc,jklabc->ij', wv, rw) * .5
    gvv = numpy.einsum('ijkacd,ijkbcd->ab', wv, rw) * .5

    doo += goo
    dvv += gvv
    return doo, dov, dvo, dvv
Exemple #35
0
def run(rhf, excite='ip', method='pyscf', nroots=1, tol=1e-14, debug=False):
    if excite == 'ip':
        o, v = rhf.occ > 0, rhf.occ == 0
        factor = -1
    elif excite == 'ea':
        v, o = rhf.occ > 0, rhf.occ == 0
        factor = 1

    nocc, nvir = np.sum(o), np.sum(v)
    eo, ev = rhf.e[o], rhf.e[v]
    co, cv = rhf.c[:,o], rhf.c[:,v]

    eri = rhf._pyscf.with_df._cderi
    qia = df_ao2mo(eri, co, cv, sym_in='s2', sym_out='s1')
    ijq = df_ao2mo(eri, co, co, sym_in='s2', sym_out='s2').T
    ijq = np.ascontiguousarray(lib.unpack_tril(ijq, axis=0).reshape((nocc*nocc, -1)))

    mij = get_1p(eo, ev, qia)
    diag = get_diag(eo, ev, mij)
    matvec, size = get_dot(eo, ev, ijq, qia, mij)

    if debug:
        return matvec, diag, mij

    w, v = diagonalise(matvec, diag, size, method=method, nroots=nroots, tol=tol)
    w *= factor

    return w, v
Exemple #36
0
    def test_r_incore(self):
        j3c = df.r_incore.aux_e2(mol, auxmol, intor='cint3c2e_spinor', aosym='s1')
        nao = mol.nao_2c()
        naoaux = auxmol.nao_nr()
        j3c = j3c.reshape(nao,nao,naoaux)

        eri0 = numpy.empty((nao,nao,naoaux), dtype=numpy.complex)
        pi = 0
        for i in range(mol.nbas):
            pj = 0
            for j in range(mol.nbas):
                pk = 0
                for k in range(mol.nbas, mol.nbas+auxmol.nbas):
                    shls = (i, j, k)
                    buf = gto.moleintor.getints_by_shell('cint3c2e_spinor',
                                                         shls, atm, bas, env)
                    di, dj, dk = buf.shape
                    eri0[pi:pi+di,pj:pj+dj,pk:pk+dk] = buf
                    pk += dk
                pj += dj
            pi += di
        self.assertTrue(numpy.allclose(eri0, j3c))
        eri1 = df.r_incore.aux_e2(mol, auxmol, intor='cint3c2e_spinor',
                                  aosym='s2ij')
        for i in range(naoaux):
            j3c[:,:,i] = lib.unpack_tril(eri1[:,i])
        self.assertTrue(numpy.allclose(eri0, j3c))
Exemple #37
0
def Lvv(t1,t2,eris):
    nocc, nvir = t1.shape
    fov = eris.fock[:nocc,nocc:]
    Lac = cc_Fvv(t1,t2,eris) - einsum('kc,ka->ac',fov,t1)
    eris_ovvv = lib.unpack_tril(np.asarray(eris.ovvv).reshape(nocc*nvir,-1)).reshape(nocc,nvir,nvir,nvir)
    Lac += 2*einsum('kdac,kd->ac',eris_ovvv,t1)
    Lac +=  -einsum('kcad,kd->ac',eris_ovvv,t1)
    return Lac
Exemple #38
0
def part_eri_hermi(eri, norb, nimp):
    eri1 = ao2mo.restore(4, eri, norb)
    for i in range(eri1.shape[0]):
        tmp = lib.unpack_tril(eri1[i])
        tmp[nimp:] = 0
        eri1[i] = lib.pack_tril(tmp + tmp.T)
    eri1 = lib.transpose_sum(eri1, inplace=True)
    return ao2mo.restore(8, eri1, norb) * 0.25
Exemple #39
0
 def batch_nuc(mol, grid_coords, out=None):
     fakemol = gto.fakemol_for_charges(grid_coords)
     j3c = aux_e2(mol,
                  fakemol,
                  intor='int3c2e',
                  aosym='s2ij',
                  cintopt=cintopt)
     return lib.unpack_tril(j3c.T, out=out)
Exemple #40
0
    def get_fock(self, rdm1=None):
        ''' Returns the Fock matrix resulting from the current, or
            provided, density.
        '''

        if rdm1 is None:
            rdm1 = self.rdm1

        nphys = self.nphys
        naux = self.eri.shape[0]
        maxblk = self.options['maxblk']

        j = np.zeros((nphys * (nphys + 1) // 2), dtype=types.float64)
        k = np.zeros((nphys, nphys), dtype=types.float64)

        rdm1_tril = lib.pack_tril(rdm1 + np.tril(rdm1, k=-1))
        c_int = ctypes.c_int
        args = (c_int(nphys), (c_int * 4)(0, nphys, 0,
                                          nphys), lib.c_null_ptr(), c_int(0))
        buf = np.empty((2, maxblk, nphys, nphys))

        for p0 in range(0, naux, maxblk):
            s = slice(p0, min(p0 + maxblk, naux))

            eri1 = self.eri[s]
            naux_block = eri1.shape[0]

            rho = np.dot(eri1, rdm1_tril)
            j += np.dot(rho, eri1)

            buf1 = buf[0, :naux_block]
            _fdrv(to_ptr(buf1), to_ptr(eri1), to_ptr(rdm1), c_int(naux_block),
                  *args)

            buf2 = lib.unpack_tril(eri1, out=buf[1])
            k = util.dgemm(buf1.reshape((-1, nphys)).T,
                           buf2.reshape((-1, nphys)),
                           c=k,
                           beta=1)

        j = lib.unpack_tril(j).reshape(rdm1.shape)
        k = k.reshape(rdm1.shape)

        f = self.h1e + j - 0.5 * k

        return f
Exemple #41
0
 def load(Lpq, bufR, bufI):
     shape = Lpq.shape
     if unpack:
         tmp = numpy.ndarray(shape, buffer=buf)
         tmp[:] = Lpq.real
         LpqR = lib.unpack_tril(tmp, out=bufR).reshape(-1,nao**2)
         tmp[:] = Lpq.imag
         LpqI = lib.unpack_tril(tmp, lib.ANTIHERMI, out=bufI).reshape(-1,nao**2)
     else:
         LpqR = numpy.ndarray(shape, buffer=bufR)
         LpqR[:] = Lpq.real
         LpqI = numpy.ndarray(shape, buffer=bufI)
         LpqI[:] = Lpq.imag
     if transpose102:
         LpqR = numpy.asarray(LpqR.reshape(-1,nao,nao).transpose(1,0,2), order='C')
         LpqI = numpy.asarray(LpqI.reshape(-1,nao,nao).transpose(1,0,2), order='C')
     return LpqR, LpqI
Exemple #42
0
def _make_eris_outcore(mycc, mo_coeff=None):
    cput0 = (time.clock(), time.time())
    log = logger.Logger(mycc.stdout, mycc.verbose)
    eris = _ChemistsERIs()
    eris._common_init_(mycc, mo_coeff)

    mol = mycc.mol
    mo_coeff = eris.mo_coeff
    nocc = eris.nocc
    nao, nmo = mo_coeff.shape
    nvir = nmo - nocc
    orbo = mo_coeff[:,:nocc]
    orbv = mo_coeff[:,nocc:]
    nvpair = nvir * (nvir+1) // 2
    eris.feri1 = lib.H5TmpFile()
    eris.oooo = eris.feri1.create_dataset('oooo', (nocc,nocc,nocc,nocc), 'f8')
    eris.ovoo = eris.feri1.create_dataset('ovoo', (nocc,nvir,nocc,nocc), 'f8', chunks=(nocc,1,nocc,nocc))
    eris.ovov = eris.feri1.create_dataset('ovov', (nocc,nvir,nocc,nvir), 'f8', chunks=(nocc,1,nocc,nvir))
    eris.ovvo = eris.feri1.create_dataset('ovvo', (nocc,nvir,nvir,nocc), 'f8', chunks=(nocc,1,nvir,nocc))
    eris.ovvv = eris.feri1.create_dataset('ovvv', (nocc,nvir,nvir,nvir), 'f8')
    eris.oovv = eris.feri1.create_dataset('oovv', (nocc,nocc,nvir,nvir), 'f8', chunks=(nocc,nocc,1,nvir))
    eris.vvvv = eris.feri1.create_dataset('vvvv', (nvir,nvir,nvir,nvir), 'f8')
    max_memory = max(MEMORYMIN, mycc.max_memory-lib.current_memory()[0])

    ftmp = lib.H5TmpFile()
    ao2mo.full(mol, mo_coeff, ftmp, max_memory=max_memory, verbose=log)
    eri = ftmp['eri_mo']

    nocc_pair = nocc*(nocc+1)//2
    tril2sq = lib.square_mat_in_trilu_indices(nmo)
    oo = eri[:nocc_pair]
    eris.oooo[:] = ao2mo.restore(1, oo[:,:nocc_pair], nocc)
    oovv = lib.take_2d(oo, tril2sq[:nocc,:nocc].ravel(), tril2sq[nocc:,nocc:].ravel())
    eris.oovv[:] = oovv.reshape(nocc,nocc,nvir,nvir)
    oo = oovv = None

    tril2sq = lib.square_mat_in_trilu_indices(nmo)
    blksize = min(nvir, max(BLKMIN, int(max_memory*1e6/8/nmo**3/2)))
    for p0, p1 in lib.prange(0, nvir, blksize):
        q0, q1 = p0+nocc, p1+nocc
        off0 = q0*(q0+1)//2
        off1 = q1*(q1+1)//2
        buf = lib.unpack_tril(eri[off0:off1])

        tmp = buf[ tril2sq[q0:q1,:nocc] - off0 ]
        eris.ovoo[:,p0:p1] = tmp[:,:,:nocc,:nocc].transpose(1,0,2,3)
        eris.ovvo[:,p0:p1] = tmp[:,:,nocc:,:nocc].transpose(1,0,2,3)
        eris.ovov[:,p0:p1] = tmp[:,:,:nocc,nocc:].transpose(1,0,2,3)
        eris.ovvv[:,p0:p1] = tmp[:,:,nocc:,nocc:].transpose(1,0,2,3)

        tmp = buf[ tril2sq[q0:q1,nocc:q1] - off0 ]
        eris.vvvv[p0:p1,:p1] = tmp[:,:,nocc:,nocc:]
        if p0 > 0:
            eris.vvvv[:p0,p0:p1] = tmp[:,:p0,nocc:,nocc:].transpose(1,0,2,3)
        buf = tmp = None
    log.timer('CCSD integral transformation', *cput0)
    return eris
Exemple #43
0
def _trans_cvcv_(mo, ncore, ncas, fload, ao_loc=None):
    nmo = mo[0].shape[1]
    c_nmo = ctypes.c_int(nmo)

    jc_pp = numpy.empty((ncore[0],nmo,nmo))
    jc_PP = numpy.zeros((nmo,nmo))
    kc_pp = numpy.empty((ncore[0],nmo,nmo))
    jcvcv = numpy.zeros((ncore[0],nmo-ncore[0],ncore[0],nmo-ncore[0]))
    cvCV = numpy.empty((ncore[0],nmo-ncore[0],ncore[1],nmo-ncore[1]))
    vcp = numpy.empty((nmo-ncore[0],ncore[0],nmo))
    cpp = numpy.empty((ncore[0],nmo,nmo))
    for i in range(ncore[0]):
        buf = fload(i)
        klshape = (0, ncore[1], ncore[1], nmo)
        _ao2mo.nr_e2(buf[ncore[0]:nmo], mo[1], klshape,
                      aosym='s4', mosym='s1', out=cvCV[i], ao_loc=ao_loc)

        klshape = (0, nmo, 0, nmo)
        tmp = _ao2mo.nr_e2(buf[i:i+1], mo[1], klshape, aosym='s4',
                            mosym='s1', ao_loc=ao_loc)
        jc_PP += tmp.reshape(nmo,nmo)

        klshape = (0, ncore[0], 0, nmo)
        _ao2mo.nr_e2(buf[ncore[0]:nmo], mo[0], klshape,
                      aosym='s4', mosym='s1', out=vcp, ao_loc=ao_loc)
        kc_pp[i,ncore[0]:] = vcp[:,i]

        klshape = (0, nmo, 0, nmo)
        _ao2mo.nr_e2(buf[:ncore[0]], mo[0], klshape,
                      aosym='s4', mosym='s2', out=buf[:ncore[0]],
                      ao_loc=ao_loc)
        lib.unpack_tril(buf[:ncore[0]], out=cpp)
        jc_pp[i] = cpp[i]
        kc_pp[i,:ncore[0]] = cpp[:,i]

        #jcvcv = cvcv * 2 - cvcv.transpose(2,1,0,3) - ccvv.transpose(0,2,1,3)
        jcvcv[i] = vcp[:,:,ncore[0]:] * 2 \
                 - vcp[:,:,ncore[0]:].transpose(2,1,0) \
                 - cpp[:,ncore[0]:,ncore[0]:].transpose(1,0,2)

    return jc_pp, jc_PP, kc_pp, jcvcv, cvCV
Exemple #44
0
def _get_ovvv_base(ovvv, *slices):
    if len(ovvv.shape) == 3:  # DO NOT use .ndim here for h5py library
                              # backward compatbility
        ovw = np.asarray(ovvv[slices])
        nocc, nvir, nvir_pair = ovw.shape
        ovvv = lib.unpack_tril(ovw.reshape(nocc*nvir,nvir_pair))
        nvir1 = ovvv.shape[2]
        return ovvv.reshape(nocc,nvir,nvir1,nvir1)
    elif slices:
        return ovvv[slices]
    else:
        return ovvv
Exemple #45
0
    def test_unpack(self):
        a = numpy.random.random((400,400))
        a = a+a*.5j
        for i in range(400):
            a[i,i] = a[i,i].real
        b = a-a.T.conj()
        b = numpy.array((b,b))
        x = lib.hermi_triu(b[0].T, hermi=2, inplace=0)
        self.assertAlmostEqual(abs(b[0].T-x).max(), 0, 12)

        x = lib.hermi_triu(b[1], hermi=2, inplace=0)
        self.assertAlmostEqual(abs(b[1]-x).max(), 0, 12)
        self.assertAlmostEqual(abs(x - lib.unpack_tril(lib.pack_tril(x), 2)).max(), 0, 12)

        x = lib.hermi_triu(a, hermi=1, inplace=0)
        self.assertAlmostEqual(abs(x-x.T.conj()).max(), 0, 12)

        xs = numpy.asarray((x,x,x))
        self.assertAlmostEqual(abs(xs - lib.unpack_tril(lib.pack_tril(xs))).max(), 0, 12)

        numpy.random.seed(1)
        a = numpy.random.random((5050,20))
        self.assertAlmostEqual(lib.finger(lib.unpack_tril(a, axis=0)), -103.03970592075423, 10)
Exemple #46
0
        def get_hcore(self, mol=None):
            if hasattr(method, 'get_hcore'):
                h1e = method.get_hcore(mol)
            else:  # post-HF objects
                h1e = method._scf.get_hcore(mol)

            if 0: # For debug
                v = 0
                for i,q in enumerate(charges):
                    mol.set_rinv_origin_(coords[i])
                    v += mol.intor('cint1e_rinv_sph') * q
            else:
                fakemol = _make_fakemol(coords)
                j3c = df.incore.aux_e2(mol, fakemol, intor='cint3c2e_sph', aosym='s2ij')
                v = lib.unpack_tril(numpy.einsum('xk,k->x', j3c, charges))
            return h1e + v
Exemple #47
0
def _add_vvvv(mycc, t1T, t2T, eris, out=None, with_ovvv=None, t2sym=None):
    '''t2sym: whether t2 has the symmetry t2[ijab]==t2[jiba] or
    t2[ijab]==-t2[jiab] or t2[ijab]==-t2[jiba]
    '''
    if t2sym == 'jiba':
        nvir_seg, nvir, nocc = t2T.shape[:3]
        Ht2tril = _add_vvvv_tril(mycc, t1T, t2T, eris, with_ovvv=with_ovvv)
        Ht2 = numpy.zeros_like(t2T)
        Ht2 = lib.unpack_tril(Ht2tril.reshape(nvir_seg*nvir,nocc*(nocc+1)//2),
                              filltriu=lib.PLAIN, out=Ht2).reshape(t2T.shape)
        oidx = numpy.arange(nocc)
        Ht2[:,:,oidx,oidx] *= .5
    else:
        Ht2 = _add_vvvv_full(mycc, t1T, t2T, eris, out, with_ovvv)
        Ht2 *= .5
    return Ht2
Exemple #48
0
        def get_hcore(self, mol=None):
            if mol is None: mol = self.mol
            if hasattr(method, 'get_hcore'):
                h1e = method_class.get_hcore(self, mol)
            else:  # DO NOT modify post-HF objects to avoid the MM charges applied twice
                raise RuntimeError('mm_charge function cannot be applied on post-HF methods')

            if pyscf.DEBUG:
                v = 0
                for i,q in enumerate(charges):
                    mol.set_rinv_origin(coords[i])
                    v += mol.intor('cint1e_rinv_sph') * -q
            else:
                fakemol = _make_fakemol(coords)
                j3c = df.incore.aux_e2(mol, fakemol, intor='cint3c2e_sph', aosym='s2ij')
                v = lib.unpack_tril(numpy.einsum('xk,k->x', j3c, -charges))
            return h1e + v
Exemple #49
0
def contract(myci, civec, eris):
    nocc = myci.nocc
    nmo = myci.nmo
    nvir = nmo - nocc
    c0 = civec[0]
    c1 = civec[1:nocc*nvir+1].reshape(nocc,nvir)
    c2 = civec[nocc*nvir+1:].reshape(nocc,nocc,nvir,nvir)

    foo = eris.fock[:nocc,:nocc]
    fov = eris.fock[:nocc,nocc:]
    fvv = eris.fock[nocc:,nocc:]
    eris_vovv = lib.unpack_tril(eris.vovv).reshape(nvir,nocc,nvir,-1)

    t1 = numpy.einsum('ib,ab->ia', c1, fvv)
    t1-= numpy.einsum('ja,ji->ia', c1, foo)
    t1+= numpy.einsum('jb,aijb->ia', c1, eris.voov) * 2
    t1-= numpy.einsum('jb,abij->ia', c1, eris.vvoo)
    theta = c2 * 2 - c2.transpose(1,0,2,3)
    t1 += numpy.einsum('ijab,jb->ia', theta, fov)
    t1 += numpy.einsum('ijbc,cjba->ia', theta, eris_vovv)
    t1 -= numpy.einsum('jkba,bjki->ia', theta, eris.vooo)

    tw = numpy.einsum('bc,ijac->ijab', fvv, c2)
    tw-= numpy.einsum('kj,kiba->ijab', foo, c2)

    theta = c2 * 2 - c2.transpose(1,0,2,3)
    tw -= numpy.einsum('ikac,bckj->ijab', c2, eris.vvoo)
    tw -= numpy.einsum('ikca,bckj->ijba', c2, eris.vvoo)
    tw += numpy.einsum('ikac,ckjb->ijab', theta, eris.voov)

    tw += numpy.einsum('ia,jb->ijab', c1, fov)
    tw += numpy.einsum('jc,aicb->jiba', c1, eris_vovv)
    tw -= numpy.einsum('ka,bjik->jiba', c1, eris.vooo)

    t2  = tw + tw.transpose(1,0,3,2)
    t2 += numpy.einsum('kilj,klab->ijab', eris.oooo, c2)
    t2 += myci.add_wvvVV(c2, eris)

    t1 += fov * c0
    t2 += eris.voov.transpose(1,2,0,3) * c0
    tau = c2*2 - c2.transpose(1,0,2,3)
    t0  = numpy.einsum('ia,ia', fov, c1) * 2
    t0 += numpy.einsum('aijb,ijab', eris.voov, tau)
    cinew = numpy.hstack((t0, t1.ravel(), t2.ravel()))
    return cinew
Exemple #50
0
    def test_sort_eri(self):
        eris = mcc.ao2mo()
        nocc, nvir = mcc.t1.shape
        nmo = nocc + nvir
        vvop = numpy.empty((nvir,nvir,nocc,nmo))
        log = lib.logger.Logger(mcc.stdout, mcc.verbose)
        orbsym = ccsd_t._sort_eri(mcc, eris, nocc, nvir, vvop, log)

        o_sorted = numpy.hstack([numpy.where(orbsym[:nocc] == i)[0] for i in range(8)])
        v_sorted = numpy.hstack([numpy.where(orbsym[nocc:] == i)[0] for i in range(8)])
        eris_vvop = numpy.empty((nvir,nvir,nocc,nmo))
        eris_ovov = numpy.asarray(eris.ovov).reshape(nocc,nvir,nocc,nvir)
        eris_ovov = eris_ovov[o_sorted][:,v_sorted][:,:,o_sorted][:,:,:,v_sorted]
        eris_vvop[:,:,:,:nocc] = eris_ovov.transpose(1,3,0,2)
        eris_ovvv = lib.unpack_tril(numpy.asarray(eris.ovvv).reshape(nocc*nvir,-1))
        eris_ovvv = eris_ovvv.reshape(nocc,nvir,nvir,nvir)
        eris_ovvv = eris_ovvv[o_sorted][:,v_sorted][:,:,v_sorted][:,:,:,v_sorted]
        eris_vvop[:,:,:,nocc:] = eris_ovvv.transpose(1,2,0,3)
        self.assertAlmostEqual(abs(eris_vvop-vvop).sum(), 0, 9)
Exemple #51
0
 def test_rhf_veff(self):
     nao = mol.nao_nr()
     numpy.random.seed(1)
     dm = numpy.random.random((2,nao,nao))
     mf = scf.density_fit(scf.RHF(mol))
     vhf1 = mf.get_veff(mol, dm, hermi=0)
     naux = mf._cderi.shape[0]
     cderi = numpy.empty((naux,nao,nao))
     for i in range(naux):
         cderi[i] = lib.unpack_tril(mf._cderi[i])
     vj0 = []
     vk0 = []
     for dmi in dm:
         v1 = numpy.einsum('kij,ij->k', cderi, dmi)
         vj0.append(numpy.einsum('kij,k->ij', cderi, v1))
         v1 = numpy.einsum('pij,jk->pki', cderi, dmi.T)
         vk0.append(numpy.einsum('pki,pkj->ij', cderi, v1))
     vj1, vk1 = scf.dfhf.get_jk_(mf, mol, dm, 0)
     self.assertTrue(numpy.allclose(vj0, vj1))
     self.assertTrue(numpy.allclose(numpy.array(vk0), vk1))
     vhf0 = vj1 - vk1 * .5
     self.assertTrue(numpy.allclose(vhf0, vhf1))
Exemple #52
0
def ecp_int(cell, kpts=None):
    from pyscf.pbc.df import incore
    if kpts is None:
        kpts_lst = numpy.zeros((1,3))
    else:
        kpts_lst = numpy.reshape(kpts, (-1,3))

    cell, contr_coeff = gto.cell._split_basis(cell)
    lib.logger.debug1(cell, 'nao %d -> nao %d', *(contr_coeff.shape))

    ecpcell = gto.Cell()
    ecpcell._atm = cell._atm
    # append a fictitious s function to mimic the auxiliary index in pbc.incore.
    # ptr2last_env_idx to force PBCnr3c_fill_* function to copy the entire "env"
    ptr2last_env_idx = len(cell._env) - 1
    ecpbas = numpy.vstack([[0, 0, 1, 1, 0, ptr2last_env_idx, 0, 0],
                           cell._ecpbas]).astype(numpy.int32)
    ecpcell._bas = ecpbas
    ecpcell._env = cell._env
    # In pbc.incore _ecpbas is appended to two sets of cell._bas and the
    # fictitious s function.
    cell._env[AS_ECPBAS_OFFSET] = cell.nbas * 2 + 1
    cell._env[AS_NECPBAS] = len(cell._ecpbas)
    # shls_slice of auxiliary index (0,1) corresponds to the fictitious s function
    shls_slice = (0, cell.nbas, 0, cell.nbas, 0, 1)

    kptij_lst = numpy.hstack((kpts_lst,kpts_lst)).reshape(-1,2,3)
    buf = incore.aux_e2(cell, ecpcell, 'ECPscalar', aosym='s2',
                        kptij_lst=kptij_lst, shls_slice=shls_slice)
    buf = buf.reshape(len(kpts_lst),-1)
    mat = []
    for k, kpt in enumerate(kpts_lst):
        v = lib.unpack_tril(buf[k], lib.HERMITIAN)
        if abs(kpt).sum() < 1e-9:  # gamma_point:
            v = v.real
        mat.append(reduce(numpy.dot, (contr_coeff.T, v, contr_coeff)))
    if kpts is None or numpy.shape(kpts) == (3,):
        mat = mat[0]
    return mat
Exemple #53
0
def get_pp_loc_part2(cell, kpts=None):
    '''PRB, 58, 3641 Eq (1), integrals associated to C1, C2, C3, C4
    '''
    from pyscf.pbc.df import incore
    if kpts is None:
        kpts_lst = numpy.zeros((1,3))
    else:
        kpts_lst = numpy.reshape(kpts, (-1,3))
    nkpts = len(kpts_lst)

    intors = ('int3c2e', 'int3c1e', 'int3c1e_r2_origk',
              'int3c1e_r4_origk', 'int3c1e_r6_origk')
    kptij_lst = numpy.hstack((kpts_lst,kpts_lst)).reshape(-1,2,3)
    buf = 0
    for cn in range(1, 5):
        fakecell = fake_cell_vloc(cell, cn)
        if fakecell.nbas > 0:
            v = incore.aux_e2(cell, fakecell, intors[cn], aosym='s2', comp=1,
                              kptij_lst=kptij_lst)
            buf += numpy.einsum('...i->...', v)

    if isinstance(buf, int):
        if any(cell.atom_symbol(ia) in cell._pseudo for ia in range(cell.natm)):
            pass
        else:
            lib.logger.warn(cell, 'cell.pseudo was specified but its elements %s '
                             'were not found in the system.', cell._pseudo.keys())
        vpploc = [0] * nkpts
    else:
        buf = buf.reshape(nkpts,-1)
        vpploc = []
        for k, kpt in enumerate(kpts_lst):
            v = lib.unpack_tril(buf[k])
            if abs(kpt).sum() < 1e-9:  # gamma_point:
                v = v.real
            vpploc.append(v)
    if kpts is None or numpy.shape(kpts) == (3,):
        vpploc = vpploc[0]
    return vpploc
Exemple #54
0
def get_gth_pp(mol):
    from pyscf.gto import ATOM_OF
    from pyscf.pbc.gto import Cell
    from pyscf.pbc.gto.pseudo import pp_int
    from pyscf.df import incore

    # Analytical integration for get_pp_loc_part1(cell).
    fakemol = pp_int.fake_cell_vloc(mol, 0)
    vpploc = 0
    if fakemol.nbas > 0:
        charges = fakemol.atom_charges()
        atmlst = fakemol._bas[:,ATOM_OF]
        v = incore.aux_e2(mol, fakemol, 'int3c2e', aosym='s2', comp=1)
        v = numpy.einsum('...i,i->...', v, -charges[atmlst])
        vpploc += lib.unpack_tril(v)

    # To compute the rest part of GTH PP, mimic the mol with a 0D cell.
    cell_0D = mol.view(Cell)
    cell_0D.dimension = 0
    cell_0D.a = numpy.eye(3)
    vpploc += pp_int.get_pp_loc_part2(cell_0D).real
    vpploc += pp_int.get_pp_nl(cell_0D).real
    return vpploc
Exemple #55
0
def vector_to_amplitudes(vector, nmo, nocc):
    nvir = nmo - nocc
    nov = nocc * nvir
    nocc2 = nocc*(nocc+1)//2
    vlocs = [_task_location(nvir, task_id) for task_id in range(mpi.pool.size)]
    vloc0, vloc1 = vlocs[rank]
    nvir_seg = vloc1 - vloc0

    if rank == 0:
        t1T = vector[:nov].copy().reshape((nvir,nocc))
        mpi.bcast(t1T)
        t2tril = vector[nov:].reshape(nvir_seg,nvir,nocc2)
    else:
        t1T = mpi.bcast(None)
        t2tril = vector.reshape(nvir_seg,nvir,nocc2)

    t2T = lib.unpack_tril(t2tril.reshape(nvir_seg*nvir,nocc2), filltriu=lib.PLAIN)
    t2T = t2T.reshape(nvir_seg,nvir,nocc,nocc)
    t2tmp = mpi.alltoall([t2tril[:,p0:p1] for p0,p1 in vlocs], split_recvbuf=True)
    idx,idy = numpy.tril_indices(nocc)
    for task_id, (p0, p1) in enumerate(vlocs):
        tmp = t2tmp[task_id].reshape(p1-p0,nvir_seg,nocc2)
        t2T[:,p0:p1,idy,idx] = tmp.transpose(1,0,2)
    return t1T.T, t2T.transpose(2,3,0,1)
Exemple #56
0
def restore(symmetry, eri, norb, tao=None):
    r'''Convert the 2e integrals (in Chemist's notation) between different
    level of permutation symmetry (8-fold, 4-fold, or no symmetry)

    Args:
        symmetry : int or str
            code to present the target symmetry of 2e integrals

            | 's8' or '8' or 8 : 8-fold symmetry
            | 's4' or '4' or 4 : 4-fold symmetry
            | 's1' or '1' or 1 : no symmetry
            | 's2ij' or '2ij' : symmetric ij pair for (ij|kl) (TODO)
            | 's2ij' or '2kl' : symmetric kl pair for (ij|kl) (TODO)

            Note the 4-fold symmetry requires (ij|kl) == (ij|lk) == (ij|lk)
            while (ij|kl) != (kl|ij) is not required.

        eri : ndarray
            The symmetry of eri is determined by the size of eri and norb
        norb : int
            The symmetry of eri is determined by the size of eri and norb

    Returns:
        ndarray.  The shape depends on the target symmetry.

            | 8 : (norb*(norb+1)/2)*(norb*(norb+1)/2+1)/2
            | 4 : (norb*(norb+1)/2, norb*(norb+1)/2)
            | 1 : (norb, norb, norb, norb)

    Examples:

    >>> from pyscf import gto
    >>> from pyscf.scf import _vhf
    >>> from pyscf import ao2mo
    >>> mol = gto.M(atom='O 0 0 0; H 0 1 0; H 0 0 1', basis='sto3g')
    >>> eri = mol.intor('int2e')
    >>> eri1 = ao2mo.restore(1, eri, mol.nao_nr())
    >>> eri4 = ao2mo.restore(4, eri, mol.nao_nr())
    >>> eri8 = ao2mo.restore(8, eri, mol.nao_nr())
    >>> print(eri1.shape)
    (7, 7, 7, 7)
    >>> print(eri1.shape)
    (28, 28)
    >>> print(eri1.shape)
    (406,)
    '''
    targetsym = _stand_sym_code(symmetry)
    if targetsym not in ('8', '4', '1', '2kl', '2ij'):
        raise ValueError('symmetry = %s' % symmetry)

    if eri.dtype != numpy.double:
        raise RuntimeError('Complex integrals not supported')

    eri = numpy.asarray(eri, order='C')
    npair = norb*(norb+1)//2
    if eri.size == norb**4:  # s1
        if targetsym == '1':
            return eri.reshape(norb,norb,norb,norb)
        elif targetsym == '2kl':
            eri = lib.pack_tril(eri.reshape(norb**2,norb,norb))
            return eri.reshape(norb,norb,npair)
        elif targetsym == '2ij':
            eri = lib.pack_tril(eri.reshape(norb,norb,norb**2), axis=0)
            return eri.reshape(npair,norb,norb)
        else:
            return _convert('1', targetsym, eri, norb)

    elif eri.size == npair**2:  # s4
        if targetsym == '4':
            return eri.reshape(npair,npair)
        elif targetsym == '8':
            return lib.pack_tril(eri.reshape(npair,npair))
        elif targetsym == '2kl':
            return lib.unpack_tril(eri, lib.SYMMETRIC, axis=0)
        elif targetsym == '2ij':
            return lib.unpack_tril(eri, lib.SYMMETRIC, axis=-1)
        else:
            return _convert('4', targetsym, eri, norb)

    elif eri.size == npair*(npair+1)//2: # 8-fold
        if targetsym == '8':
            return eri.ravel()
        elif targetsym == '4':
            return lib.unpack_tril(eri.ravel(), lib.SYMMETRIC)
        elif targetsym == '2kl':
            return lib.unpack_tril(lib.unpack_tril(eri.ravel()), lib.SYMMETRIC, axis=0)
        elif targetsym == '2ij':
            return lib.unpack_tril(lib.unpack_tril(eri.ravel()), lib.SYMMETRIC, axis=-1)
        else:
            return _convert('8', targetsym, eri, norb)

    elif eri.size == npair*norb**2 and eri.shape[0] == npair:  # s2ij
        if targetsym == '2ij':
            return eri.reshape(npair,norb,norb)
        elif targetsym == '8':
            eri = lib.pack_tril(eri.reshape(npair,norb,norb))
            return lib.pack_tril(eri)
        elif targetsym == '4':
            return lib.pack_tril(eri.reshape(npair,norb,norb))
        elif targetsym == '1':
            eri = lib.unpack_tril(eri.reshape(npair,norb**2), lib.SYMMETRIC, axis=0)
            return eri.reshape(norb,norb,norb,norb)
        elif targetsym == '2kl':
            tril2sq = lib.square_mat_in_trilu_indices(norb)
            trilidx = numpy.tril_indices(norb)
            eri = lib.take_2d(eri.reshape(npair,norb**2), tril2sq.ravel(),
                              trilidx[0]*norb+trilidx[1])
            return eri.reshape(norb,norb,npair)

    elif eri.size == npair*norb**2 and eri.shape[-1] == npair:  # s2kl
        if targetsym == '2kl':
            return eri.reshape(norb,norb,npair)
        elif targetsym == '8':
            eri = lib.pack_tril(eri.reshape(norb,norb,npair), axis=0)
            return lib.pack_tril(eri)
        elif targetsym == '4':
            return lib.pack_tril(eri.reshape(norb,norb,npair), axis=0)
        elif targetsym == '1':
            eri = lib.unpack_tril(eri.reshape(norb**2,npair), lib.SYMMETRIC, axis=-1)
            return eri.reshape(norb,norb,norb,norb)
        elif targetsym == '2ij':
            tril2sq = lib.square_mat_in_trilu_indices(norb)
            trilidx = numpy.tril_indices(norb)
            eri = lib.take_2d(eri.reshape(norb**2,npair),
                              trilidx[0]*norb+trilidx[1], tril2sq.ravel())
            return eri.reshape(npair,norb,norb)

    else:
        raise RuntimeError('eri.size = %d, norb = %d' % (eri.size, norb))
Exemple #57
0
def get_j_kpts(mydf, dm_kpts, hermi=1, kpts=numpy.zeros((1,3)), kpt_band=None):
    cell = mydf.cell
    log = logger.Logger(mydf.stdout, mydf.verbose)
    t1 = (time.clock(), time.time())
    if mydf._cderi is None:
        mydf.build()
        t1 = log.timer_debug1('Init get_j_kpts', *t1)

    dm_kpts = lib.asarray(dm_kpts, order='C')
    dms = _format_dms(dm_kpts, kpts)
    nset, nkpts, nao = dms.shape[:3]
    auxcell = mydf.auxcell
    naux = auxcell.nao_nr()

    if kpt_band is None:
        kpts_band = kpts
    else:
        kpts_band = numpy.reshape(kpt_band, (-1,3))
    nband = len(kpts_band)
    j_real = gamma_point(kpts_band)

    dmsR = dms.real.reshape(nset,nkpts,nao**2)
    dmsI = dms.imag.reshape(nset,nkpts,nao**2)
    kpt_allow = numpy.zeros(3)
    coulG = tools.get_coulG(cell, kpt_allow, gs=mydf.gs) / cell.vol
    ngs = len(coulG)
    vR = numpy.zeros((nset,ngs))
    vI = numpy.zeros((nset,ngs))
    max_memory = mydf.max_memory - lib.current_memory()[0]
    for k, pqkR, pqkI, p0, p1 \
            in mydf.ft_loop(cell, mydf.gs, kpt_allow, kpts, max_memory=max_memory):
        # contract dm to rho_rs(-G+k_rs)  (Note no .T on dm)
        # rho_rs(-G+k_rs) is computed as conj(rho_{rs^*}(G-k_rs))
        #               == conj(transpose(rho_sr(G+k_sr), (0,2,1)))
        for i in range(nset):
            rhoR = numpy.dot(dmsR[i,k], pqkR)
            rhoR+= numpy.dot(dmsI[i,k], pqkI)
            rhoI = numpy.dot(dmsI[i,k], pqkR)
            rhoI-= numpy.dot(dmsR[i,k], pqkI)
            vR[i,p0:p1] += rhoR * coulG[p0:p1]
            vI[i,p0:p1] += rhoI * coulG[p0:p1]
    weight = 1./nkpts
    vR *= weight
    vI *= weight

    pqkR = pqkI = coulG = None
    t1 = log.timer_debug1('get_j pass 1 to compute J(G)', *t1)

    vjR = numpy.zeros((nset,nband,nao*nao))
    vjI = numpy.zeros((nset,nband,nao*nao))
    for k, pqkR, pqkI, p0, p1 \
            in mydf.ft_loop(cell, mydf.gs, kpt_allow, kpts_band, max_memory=max_memory):
        for i in range(nset):
            vjR[i,k] += numpy.dot(pqkR, vR[i,p0:p1])
            vjR[i,k] -= numpy.dot(pqkI, vI[i,p0:p1])
            if not j_real:
                vjI[i,k] += numpy.dot(pqkI, vR[i,p0:p1])
                vjI[i,k] += numpy.dot(pqkR, vI[i,p0:p1])
        pqkR = pqkI = coulG = None

    rhoR  = numpy.zeros((nset,naux))
    rhoI  = numpy.zeros((nset,naux))
    jauxR = numpy.zeros((nset,naux))
    jauxI = numpy.zeros((nset,naux))
    for k, kpt in enumerate(kpts_band):
        kptii = numpy.asarray((kpt,kpt))
        p1 = 0
        for LpqR, LpqI, j3cR, j3cI in mydf.sr_loop(kptii, max_memory, False, False):
            p0, p1 = p1, p1+LpqR.shape[0]
            #:Lpq = (LpqR + LpqI*1j).transpose(1,0,2)
            #:j3c = (j3cR + j3cI*1j).transpose(1,0,2)
            #:rho [:,p0:p1] += numpy.einsum('Lpq,xpq->xL', Lpq, dms[:,k])
            #:jaux[:,p0:p1] += numpy.einsum('Lpq,xpq->xL', j3c, dms[:,k])
            rhoR [:,p0:p1]+= numpy.einsum('Lp,xp->xL', LpqR, dmsR[:,k])
            rhoR [:,p0:p1]-= numpy.einsum('Lp,xp->xL', LpqI, dmsI[:,k])
            rhoI [:,p0:p1]+= numpy.einsum('Lp,xp->xL', LpqR, dmsI[:,k])
            rhoI [:,p0:p1]+= numpy.einsum('Lp,xp->xL', LpqI, dmsR[:,k])
            jauxR[:,p0:p1]+= numpy.einsum('Lp,xp->xL', j3cR, dmsR[:,k])
            jauxR[:,p0:p1]-= numpy.einsum('Lp,xp->xL', j3cI, dmsI[:,k])
            jauxI[:,p0:p1]+= numpy.einsum('Lp,xp->xL', j3cR, dmsI[:,k])
            jauxI[:,p0:p1]+= numpy.einsum('Lp,xp->xL', j3cI, dmsR[:,k])

    weight = 1./nkpts
    jauxR *= weight
    jauxI *= weight
    rhoR *= weight
    rhoI *= weight
    vjR = vjR.reshape(nset,nband,nao,nao)
    vjI = vjI.reshape(nset,nband,nao,nao)
    for k, kpt in enumerate(kpts_band):
        kptii = numpy.asarray((kpt,kpt))
        p1 = 0
        for LpqR, LpqI, j3cR, j3cI in mydf.sr_loop(kptii, max_memory, True, False):
            p0, p1 = p1, p1+LpqR.shape[0]
            #:v = numpy.dot(jaux, Lpq) + numpy.dot(rho, j3c)
            #:vj_kpts[:,k] += lib.unpack_tril(v)
            v  = numpy.dot(jauxR[:,p0:p1], LpqR)
            v -= numpy.dot(jauxI[:,p0:p1], LpqI)
            v += numpy.dot(rhoR [:,p0:p1], j3cR)
            v -= numpy.dot(rhoI [:,p0:p1], j3cI)
            vjR[:,k] += lib.unpack_tril(v)
            if not j_real:
                v  = numpy.dot(jauxR[:,p0:p1], LpqI)
                v += numpy.dot(jauxI[:,p0:p1], LpqR)
                v += numpy.dot(rhoR [:,p0:p1], j3cI)
                v += numpy.dot(rhoI [:,p0:p1], j3cR)
                vjI[:,k] += lib.unpack_tril(v, lib.ANTIHERMI)
    t1 = log.timer_debug1('get_j pass 2', *t1)

    if j_real:
        vj_kpts = vjR
    else:
        vj_kpts = vjR + vjI*1j

    if kpt_band is not None and numpy.shape(kpt_band) == (3,):
        if nset == 1:  # One set of dm_kpts for KRHF
            return vj_kpts[0,0]
        else:
            return vj_kpts[:,0]
    else:
        return vj_kpts.reshape(dm_kpts.shape)