Python scipy.sum() Examples

The following are 30 code examples of scipy.sum(). 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 scipy , or try the search function .
Example #1
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CalculateHarmonicTopoIndex(mol):
    """
    #################################################################
    Calculation of harmonic topological index proposed by Narnumi.

    ---->Hato

    Usage:

        result=CalculateHarmonicTopoIndex(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """
    deltas = [x.GetDegree() for x in mol.GetAtoms()]
    while 0 in deltas:
        deltas.remove(0)
    deltas = numpy.array(deltas, "d")
    nAtoms = mol.GetNumAtoms()

    res = nAtoms / sum(1.0 / deltas)

    return res 
Example #2
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CalculatePolarityNumber(mol):
    """
    #################################################################
    Calculation of Polarity number.

    It is the number of pairs of vertexes at

    distance matrix equal to 3

    ---->Pol

    Usage:

        result=CalculatePolarityNumber(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """
    Distance = Chem.GetDistanceMatrix(mol)
    res = 1.0 / 2 * sum(sum(Distance == 3))

    return res 
Example #3
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CalculateHarary(mol):
    """
    #################################################################
    Calculation of Harary number

    ---->Thara

    Usage:

        result=CalculateHarary(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """

    Distance = numpy.array(Chem.GetDistanceMatrix(mol), "d")

    return 1.0 / 2 * (sum(1.0 / Distance[Distance != 0])) 
Example #4
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CalculateSchiultz(mol):
    """
    #################################################################
    Calculation of Schiultz number

    ---->Tsch(log value)

    Usage:

        result=CalculateSchiultz(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """
    Distance = numpy.array(Chem.GetDistanceMatrix(mol), "d")
    Adjacent = numpy.array(Chem.GetAdjacencyMatrix(mol), "d")
    VertexDegree = sum(Adjacent)

    return sum(scipy.dot((Distance + Adjacent), VertexDegree)) 
Example #5
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CalculateZagreb1(mol):
    """
    #################################################################
    Calculation of Zagreb index with order 1 in a molecule

    ---->ZM1

    Usage:

        result=CalculateZagreb1(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """

    deltas = [x.GetDegree() for x in mol.GetAtoms()]
    return sum(numpy.array(deltas) ** 2) 
Example #6
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CalculateWeiner(mol):
    """
    #################################################################
    Calculation of Weiner number in a molecule

    ---->W

    Usage:

        result=CalculateWeiner(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """
    return 1.0 / 2 * sum(sum(Chem.GetDistanceMatrix(mol))) 
Example #7
Source File: MR.py    From mr_saliency with GNU General Public License v2.0 6 votes vote down vote up
def __MR_W_D_matrix(self,img,labels):
        s = sp.amax(labels)+1
        vect = self.__MR_superpixel_mean_vector(img,labels)
        
        adj = self.__MR_get_adj_loop(labels)
        
        W = sp.spatial.distance.squareform(sp.spatial.distance.pdist(vect))
        
        W = sp.exp(-1*W / self.weight_parameters['delta'])
        W[adj.astype(np.bool)] = 0
        

        D = sp.zeros((s,s)).astype(float)
        for i in range(s):
            D[i, i] = sp.sum(W[i])

        return W,D 
Example #8
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CalculateZagreb2(mol):

    """
    #################################################################
    Calculation of Zagreb index with order 2 in a molecule

    ---->ZM2

    Usage:

        result=CalculateZagreb2(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """
    ke = [
        x.GetBeginAtom().GetDegree() * x.GetEndAtom().GetDegree()
        for x in mol.GetBonds()
    ]

    return sum(ke) 
Example #9
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CalculateMZagreb2(mol):
    """
    #################################################################
    Calculation of Modified Zagreb index with order 2 in a molecule

    ---->MZM2

    Usage:

        result=CalculateMZagreb2(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """
    cc = [
        x.GetBeginAtom().GetDegree() * x.GetEndAtom().GetDegree()
        for x in mol.GetBonds()
    ]
    while 0 in cc:
        cc.remove(0)
    cc = numpy.array(cc, "d")
    res = sum((1.0 / cc) ** 2)
    return res 
Example #10
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def CalculatePlatt(mol):
    """
    #################################################################
    Calculation of Platt number in a molecule

    ---->Platt

    Usage:

        result=CalculatePlatt(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """
    cc = [
        x.GetBeginAtom().GetDegree() + x.GetEndAtom().GetDegree() - 2
        for x in mol.GetBonds()
    ]
    return sum(cc) 
Example #11
Source File: recipe-576547.py    From code with MIT License 6 votes vote down vote up
def coupling_optim(y,t):
	creation=s.zeros(n_bin)
	destruction=s.zeros(n_bin)
	#now I try to rewrite this in a more optimized way
	destruction = -s.dot(s.transpose(kernel),y)*y #much more concise way to express\
	#the destruction of k-mers 
	kyn = kernel*y[:,s.newaxis]*y[s.newaxis,:]
	for k in xrange(n_bin):
		creation[k] = s.sum(kyn[s.arange(k),k-s.arange(k)-1])
	creation=0.5*creation
	out=creation+destruction
	return out


#Now I go for the optimal optimization of the chi_{i,j,k} coefficients used by Garrick for
# dealing with a non-uniform grid. 
Example #12
Source File: recipe-576547.py    From code with MIT License 6 votes vote down vote up
def coupling_optim_garrick(y,t):
	creation=s.zeros(n_bin)
	destruction=s.zeros(n_bin)
	#now I try to rewrite this in a more optimized way
	destruction = -s.dot(s.transpose(kernel),y)*y #much more concise way to express\
	#the destruction of k-mers 
	
	for k in xrange(n_bin):
		kyn = (kernel*f_garrick[:,:,k])*y[:,s.newaxis]*y[s.newaxis,:]
		creation[k] = s.sum(kyn)
	creation=0.5*creation
	out=creation+destruction
	return out



#Now I work with the function for espressing smoluchowski equation when a uniform grid is used 
Example #13
Source File: _docopyregression.py    From pyradi with MIT License 6 votes vote down vote up
def compare_images(img1, img2, method='zeronorm'):
    # normalize to compensate for exposure difference, this may be unnecessary
    # consider disabling it
    img1 = normalize(img1)
    img2 = normalize(img2)
    # calculate the difference and its norms
    diff = img1 - img2  # elementwise for scipy arrays
    if method in 'zeronorm':
        inorm = norm(diff.ravel(), 0)  # Zero norm
    else:
        inorm = sum(abs(diff))  # Manhattan norm
    #normalise by image size
    inorm /= float(img1.size)
    return inorm


################################################################################# 
Example #14
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def CalculateBertzCT(mol):
    """
    #################################################################
    A topological index meant to quantify "complexity" of molecules.

    Consists of a sum of two terms, one representing the complexity

    of the bonding, the other representing the complexity of the

    distribution of heteroatoms.

    From S. H. Bertz, J. Am. Chem. Soc., vol 103, 3599-3601 (1981)

    ---->BertzCT(log value)

    Usage:

        result=CalculateBertzCT(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """
    temp = GD.BertzCT(mol)
    if temp > 0:
        return numpy.log10(temp)
    else:
        return "NaN" 
Example #15
Source File: image.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def compare_images(img1, img2):
    # normalize to compensate for exposure difference, this may be unnecessary
    # consider disabling it
    img1 = normalize(img1)
    img2 = normalize(img2)
    # calculate the difference and its norms
    diff = img1 - img2  # elementwise for scipy arrays
    m_norm = sum(abs(diff))  # Manhattan norm
    z_norm = norm(diff.ravel(), 0)  # Zero norm
    return (m_norm, z_norm) 
Example #16
Source File: timeSeries2.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def compare_images(img1, img2):
    # normalize to compensate for exposure difference, this may be unnecessary
    # consider disabling it
    img1 = normalize(img1)
    img2 = normalize(img2)
    # calculate the difference and its norms
    diff = img1 - img2  # elementwise for scipy arrays
    m_norm = sum(abs(diff))  # Manhattan norm
    z_norm = norm(diff.ravel(), 0)  # Zero norm
    return (m_norm, z_norm) 
Example #17
Source File: factor_analyzer.py    From factor_analyzer with GNU General Public License v2.0 5 votes vote down vote up
def _fit_ml_objective(psi, corr_mtx, n_factors):
        """
        The objective function passed to `minimize()` for ML.

        Parameters
        ----------
        psi : array-like
            Value passed to minimize the objective function.
        corr_mtx : array-like
            The correlation matrix.
        n_factors : int
            The number of factors to select.

        Returns
        -------
        error : float
            The scalar error calculated from the residuals
            of the loading matrix.

        Note
        ----
        The ML objective is based on the `factanal()` function
        from R's `stats` package. It may generate results different
        from the `fa()` function in `psych`.

        References
        ----------
        [1] https://github.com/SurajGupta/r-source/blob/master/src/library/stats/R/factanal.R
        """
        sc = np.diag(1 / np.sqrt(psi))
        sstar = np.dot(np.dot(sc, corr_mtx), sc)

        # get the eigenvalues and eigenvectors for n_factors
        values, _ = np.linalg.eigh(sstar)
        values = values[::-1][n_factors:]

        # calculate the error
        error = -(np.sum(np.log(values) - values) -
                  n_factors + corr_mtx.shape[0])
        return error 
Example #18
Source File: factor_analyzer.py    From factor_analyzer with GNU General Public License v2.0 5 votes vote down vote up
def get_communalities(self):
        """
        Calculate the communalities, given the
        factor loading matrix.

        Returns
        -------
        communalities : numpy array
            The communalities from the factor loading
            matrix.

        Examples
        --------
        >>> import pandas as pd
        >>> from factor_analyzer import FactorAnalyzer
        >>> df_features = pd.read_csv('tests/data/test02.csv')
        >>> fa = FactorAnalyzer(rotation=None)
        >>> fa.fit(df_features)
        FactorAnalyzer(bounds=(0.005, 1), impute='median', is_corr_matrix=False,
                method='minres', n_factors=3, rotation=None, rotation_kwargs={},
                use_smc=True)
        >>> fa.get_communalities()
        array([0.588758  , 0.00382308, 0.50452402, 0.72841183, 0.33184336,
               0.66208428, 0.61911036, 0.73194557, 0.64929612, 0.71149718])
        """
        # meets all of our expected criteria
        check_is_fitted(self, 'loadings_')
        loadings = self.loadings_.copy()
        communalities = (loadings ** 2).sum(axis=1)
        return communalities 
Example #19
Source File: factor_analyzer.py    From factor_analyzer with GNU General Public License v2.0 5 votes vote down vote up
def _get_factor_variance(loadings):
        """
        A helper method to get the factor variances,
        because sometimes we need them even before the
        model is fitted.

        Parameters
        ----------
        loadings : array-like
            The factor loading matrix,
            in whatever state.

        Returns
        -------
        variance : numpy array
            The factor variances.
        proportional_variance : numpy array
            The proportional factor variances.
        cumulative_variances : numpy array
            The cumulative factor variances.
        """
        n_rows = loadings.shape[0]

        # calculate variance
        loadings = loadings ** 2
        variance = np.sum(loadings, axis=0)

        # calculate proportional variance
        proportional_variance = variance / n_rows

        # calculate cumulative variance
        cumulative_variance = np.cumsum(proportional_variance, axis=0)

        return (variance,
                proportional_variance,
                cumulative_variance) 
Example #20
Source File: ld.py    From ldpred with MIT License 5 votes vote down vote up
def _calculate_D(snps, snp_i, snp, start_i, stop_i, ld_dict, ld_scores):
    m, n = snps.shape
    X = snps[start_i: stop_i]
    D_i = sp.dot(snp, X.T) / n
    D_i_shrunk = shrink_r2_mat(D_i,n)
    r2s = D_i ** 2
    ld_dict[snp_i] = D_i_shrunk
    lds_i = sp.sum(r2s - (1 - r2s) / (n - 2), dtype='float32')
    ld_scores[snp_i] = lds_i 
Example #21
Source File: util.py    From ldpred with MIT License 5 votes vote down vote up
def count_lines_fast(filename):
    opener = open
    if is_gz(filename):
        opener = gzip.open
    try:
        with opener(filename, 'rb') as f:
            bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))
            num_lines =sum( buf.count(b'\n') for buf in bufgen )
    except Exception:
        num_lines = -1
    return num_lines 
Example #22
Source File: util.py    From ldpred with MIT License 5 votes vote down vote up
def count_lines_slow(filename):
    opener = open
    if is_gz(filename):
        opener = gzip.open    
    try:
        with opener(filename, 'rb') as f:
            num_lines = sum(1 for line in f)
    except Exception:
        num_lines=-1
    return num_lines 
Example #23
Source File: plinkfiles.py    From ldpred with MIT License 5 votes vote down vote up
def parse_plink_snps(genotype_file, snp_indices):
    plinkf = plinkfile.PlinkFile(genotype_file)
    samples = plinkf.get_samples()
    num_individs = len(samples)
    num_snps = len(snp_indices)
    raw_snps = sp.empty((num_snps, num_individs), dtype='int8')
    # If these indices are not in order then we place them in the right place while parsing SNPs.
    snp_order = sp.argsort(snp_indices)
    ordered_snp_indices = list(snp_indices[snp_order])
    ordered_snp_indices.reverse()
    # Iterating over file to load SNPs
    snp_i = 0
    next_i = ordered_snp_indices.pop()
    line_i = 0
    max_i = ordered_snp_indices[0]
    while line_i <= max_i: 
        if line_i < next_i:
            next(plinkf)
        elif line_i == next_i:
            line = next(plinkf)
            snp = sp.array(line, dtype='int8')
            bin_counts = line.allele_counts()
            if bin_counts[-1] > 0:
                mode_v = sp.argmax(bin_counts[:2])
                snp[snp == 3] = mode_v
            s_i = snp_order[snp_i]
            raw_snps[s_i] = snp
            if line_i < max_i:
                next_i = ordered_snp_indices.pop()
            snp_i += 1
        line_i += 1
    plinkf.close()
    assert snp_i == len(raw_snps), 'Parsing SNPs from plink file failed.'
    num_indivs = len(raw_snps[0])
    freqs = sp.sum(raw_snps, 1, dtype='float32') / (2 * float(num_indivs))
    return raw_snps, freqs 
Example #24
Source File: util.py    From temci with GNU General Public License v3.0 5 votes vote down vote up
def geom_std(values: t.List[float]) -> float:
    """
    Calculates the geometric standard deviation for the passed values.
    Source: https://en.wikipedia.org/wiki/Geometric_standard_deviation
    """
    import scipy.stats as stats
    import scipy as sp
    gmean = stats.gmean(values)
    return sp.exp(sp.sqrt(sp.sum([sp.log(x / gmean) ** 2 for x in values]) / len(values))) 
Example #25
Source File: topology.py    From PyBioMed with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def CalculateXuIndex(mol):
    """
    #################################################################
    Calculation of Xu index

    ---->Xu

    Usage:

        result=CalculateXuIndex(mol)

        Input: mol is a molecule object

        Output: result is a numeric value
    #################################################################
    """
    nAT = mol.GetNumAtoms()
    deltas = [x.GetDegree() for x in mol.GetAtoms()]
    Distance = Chem.GetDistanceMatrix(mol)
    sigma = scipy.sum(Distance, axis=1)
    temp1 = 0.0
    temp2 = 0.0
    for i in range(nAT):
        temp1 = temp1 + deltas[i] * ((sigma[i]) ** 2)
        temp2 = temp2 + deltas[i] * (sigma[i])
    Xu = numpy.sqrt(nAT) * numpy.log(temp1 / temp2)

    return Xu 
Example #26
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 5 votes vote down vote up
def __minowski_low_positive_integer_p(h1, h2, p = 2): # 11..43 us for p = 1..24 \w 100 bins
    """
    A faster implementation of the Minowski distance for positive integer < 25.
    @note do not use this function directly, but the general @link minowski() method.
    @note the passed histograms must be scipy arrays.
    """
    mult = scipy.absolute(h1 - h2)
    dif = mult
    for _ in range(p - 1): dif = scipy.multiply(dif, mult)
    return math.pow(scipy.sum(dif), 1./p) 
Example #27
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 5 votes vote down vote up
def __minowski_low_negative_integer_p(h1, h2, p = 2): # 14..46 us for p = -1..-24 \w 100 bins
    """
    A faster implementation of the Minowski distance for negative integer > -25.
    @note do not use this function directly, but the general @link minowski() method.
    @note the passed histograms must be scipy arrays.
    """
    mult = scipy.absolute(h1 - h2)
    dif = mult
    for _ in range(-p + 1): dif = scipy.multiply(dif, mult)
    return math.pow(scipy.sum(1./dif), 1./p) 
Example #28
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 5 votes vote down vote up
def manhattan(h1, h2): # # 7 us @array, 31 us @list \w 100 bins
    r"""
    Equal to Minowski distance with :math:`p=1`.
    
    See also
    --------
    minowski
    """
    h1, h2 = __prepare_histogram(h1, h2)
    return scipy.sum(scipy.absolute(h1 - h2)) 
Example #29
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 5 votes vote down vote up
def euclidean(h1, h2): # 9 us @array, 33 us @list \w 100 bins
    r"""
    Equal to Minowski distance with :math:`p=2`.
    
    See also
    --------
    minowski
    """
    h1, h2 = __prepare_histogram(h1, h2)
    return math.sqrt(scipy.sum(scipy.square(scipy.absolute(h1 - h2)))) 
Example #30
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 5 votes vote down vote up
def __kullback_leibler(h1, h2): # 36.3 us
    """
    The actual KL implementation. @see kullback_leibler() for details.
    Expects the histograms to be of type scipy.ndarray.
    """
    result = h1.astype(scipy.float_)
    mask = h1 != 0
    result[mask] = scipy.multiply(h1[mask], scipy.log(h1[mask] / h2[mask]))
    return scipy.sum(result)