Python numpy.count_nonzero() Examples

The following are 30 code examples of numpy.count_nonzero(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: dhf.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def make_para(sscobj, mol, mo1, mo_coeff, mo_occ, nuc_pair=None):
    if nuc_pair is None: nuc_pair = sscobj.nuc_pair
    if sscobj.mb.upper().startswith('ST'):
        nmo = mo_occ.size
        mo_coeff = mo_coeff[:,nmo//2:]
        mo_occ   = mo_occ[nmo//2:]

    nocc = numpy.count_nonzero(mo_occ> 0)
    nvir = numpy.count_nonzero(mo_occ==0)
    atm1lst = sorted(set([i for i,j in nuc_pair]))
    atm2lst = sorted(set([j for i,j in nuc_pair]))
    atm1dic = dict([(ia,k) for k,ia in enumerate(atm1lst)])
    atm2dic = dict([(ia,k) for k,ia in enumerate(atm2lst)])
    mo1 = mo1.reshape(len(atm1lst),3,nvir,nocc)
    h1 = make_h1(mol, mo_coeff, mo_occ, atm1lst)
    h1 = numpy.asarray(h1).reshape(len(atm1lst),3,nvir,nocc)

    para = []
    for i,j in nuc_pair:
        e = numpy.einsum('xij,yij->xy', h1[atm1dic[i]], mo1[atm2dic[j]].conj()) * 2
        para.append(e.real)
    return numpy.asarray(para) * nist.ALPHA**4 
Example #2
Source File: classifiers.py    From OpenCV-Computer-Vision-Projects-with-Python with MIT License 6 votes vote down vote up
def _confusion(self, y_test, Y_vote):
        """Calculates confusion matrix

            This method calculates the confusion matrix based on a vector of
            ground-truth labels (y-test) and a 2D voting matrix (Y_vote) of
            size (len(y_test), num_classes).
            Matrix element conf[r,c] will contain the number of samples that
            were predicted to have label r but have ground-truth label c.

            :param y_test: vector of ground-truth labels
            :param Y_vote: 2D voting matrix (rows=samples, cols=class votes)
            :returns: confusion matrix
        """
        y_hat = np.argmax(Y_vote, axis=1)
        conf = np.zeros((self.num_classes, self.num_classes)).astype(np.int32)
        for c_true in xrange(self.num_classes):
            # looking at all samples of a given class, c_true
            # how many were classified as c_true? how many as others?
            for c_pred in xrange(self.num_classes):
                y_this = np.where((y_test == c_true) * (y_hat == c_pred))
                conf[c_pred, c_true] = np.count_nonzero(y_this)
        return conf 
Example #3
Source File: classifiers.py    From OpenCV-Computer-Vision-Projects-with-Python with MIT License 6 votes vote down vote up
def _accuracy(self, y_test, Y_vote):
        """Calculates accuracy

            This method calculates the accuracy based on a vector of
            ground-truth labels (y_test) and a 2D voting matrix (Y_vote) of
            size (len(y_test), num_classes).

            :param y_test: vector of ground-truth labels
            :param Y_vote: 2D voting matrix (rows=samples, cols=class votes)
            :returns: accuracy e[0,1]
        """
        # predicted classes
        y_hat = np.argmax(Y_vote, axis=1)

        # all cases where predicted class was correct
        mask = y_hat == y_test
        return np.float32(np.count_nonzero(mask)) / len(y_test) 
Example #4
Source File: test_KnownRVPlanetsUniverse.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_init_indexes(self):
        r"""Test of initialization and __init__ -- indexes.

        Method: Insure the plan2star and sInds indexes are present. 
        Performs sanity check on the range of index values.
        TODO: More could be done to ensure the index values are correct.
        """
        universe = self.fixture
        self.basic_validation(universe)
        # indexes present
        self.assertIn('plan2star', universe.__dict__)
        self.assertIn('sInds', universe.__dict__)
        # range: 0 <= sInds < nStars
        self.assertEqual(0, np.count_nonzero(universe.sInds < 0))
        self.assertEqual(0, np.count_nonzero(universe.sInds >= universe.TargetList.nStars))
        # domain: plan2star covers 0...nPlans-1
        self.assertEqual(len(universe.plan2star), universe.nPlans)
        # range: 0 <= plan2star < nStars
        self.assertEqual(0, np.count_nonzero(universe.plan2star < 0))
        self.assertEqual(0, np.count_nonzero(universe.plan2star >= universe.TargetList.nStars)) 
Example #5
Source File: test_KnownRVPlanets.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_gen_mass(self):
        r"""Test gen_mass method.

        Approach: Ensures the output is set, of the correct type, length, and units.
        Check the range of the returned values.  Check that, for this power law, there
        are more small than large masses (for n large).
        """

        plan_pop = self.fixture
        n = 10000
        # call the routine
        masses = plan_pop.gen_mass(n)
        # check the type
        self.assertEqual(type(masses), type(1.0 * u.kg))
        # crude check on the shape (more small than large for this power law)
        midpoint = np.mean(plan_pop.Mprange)
        self.assertGreater(np.count_nonzero(masses < midpoint),
                           np.count_nonzero(masses > midpoint))
        # test some illegal "n" values
        n_list_bad = [-1, '100', 22.5]
        for n in n_list_bad:
            with self.assertRaises(AssertionError):
                masses = plan_pop.gen_mass(n) 
Example #6
Source File: test_KeplerLike1.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_gen_mass(self):
        r"""Test gen_mass method.

        Approach: Ensures the output is set, of the correct type, length, and units.
        Check that returned values are nonnegative.  Check that, for this power law, there
        are more small than large masses (for n large).
        """

        plan_pop = self.fixture
        n = 10000
        masses = plan_pop.gen_mass(n)

        self.assertEqual(len(masses), n)
        self.assertTrue(np.all(masses.value >= 0))
        self.assertTrue(np.all(np.isfinite(masses.value)))

        midpoint = np.mean(masses)
        self.assertGreater(np.count_nonzero(masses < midpoint),
                           np.count_nonzero(masses > midpoint))

        # test some illegal "n" values
        n_list_bad = [-1, '100', 22.5]
        for n in n_list_bad:
            with self.assertRaises(AssertionError):
                masses = plan_pop.gen_mass(n) 
Example #7
Source File: khf.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def canonicalize(mf, mo_coeff_kpts, mo_occ_kpts, fock=None):
    if fock is None:
        dm = mf.make_rdm1(mo_coeff_kpts, mo_occ_kpts)
        fock = mf.get_fock(dm=dm)
    mo_coeff = []
    mo_energy = []
    for k, mo in enumerate(mo_coeff_kpts):
        mo1 = np.empty_like(mo)
        mo_e = np.empty_like(mo_occ_kpts[k])
        occidx = mo_occ_kpts[k] == 2
        viridx = ~occidx
        for idx in (occidx, viridx):
            if np.count_nonzero(idx) > 0:
                orb = mo[:,idx]
                f1 = reduce(np.dot, (orb.T.conj(), fock[k], orb))
                e, c = scipy.linalg.eigh(f1)
                mo1[:,idx] = np.dot(orb, c)
                mo_e[idx] = e
        mo_coeff.append(mo1)
        mo_energy.append(mo_e)
    return mo_energy, mo_coeff 
Example #8
Source File: kmp2.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def _frozen_sanity_check(frozen, mo_occ, kpt_idx):
    '''Performs a few sanity checks on the frozen array and mo_occ.

    Specific tests include checking for duplicates within the frozen array.

    Args:
        frozen (array_like of int): The orbital indices that will be frozen.
        mo_occ (:obj:`ndarray` of int): The occupuation number for each orbital
            resulting from a mean-field-like calculation.
        kpt_idx (int): The k-point that `mo_occ` and `frozen` belong to.

    '''
    frozen = np.array(frozen)
    nocc = np.count_nonzero(mo_occ > 0)

    assert nocc, 'No occupied orbitals?\n\nnocc = %s\nmo_occ = %s' % (nocc, mo_occ)
    all_frozen_unique = (len(frozen) - len(np.unique(frozen))) == 0
    if not all_frozen_unique:
        raise RuntimeError('Frozen orbital list contains duplicates!\n\nkpt_idx %s\n'
                           'frozen %s' % (kpt_idx, frozen))
    if len(frozen) > 0 and np.max(frozen) > len(mo_occ) - 1:
        raise RuntimeError('Freezing orbital not in MO list!\n\nkpt_idx %s\n'
                           'frozen %s\nmax orbital idx %s' % (kpt_idx, frozen, len(mo_occ) - 1)) 
Example #9
Source File: kuhf.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def _unpack(vo, mo_occ):
    za = []
    zb = []
    p1 = 0
    for k, occ in enumerate(mo_occ[0]):
        no = numpy.count_nonzero(occ > 0)
        nv = occ.size - no
        p0, p1 = p1, p1 + no * nv
        za.append(vo[p0:p1].reshape(no,nv))

    for k, occ in enumerate(mo_occ[1]):
        no = numpy.count_nonzero(occ > 0)
        nv = occ.size - no
        p0, p1 = p1, p1 + no * nv
        zb.append(vo[p0:p1].reshape(no,nv))
    return za, zb 
Example #10
Source File: hf_symm.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def _dump_mo_energy(mol, mo_energy, mo_occ, ehomo, elumo, orbsym, title='',
                    verbose=logger.DEBUG):
    log = logger.new_logger(mol, verbose)
    for i, ir in enumerate(mol.irrep_id):
        irname = mol.irrep_name[i]
        ir_idx = (orbsym == ir)
        nso = numpy.count_nonzero(ir_idx)
        nocc = numpy.count_nonzero(mo_occ[ir_idx])
        e_ir = mo_energy[ir_idx]
        if nocc == 0:
            log.debug('%s%s nocc = 0', title, irname)
        elif nocc == nso:
            log.debug('%s%s nocc = %d  HOMO = %.15g',
                      title, irname, nocc, e_ir[nocc-1])
        else:
            log.debug('%s%s nocc = %d  HOMO = %.15g  LUMO = %.15g',
                      title, irname, nocc, e_ir[nocc-1], e_ir[nocc])
            if e_ir[nocc-1]+1e-3 > elumo:
                log.warn('%s%s HOMO %.15g > system LUMO %.15g',
                         title, irname, e_ir[nocc-1], elumo)
            if e_ir[nocc] < ehomo+1e-3:
                log.warn('%s%s LUMO %.15g < system HOMO %.15g',
                         title, irname, e_ir[nocc], ehomo)
        log.debug('   mo_energy = %s', e_ir) 
Example #11
Source File: addons.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def float_occ_(mf):
    '''
    For UHF, allowing the Sz value being changed during SCF iteration.
    Determine occupation of alpha and beta electrons based on energy spectrum
    '''
    from pyscf.scf import uhf
    assert(isinstance(mf, uhf.UHF))
    def get_occ(mo_energy, mo_coeff=None):
        mol = mf.mol
        ee = numpy.sort(numpy.hstack(mo_energy))
        n_a = numpy.count_nonzero(mo_energy[0]<(ee[mol.nelectron-1]+1e-3))
        n_b = mol.nelectron - n_a
        if mf.nelec is None:
            nelec = mf.mol.nelec
        else:
            nelec = mf.nelec
        if n_a != nelec[0]:
            logger.info(mf, 'change num. alpha/beta electrons '
                        ' %d / %d -> %d / %d',
                        nelec[0], nelec[1], n_a, n_b)
            mf.nelec = (n_a, n_b)
        return uhf.UHF.get_occ(mf, mo_energy, mo_coeff)
    mf.get_occ = get_occ
    return mf 
Example #12
Source File: test_rhf.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def test_uniq_var(self):
        mo_occ = mf.mo_occ.copy()
        nmo = mo_occ.size
        nocc = numpy.count_nonzero(mo_occ > 0)
        nvir = nmo - nocc
        numpy.random.seed(1)
        f = numpy.random.random((nmo,nmo))
        f_uniq = scf.hf.pack_uniq_var(f, mo_occ)
        self.assertEqual(f_uniq.size, nocc*nvir)
        f1 = scf.hf.unpack_uniq_var(f_uniq, mo_occ)
        self.assertAlmostEqual(abs(f1 + f1.T).max(), 0, 12)

        mo_occ[4:7] = 1
        ndocc = 4
        nocc = 7
        f_uniq = scf.hf.pack_uniq_var(f, mo_occ)
        self.assertEqual(f_uniq.size, nocc*(nmo-ndocc)-(nocc-ndocc)**2)

        f1 = scf.hf.unpack_uniq_var(f_uniq, mo_occ)
        self.assertAlmostEqual(abs(f1 + f1.T).max(), 0, 12) 
Example #13
Source File: linalg_helper.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def pick_real_eigs(w, v, nroots, envs):
    '''This function searchs the real eigenvalues or eigenvalues with small
    imaginary component.
    '''
    threshold = 1e-3
    abs_imag = abs(w.imag)
    # Grab `nroots` number of e with small(est) imaginary components
    max_imag_tol = max(threshold, numpy.sort(abs_imag)[min(w.size,nroots)-1])
    real_idx = numpy.where((abs_imag <= max_imag_tol))[0]
    nbelow_thresh = numpy.count_nonzero(abs_imag[real_idx] < threshold)
    if nbelow_thresh < nroots and w.size >= nroots:
        warnings.warn('Only %d eigenvalues (out of %3d requested roots) with imaginary part < %4.3g.\n'
                      % (nbelow_thresh, min(w.size,nroots), threshold))

    # Guess whether the matrix to diagonalize is real or complex
    if envs.get('dtype') == numpy.double:
        w, v, idx = _eigs_cmplx2real(w, v, real_idx, real_eigenvectors=True)
    else:
        w, v, idx = _eigs_cmplx2real(w, v, real_idx, real_eigenvectors=False)
    return w, v, idx 
Example #14
Source File: linalg_helper.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def _sort_by_similarity(w, v, nroots, conv, vlast, emin=None, heff=None):
    if not any(conv) or vlast is None:
        return w[:nroots], v[:,:nroots]

    head, nroots = vlast.shape
    conv = numpy.asarray(conv[:nroots])
    ovlp = vlast[:,conv].T.conj().dot(v[:head])
    ovlp = numpy.einsum('ij,ij->j', ovlp, ovlp)
    nconv = numpy.count_nonzero(conv)
    nleft = nroots - nconv
    idx = ovlp.argsort()
    sorted_idx = numpy.zeros(nroots, dtype=int)
    sorted_idx[conv] = numpy.sort(idx[-nconv:])
    sorted_idx[~conv] = numpy.sort(idx[:-nconv])[:nleft]

    e = w[sorted_idx]
    c = v[:,sorted_idx]
    return e, c 
Example #15
Source File: gcisd.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def from_ucisdvec(civec, nocc, orbspin):
    '''Convert the (spin-separated) CISD coefficient vector to GCISD
    coefficient vector'''
    nmoa = numpy.count_nonzero(orbspin == 0)
    nmob = numpy.count_nonzero(orbspin == 1)
    if isinstance(nocc, int):
        nocca = numpy.count_nonzero(orbspin[:nocc] == 0)
        noccb = numpy.count_nonzero(orbspin[:nocc] == 1)
    else:
        nocca, noccb = nocc
    nvira = nmoa - nocca

    if civec.size == nocca*nvira + (nocca*nvira)**2 + 1:  # RCISD
        c0, c1, c2 = cisd.cisdvec_to_amplitudes(civec, nmoa, nocca)
    else:  # UCISD
        c0, c1, c2 = ucisd.cisdvec_to_amplitudes(civec, (nmoa,nmob), (nocca,noccb))
    c1 = spatial2spin(c1, orbspin)
    c2 = spatial2spin(c2, orbspin)
    return amplitudes_to_cisdvec(c0, c1, c2) 
Example #16
Source File: gcisd.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def to_fcivec(cisdvec, nelec, orbspin, frozen=None):
    assert(numpy.count_nonzero(orbspin == 0) ==
           numpy.count_nonzero(orbspin == 1))
    norb = len(orbspin)
    frozen_mask = numpy.zeros(norb, dtype=bool)
    if frozen is None:
        pass
    elif isinstance(frozen, (int, numpy.integer)):
        frozen_mask[:frozen] = True
    else:
        frozen_mask[frozen] = True
    frozen = (numpy.where(frozen_mask[orbspin == 0])[0],
              numpy.where(frozen_mask[orbspin == 1])[0])
    nelec = (numpy.count_nonzero(orbspin[:nelec] == 0),
             numpy.count_nonzero(orbspin[:nelec] == 1))
    orbspin = orbspin[~frozen_mask]
    nmo = len(orbspin)
    nocc = numpy.count_nonzero(~frozen_mask[:sum(nelec)])
    ucisdvec = to_ucisdvec(cisdvec, nmo, nocc, orbspin)
    return ucisd.to_fcivec(ucisdvec, norb//2, nelec, frozen) 
Example #17
Source File: gcisd.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def from_fcivec(ci0, nelec, orbspin, frozen=None):
    if not (frozen is None or frozen == 0):
        raise NotImplementedError

    assert(numpy.count_nonzero(orbspin == 0) ==
           numpy.count_nonzero(orbspin == 1))
    norb = len(orbspin)
    frozen_mask = numpy.zeros(norb, dtype=bool)
    if frozen is None:
        pass
    elif isinstance(frozen, (int, numpy.integer)):
        frozen_mask[:frozen] = True
    else:
        frozen_mask[frozen] = True
    #frozen = (numpy.where(frozen_mask[orbspin == 0])[0],
    #          numpy.where(frozen_mask[orbspin == 1])[0])
    nelec = (numpy.count_nonzero(orbspin[:nelec] == 0),
             numpy.count_nonzero(orbspin[:nelec] == 1))
    ucisdvec = ucisd.from_fcivec(ci0, norb//2, nelec, frozen)
    nocc = numpy.count_nonzero(~frozen_mask[:sum(nelec)])
    return from_ucisdvec(ucisdvec, nocc, orbspin[~frozen_mask]) 
Example #18
Source File: test_tdrks.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def test_ab_hf(self):
        mf = scf.RHF(mol).run()
        a, b = rhf.get_ab(mf)
        fock = mf.get_hcore() + mf.get_veff()
        ftda = rhf.gen_tda_operation(mf, fock, singlet=True)[0]
        ftdhf = rhf.gen_tdhf_operation(mf, singlet=True)[0]
        nocc = numpy.count_nonzero(mf.mo_occ == 2)
        nvir = numpy.count_nonzero(mf.mo_occ == 0)
        numpy.random.seed(2)
        x, y = xy = numpy.random.random((2,nocc,nvir))
        ax = numpy.einsum('iajb,jb->ia', a, x)
        self.assertAlmostEqual(abs(ax - ftda([x]).reshape(nocc,nvir)).max(), 0, 6)

        ab1 = ax + numpy.einsum('iajb,jb->ia', b, y)
        ab2 =-numpy.einsum('iajb,jb->ia', b, x)
        ab2-= numpy.einsum('iajb,jb->ia', a, y)
        abxy_ref = ftdhf([xy]).reshape(2,nocc,nvir)
        self.assertAlmostEqual(abs(ab1 - abxy_ref[0]).max(), 0, 9)
        self.assertAlmostEqual(abs(ab2 - abxy_ref[1]).max(), 0, 9) 
Example #19
Source File: mp2.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def get_nocc(mp):
    if mp._nocc is not None:
        return mp._nocc
    elif mp.frozen is None:
        nocc = numpy.count_nonzero(mp.mo_occ > 0)
        assert(nocc > 0)
        return nocc
    elif isinstance(mp.frozen, (int, numpy.integer)):
        nocc = numpy.count_nonzero(mp.mo_occ > 0) - mp.frozen
        assert(nocc > 0)
        return nocc
    elif isinstance(mp.frozen[0], (int, numpy.integer)):
        occ_idx = mp.mo_occ > 0
        occ_idx[list(mp.frozen)] = False
        nocc = numpy.count_nonzero(occ_idx)
        assert(nocc > 0)
        return nocc
    else:
        raise NotImplementedError 
Example #20
Source File: test_tdrks.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def test_ab_lda(self):
        mf = mf_lda
        a, b = rhf.get_ab(mf)
        ftda = rhf.gen_tda_operation(mf, singlet=True)[0]
        ftdhf = rhf.gen_tdhf_operation(mf, singlet=True)[0]
        nocc = numpy.count_nonzero(mf.mo_occ == 2)
        nvir = numpy.count_nonzero(mf.mo_occ == 0)
        numpy.random.seed(2)
        x, y = xy = numpy.random.random((2,nocc,nvir))
        ax = numpy.einsum('iajb,jb->ia', a, x)
        self.assertAlmostEqual(abs(ax - ftda([x]).reshape(nocc,nvir)).max(), 0, 9)

        ab1 = ax + numpy.einsum('iajb,jb->ia', b, y)
        ab2 =-numpy.einsum('iajb,jb->ia', b, x)
        ab2-= numpy.einsum('iajb,jb->ia', a, y)
        abxy_ref = ftdhf([xy]).reshape(2,nocc,nvir)
        self.assertAlmostEqual(abs(ab1 - abxy_ref[0]).max(), 0, 9)
        self.assertAlmostEqual(abs(ab2 - abxy_ref[1]).max(), 0, 9) 
Example #21
Source File: ccsd_slow.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def __init__(self, cc, mo_coeff):
        nocc = numpy.count_nonzero(cc.mo_occ > 0)
        eri0 = ao2mo.full(cc._scf._eri, mo_coeff)
        eri0 = ao2mo.restore(1, eri0, mo_coeff.shape[1])
        eri0 = eri0.reshape((mo_coeff.shape[1],)*4)
        self.oooo = eri0[:nocc,:nocc,:nocc,:nocc].copy()
        self.ooov = eri0[:nocc,:nocc,:nocc,nocc:].copy()
        self.ovoo = eri0[:nocc,nocc:,:nocc,:nocc].copy()
        self.oovo = eri0[:nocc,:nocc,nocc:,:nocc].copy()
        self.oovv = eri0[:nocc,:nocc,nocc:,nocc:].copy()
        self.ovov = eri0[:nocc,nocc:,:nocc,nocc:].copy()
        self.ovvo = eri0[:nocc,nocc:,nocc:,:nocc].copy()
        self.ovvv = eri0[:nocc,nocc:,nocc:,nocc:].copy()
        self.vvvv = eri0[nocc:,nocc:,nocc:,nocc:].copy()
        self.vvvo = eri0[nocc:,nocc:,nocc:,:nocc].copy()
        self.vovv = eri0[nocc:,:nocc,nocc:,nocc:].copy()
        self.vvov = eri0[nocc:,nocc:,:nocc,nocc:].copy()
        self.vvoo = eri0[nocc:,nocc:,:nocc,:nocc].copy()
        self.voov = eri0[nocc:,:nocc,:nocc,nocc:].copy()
        self.vooo = eri0[nocc:,:nocc,:nocc,:nocc].copy()
        self.mo_coeff = mo_coeff
        self.fock = numpy.diag(cc._scf.mo_energy) 
Example #22
Source File: ccsd_slow.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def _gamma1_intermediates(cc, t1, t2, l1, l2):
    d1 = ccsd_rdm._gamma1_intermediates(cc, t1, t2, l1, l2)
    if cc.frozen is None:
        return d1
    nocc = numpy.count_nonzero(cc.mo_occ>0)
    nvir = cc.mo_occ.size - nocc
    OA, VA, OF, VF = index_frozen_active(cc)
    doo = numpy.zeros((nocc,nocc))
    dov = numpy.zeros((nocc,nvir))
    dvo = numpy.zeros((nvir,nocc))
    dvv = numpy.zeros((nvir,nvir))
    doo[OA[:,None],OA] = d1[0]
    dov[OA[:,None],VA] = d1[1]
    dvo[VA[:,None],OA] = d1[2]
    dvv[VA[:,None],VA] = d1[3]
    return doo, dov, dvo, dvv 
Example #23
Source File: rhf.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def make_pso(sscobj, mol, mo1, mo_coeff, mo_occ, nuc_pair=None):
    if nuc_pair is None: nuc_pair = sscobj.nuc_pair
    para = []
    nocc = numpy.count_nonzero(mo_occ> 0)
    nvir = numpy.count_nonzero(mo_occ==0)
    atm1lst = sorted(set([i for i,j in nuc_pair]))
    atm2lst = sorted(set([j for i,j in nuc_pair]))
    atm1dic = dict([(ia,k) for k,ia in enumerate(atm1lst)])
    atm2dic = dict([(ia,k) for k,ia in enumerate(atm2lst)])
    mo1 = mo1.reshape(len(atm1lst),3,nvir,nocc)
    h1 = make_h1_pso(mol, mo_coeff, mo_occ, atm1lst)
    h1 = numpy.asarray(h1).reshape(len(atm1lst),3,nvir,nocc)
    for i,j in nuc_pair:
        # PSO = -Tr(Im[h1_ov], Im[mo1_vo]) + cc = 2 * Tr(Im[h1_vo], Im[mo1_vo])
        e = numpy.einsum('xij,yij->xy', h1[atm1dic[i]], mo1[atm2dic[j]])
        para.append(e*4)  # *4 for +c.c. and double occupnacy
    return numpy.asarray(para) * nist.ALPHA**4 
Example #24
Source File: hf.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def canonicalize(mf, mo_coeff, mo_occ, fock=None):
    '''Canonicalization diagonalizes the Fock matrix within occupied, open,
    virtual subspaces separatedly (without change occupancy).
    '''
    if fock is None:
        dm = mf.make_rdm1(mo_coeff, mo_occ)
        fock = mf.get_fock(dm=dm)
    coreidx = mo_occ == 2
    viridx = mo_occ == 0
    openidx = ~(coreidx | viridx)
    mo = numpy.empty_like(mo_coeff)
    mo_e = numpy.empty(mo_occ.size)
    for idx in (coreidx, openidx, viridx):
        if numpy.count_nonzero(idx) > 0:
            orb = mo_coeff[:,idx]
            f1 = reduce(numpy.dot, (orb.conj().T, fock, orb))
            e, c = scipy.linalg.eigh(f1)
            mo[:,idx] = numpy.dot(orb, c)
            mo_e[idx] = e
    return mo_e, mo 
Example #25
Source File: test_count_nonzero.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_not_none(self):
        mech = count_nonzero
        self.assertIsNotNone(mech) 
Example #26
Source File: test_count_nonzero.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def test_no_params(self):
        a = np.array([1, 2, 3])
        res = count_nonzero(a)
        self.assertIsNotNone(res) 
Example #27
Source File: addons.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def get_ghf_orbspin(mo_energy, mo_occ, is_rhf=None):
    '''Spin of each GHF orbital when the GHF orbitals are converted from
    RHF/UHF orbitals

    For RHF orbitals, the orbspin corresponds to first occupied orbitals then
    unoccupied orbitals.  In the occupied orbital space, if degenerated, first
    alpha then beta, last the (open-shell) singly occupied (alpha) orbitals. In
    the unoccupied orbital space, first the (open-shell) unoccupied (beta)
    orbitals if applicable, then alpha and beta orbitals

    For UHF orbitals, the orbspin corresponds to first occupied orbitals then
    unoccupied orbitals.
    '''
    if is_rhf is None:  # guess whether the orbitals are RHF orbitals
        is_rhf = mo_energy[0].ndim == 0

    if is_rhf:
        nmo = mo_energy.size
        nocc = numpy.count_nonzero(mo_occ >0)
        nvir = nmo - nocc
        ndocc = numpy.count_nonzero(mo_occ==2)
        nsocc = nocc - ndocc
        orbspin = numpy.array([0,1]*ndocc + [0]*nsocc + [1]*nsocc + [0,1]*nvir)
    else:
        nmo = mo_energy[0].size
        nocca = numpy.count_nonzero(mo_occ[0]>0)
        nvira = nmo - nocca
        noccb = numpy.count_nonzero(mo_occ[1]>0)
        nvirb = nmo - noccb
        # round(6) to avoid numerical uncertainty in degeneracy
        es = numpy.append(mo_energy[0][mo_occ[0] >0],
                          mo_energy[1][mo_occ[1] >0])
        oidx = numpy.argsort(es.round(6))
        es = numpy.append(mo_energy[0][mo_occ[0]==0],
                          mo_energy[1][mo_occ[1]==0])
        vidx = numpy.argsort(es.round(6))
        orbspin = numpy.append(numpy.array([0]*nocca+[1]*noccb)[oidx],
                               numpy.array([0]*nvira+[1]*nvirb)[vidx])
    return orbspin 
Example #28
Source File: ccsd_rdm.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def _make_rdm1(mycc, d1, with_frozen=True, ao_repr=False):
    r'''dm1[p,q] = <q_alpha^\dagger p_alpha> + <q_beta^\dagger p_beta>

    The convention of 1-pdm is based on McWeeney's book, Eq (5.4.20).
    The contraction between 1-particle Hamiltonian and rdm1 is
    E = einsum('pq,qp', h1, rdm1)
    '''
    doo, dov, dvo, dvv = d1
    nocc, nvir = dov.shape
    nmo = nocc + nvir
    dm1 = numpy.empty((nmo,nmo), dtype=doo.dtype)
    dm1[:nocc,:nocc] = doo + doo.conj().T
    dm1[:nocc,nocc:] = dov + dvo.conj().T
    dm1[nocc:,:nocc] = dm1[:nocc,nocc:].conj().T
    dm1[nocc:,nocc:] = dvv + dvv.conj().T
    dm1[numpy.diag_indices(nocc)] += 2

    if with_frozen and mycc.frozen is not None:
        nmo = mycc.mo_occ.size
        nocc = numpy.count_nonzero(mycc.mo_occ > 0)
        rdm1 = numpy.zeros((nmo,nmo), dtype=dm1.dtype)
        rdm1[numpy.diag_indices(nocc)] = 2
        moidx = numpy.where(mycc.get_frozen_mask())[0]
        rdm1[moidx[:,None],moidx] = dm1
        dm1 = rdm1

    if ao_repr:
        mo = mycc.mo_coeff
        dm1 = lib.einsum('pi,ij,qj->pq', mo, dm1, mo.conj())
    return dm1

# Note vvvv part of 2pdm have been symmetrized.  It does not correspond to
# vvvv part of CI 2pdm 
Example #29
Source File: gccsd_rdm.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def _make_rdm1(mycc, d1, with_frozen=True, ao_repr=False):
    r'''
    One-particle density matrix in the molecular spin-orbital representation
    (the occupied-virtual blocks from the orbital response contribution are
    not included).

    dm1[p,q] = <q^\dagger p>  (p,q are spin-orbitals)

    The convention of 1-pdm is based on McWeeney's book, Eq (5.4.20).
    The contraction between 1-particle Hamiltonian and rdm1 is
    E = einsum('pq,qp', h1, rdm1)
    '''
    doo, dov, dvo, dvv = d1
    nocc, nvir = dov.shape
    nmo = nocc + nvir

    dm1 = numpy.empty((nmo,nmo), dtype=doo.dtype)
    dm1[:nocc,:nocc] = doo + doo.conj().T
    dm1[:nocc,nocc:] = dov + dvo.conj().T
    dm1[nocc:,:nocc] = dm1[:nocc,nocc:].conj().T
    dm1[nocc:,nocc:] = dvv + dvv.conj().T
    dm1 *= .5
    dm1[numpy.diag_indices(nocc)] += 1

    if with_frozen and mycc.frozen is not None:
        nmo = mycc.mo_occ.size
        nocc = numpy.count_nonzero(mycc.mo_occ > 0)
        rdm1 = numpy.zeros((nmo,nmo), dtype=dm1.dtype)
        rdm1[numpy.diag_indices(nocc)] = 1
        moidx = numpy.where(mycc.get_frozen_mask())[0]
        rdm1[moidx[:,None],moidx] = dm1
        dm1 = rdm1

    if ao_repr:
        mo = mycc.mo_coeff
        dm1 = lib.einsum('pi,ij,qj->pq', mo, dm1, mo.conj())
    return dm1 
Example #30
Source File: mp2.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def make_fno(mp, thresh=1e-6, pct_occ=None, nvir_act=None, t2=None):
    r'''
    Frozen natural orbitals

    Returns:
        frozen : list or ndarray
            List of orbitals to freeze
        no_coeff : ndarray
            Semicanonical NO coefficients in the AO basis
    '''
    mf = mp._scf
    dm = mp.make_rdm1(t2=t2)

    nmo = mp.nmo
    nocc = mp.nocc
    n,v = numpy.linalg.eigh(dm[nocc:,nocc:])
    idx = numpy.argsort(n)[::-1]
    n,v = n[idx], v[:,idx]

    if nvir_act is None:
        if pct_occ is None:
            nvir_act = numpy.count_nonzero(n>thresh)
        else:
            print(numpy.cumsum(n/numpy.sum(n)))
            nvir_act = numpy.count_nonzero(numpy.cumsum(n/numpy.sum(n))<pct_occ)

    fvv = numpy.diag(mf.mo_energy[nocc:])
    fvv_no = numpy.dot(v.T, numpy.dot(fvv, v))
    _, v_canon = numpy.linalg.eigh(fvv_no[:nvir_act,:nvir_act])

    no_coeff_1 = numpy.dot(mf.mo_coeff[:,nocc:], numpy.dot(v[:,:nvir_act], v_canon))
    no_coeff_2 = numpy.dot(mf.mo_coeff[:,nocc:], v[:,nvir_act:])
    no_coeff = numpy.concatenate((mf.mo_coeff[:,:nocc], no_coeff_1, no_coeff_2), axis=1)

    return numpy.arange(nocc+nvir_act,nmo), no_coeff