Python scipy.absolute() Examples

The following are 30 code examples of scipy.absolute(). 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: least_squares_first_peaks_2.py    From Automated_Music_Transcription with MIT License 6 votes vote down vote up
def get_stft_bin_freqs(self, stft, framerate):
        fft_length = self.HAN_WINDOW * framerate
        binResolution = float(framerate) / float(fft_length)
        stft_binFrequencies = []
        stft_magnitudes = []
        for i in range(len(stft)):
            binFreqs = []
            magnitudes = []
            for k in range(len(stft[i])):
                binFreq = k * binResolution
                if binFreq > self.minFreqConsidered and binFreq < self.maxFreqConsidered:
                    power_spectrum = scipy.absolute(stft[i][k]) * scipy.absolute(stft[i][k])
                    if power_spectrum > self.THRESHOLD:
                        binFreqs.append(binFreq)
                        magnitudes.append(power_spectrum)
                    stft_binFrequencies.append(binFreqs)
                    stft_magnitudes.append(magnitudes)
        return (stft_binFrequencies, stft_magnitudes) 
Example #2
Source File: HigherOrderNetwork.py    From pathpy with GNU Affero General Public License v3.0 6 votes vote down vote up
def getAlgebraicConnectivity(self, lanczosVecs = 15, maxiter = 20):
        """
        Returns the algebraic connectivity of the higher-order network.    
        
        @param lanczosVecs: number of Lanczos vectors to be used in the approximate
            calculation of eigenvectors and eigenvalues. This maps to the ncv parameter 
            of scipy's underlying function eigs. 
        @param maxiter: scaling factor for the number of iterations to be used in the 
            approximate calculation of eigenvectors and eigenvalues. The number of iterations 
            passed to scipy's underlying eigs function will be n*maxiter where n is the
            number of rows/columns of the Laplacian matrix.         
        """
    
        Log.add('Calculating algebraic connectivity ... ', Severity.INFO)

        L = self.getLaplacianMatrix()
        # NOTE: ncv sets additional auxiliary eigenvectors that are computed
        # NOTE: in order to be more confident to find the one with the largest
        # NOTE: magnitude, see https://github.com/scipy/scipy/issues/4987
        w = _sla.eigs( L, which="SM", k=2, ncv=lanczosVecs, return_eigenvectors=False, maxiter = maxiter )
        evals_sorted = _np.sort(_np.absolute(w))

        Log.add('finished.', Severity.INFO)

        return _np.abs(evals_sorted[1]) 
Example #3
Source File: threshold_finder.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def get_sum_of_squares(self, fft):
        sum_of_squares = 0.0
        for i in range(len(fft)):
            sum_of_squares += scipy.absolute(fft[i]) * sscipy.absolute(fft[i])
        return sum_of_squares 
Example #4
Source File: audio_tools.py    From representation_mixing with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compute_noise_avg_spectrum(self, nsignal):
        windownum = int(len(nsignal)//(self.winsize//2) - 1)
        avgamp = np.zeros(self.winsize)
        for l in range(windownum):
            avgamp += sp.absolute(sp.fft(get_frame(nsignal, self.winsize,l) * self.window))
        return avgamp/float(windownum) 
Example #5
Source File: audio_tools.py    From representation_mixing with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_amplitude(self,signal,l):
        if self.amplitude.has_key(l):
            return self.amplitude[l]
        else:
            amp = sp.absolute(sp.fft(get_frame(signal, self.winsize,l) * self.window))
            self.amplitude[l] = amp
            return amp 
Example #6
Source File: audio.py    From representation_mixing with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compute_noise_avg_spectrum(self, nsignal):
        windownum = int(len(nsignal)//(self.winsize//2) - 1)
        avgamp = np.zeros(self.winsize)
        for l in range(windownum):
            avgamp += sp.absolute(sp.fft(get_frame(nsignal, self.winsize,l) * self.window))
        return avgamp/float(windownum) 
Example #7
Source File: audio.py    From representation_mixing with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_amplitude(self,signal,l):
        if self.amplitude.has_key(l):
            return self.amplitude[l]
        else:
            amp = sp.absolute(sp.fft(get_frame(signal, self.winsize,l) * self.window))
            self.amplitude[l] = amp
            return amp 
Example #8
Source File: sum_stats_parsers.py    From ldpred with MIT License 5 votes vote down vote up
def get_beta_from_se(beta_read, se_read, eff_type, raw_beta, N):
    if se_read==0:
        return 
    if eff_type=='LINREG' or eff_type=='LOGOR':
        abs_beta = sp.absolute(beta_read)/se_read
    elif eff_type=='OR':
        abs_beta = sp.absolute(1-beta_read)/se_read
    else: 
        raise Exception('Unknown effect type')      
    return sp.sign(raw_beta) * abs_beta/ sp.sqrt(N) 
Example #9
Source File: ld.py    From ldpred with MIT License 5 votes vote down vote up
def shrink_r2(r,n):
    abs_r = sp.absolute(r)
    if abs_r<0.0001:
        return 0
    else:
        return r * sp.sqrt(max(0,(1.0+1.0/float(n-2))*(r**2-1.0/(1.0+float(n-2)))))/abs_r 
Example #10
Source File: ld.py    From ldpred with MIT License 5 votes vote down vote up
def shrink_r2_mat(D_i,n):
    D_i = sp.clip(D_i, -1, 1)
    D_i[(1.0/(n-1))>sp.absolute(D_i)]=0
    return D_i 
Example #11
Source File: compuestos.py    From pychemqt with GNU General Public License v3.0 5 votes vote down vote up
def facent_AmbroseWalton(Pvr):
    """Calculates acentric factor of a fluid using the Ambrose-Walton
    corresponding-states correlation

    Parameters
    ----------
    Pvr : float
        Reduced vapor pressure of compound at 0.7Tc, [-]

    Returns
    -------
    w : float
        Acentric factor [-]
    """
    Tr = 0.7
    t = 1-Tr
    f0 = (-5.97616*t + 1.29874*t**1.5 - 0.60394*t**2.5 - 1.06841*t**5)/Tr
    f1 = (-5.03365*t + 1.11505*t**1.5 - 5.41217*t**2.5 - 7.46628*t**5)/Tr
    f2 = (-0.64771*t + 2.41539*t**1.5 - 4.26979*t**2.5 + 3.25259*t**5)/Tr
    coef = roots([f2, f1, f0-log(Pvr)])

    if absolute(coef[0]) < absolute(coef[1]):
        return coef[0]
    else:
        return coef[1]


# Other properties 
Example #12
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 5 votes vote down vote up
def __quadratic_forms_matrix_euclidean(h1, h2):
    r"""
    Compute the bin-similarity matrix for the quadratic form distance measure.
    The matric :math:`A` for two histograms :math:`H` and :math:`H'` of size :math:`m` and
    :math:`n` respectively is defined as
    
    .. math::
    
        A_{m,n} = 1 - \frac{d_2(H_m, {H'}_n)}{d_{max}}
    
    with
    
    .. math::
    
       d_{max} = \max_{m,n}d_2(H_m, {H'}_n)
    
    See also
    --------
    quadratic_forms
    """
    A = scipy.repeat(h2[:,scipy.newaxis], h1.size, 1) # repeat second array to form a matrix
    A = scipy.absolute(A - h1) # euclidean distances
    return 1 - (A / float(A.max()))


# //////////////// #
# Helper functions #
# //////////////// # 
Example #13
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 #14
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 #15
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 #16
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 #17
Source File: audio_tools.py    From tools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compute_noise_avg_spectrum(self, nsignal):
        windownum = int(len(nsignal)//(self.winsize//2) - 1)
        avgamp = np.zeros(self.winsize)
        for l in range(windownum):
            avgamp += sp.absolute(sp.fft(get_frame(nsignal, self.winsize,l) * self.window))
        return avgamp/float(windownum) 
Example #18
Source File: audio_tools.py    From tools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_amplitude(self,signal,l):
        if self.amplitude.has_key(l):
            return self.amplitude[l]
        else:
            amp = sp.absolute(sp.fft(get_frame(signal, self.winsize,l) * self.window))
            self.amplitude[l] = amp
            return amp 
Example #19
Source File: HigherOrderNetwork.py    From pathpy with GNU Affero General Public License v3.0 5 votes vote down vote up
def getFiedlerVectorDense(self):
        """
         Returns the (dense)Fiedler vector of the higher-order network. The Fiedler 
         vector can be used for a spectral bisectioning of the network.             
        """
    
        # NOTE: The Laplacian is transposed for the sparse case to get the left
        # NOTE: eigenvalue.
        L = self.getLaplacianMatrix()
        # convert to dense matrix and transpose again to have the untransposed
        # laplacian again.
        w, v = _la.eig(L.todense().transpose(), right=False, left=True)

        return v[:,_np.argsort(_np.absolute(w))][:,1] 
Example #20
Source File: HigherOrderNetwork.py    From pathpy with GNU Affero General Public License v3.0 5 votes vote down vote up
def getEigenValueGap(self, includeSubPaths=True, lanczosVecs = 15, maxiter = 20):
        """
        Returns the eigenvalue gap of the transition matrix.

        @param includeSubPaths: whether or not to include subpath statistics in the 
            calculation of transition probabilities.
        """
    
        #NOTE to myself: most of the time goes for construction of the 2nd order
        #NOTE            null graph, then for the 2nd order null transition matrix   
    
        Log.add('Calculating eigenvalue gap ... ', Severity.INFO)

        # Build transition matrices
        T = self.getTransitionMatrix(includeSubPaths)
    
        # Compute the two largest eigenvalues
        # NOTE: ncv sets additional auxiliary eigenvectors that are computed
        # NOTE: in order to be more confident to actually find the one with the largest
        # NOTE: magnitude, see https://github.com/scipy/scipy/issues/4987
        w2 = _sla.eigs(T, which="LM", k=2, ncv=lanczosVecs, return_eigenvectors=False, maxiter = maxiter)
        evals2_sorted = _np.sort(-_np.absolute(w2))
        
        Log.add('finished.', Severity.INFO)
    
        return _np.abs(evals2_sorted[1]) 
Example #21
Source File: highest_peak_method.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def calculateFFT(self, duration, framerate, sample):
        """
            Calculates FFT for a given sound wave.
            Considers only frequencies with the magnitudes higher than
            a given threshold.
        """

        fft_length = int(duration * framerate)

        fft_length = get_next_power_2(fft_length)
        FFT = numpy.fft.fft(sample, n=fft_length)

        ''' ADJUSTING THRESHOLD '''
        threshold = 0
        power_spectra = []
        for i in range(len(FFT) / 2):
            power_spectrum = scipy.absolute(FFT[i]) * scipy.absolute(FFT[i])
            if power_spectrum > threshold:
                threshold = power_spectrum
            power_spectra.append(power_spectrum)
        threshold *= 0.1

        binResolution = float(framerate) / float(fft_length)
        frequency_power = []
        # For each bin calculate the corresponding frequency.
        for k in range(len(FFT) / 2):
            binFreq = k * binResolution

            if binFreq > self.minFreqConsidered and binFreq < self.maxFreqConsidered:
                power_spectrum = power_spectra[k]
                #dB = 10*math.log10(power_spectrum)
                if power_spectrum > threshold:
                    frequency_power.append((binFreq, power_spectrum))

        return frequency_power 
Example #22
Source File: least_squares_first_peaks_2.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def getFilteredFFT(self, FFT, duration, threshold):
        """
            Returns a list of frequencies with the magnitudes higher than a given threshold.
        """

        significantFreqs = []
        for i in range(len(FFT)):
            power_spectrum = scipy.absolute(FFT[i]) * scipy.absolute(FFT[i])
            if power_spectrum > threshold:
                significantFreqs.append(i / duration)

        return significantFreqs 
Example #23
Source File: least_squares_first_peaks_2.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def plotMagnitudeSpectrogram(self, rate, sample, framesz, hop):
        """
            Calculates and plots the magnitude spectrum of a given sound wave.
        """

        X = self.STFT(sample, rate, framesz, hop)

        # Plot the magnitude spectrogram.
        pylab.figure('Magnitude spectrogram')
        pylab.imshow(scipy.absolute(X.T), origin='lower', aspect='auto',
                     interpolation='nearest')
        pylab.xlabel('Time')
        pylab.ylabel('Frequency')
        pylab.show() 
Example #24
Source File: least_squares_first_peaks_2.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def plotPowerSpectrum(FFT, binFrequencies, maxFreq):
    """
        Calculates and plots the power spectrum of a given sound wave.
    """

    T = int(maxFreq)
    pylab.figure('Power spectrum')
    pylab.plot(binFrequencies[:T], scipy.absolute(FFT[:T]) * scipy.absolute(FFT[:T]),)
    pylab.xlabel('Frequency (Hz)')
    pylab.ylabel('Power spectrum (|X[k]|^2)')
    pylab.show() 
Example #25
Source File: first_peaks_method.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def plotMagnitudeSpectrogram(self, rate, sample, framesz, hop):
        """
            Calculates and plots the magnitude spectrum of a given sound wave.
        """

        X = self.STFT(sample, rate, framesz, hop)

        # Plot the magnitude spectrogram.
        pylab.figure('Magnitude spectrogram')
        pylab.imshow(scipy.absolute(X.T), origin='lower', aspect='auto',
                     interpolation='nearest')
        pylab.xlabel('Time')
        pylab.ylabel('Frequency')
        pylab.show() 
Example #26
Source File: first_peaks_method.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def plotPowerSpectrum(FFT, binFrequencies, maxFreq):
    """
        Calculates and plots the power spectrum of a given sound wave.
    """

    T = int(maxFreq)
    pylab.figure('Power spectrum')
    pylab.plot(binFrequencies[:T], scipy.absolute(FFT[:T]) * scipy.absolute(FFT[:T]),)
    pylab.xlabel('Frequency (Hz)')
    pylab.ylabel('Power spectrum (|X[k]|^2)')
    pylab.show() 
Example #27
Source File: threshold_finder.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def plot_power_spectrum(self, fft):
        T = int(600)

        pylab.figure('Power spectrum')
        pylab.plot(scipy.absolute(fft[:T]) * scipy.absolute(fft[:T]),)
        pylab.xlabel('Frequency [Hz]')
        pylab.ylabel('Power spectrum []')
        pylab.show() 
Example #28
Source File: threshold_finder.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def get_FFT_of_noise(self, x, rnorm):
        sum_of_singles = x[0] * self.get_FFT(self.first_single) + x[1] * self.get_FFT(self.second_single) + x[2] * self.get_FFT(self.third_single)
        fft = scipy.absolute(self.get_FFT(self.chord) - sum_of_singles)
        return fft 
Example #29
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 4 votes vote down vote up
def minowski(h1, h2, p = 2): # 46..45..14,11..43..44 / 45 us for p=int(-inf..-24..-1,1..24..inf) / float @array, +20 us @list \w 100 bins
    r"""
    Minowski distance.
    
    With :math:`p=2` equal to the Euclidean distance, with :math:`p=1` equal to the Manhattan distance,
    and the Chebyshev distance implementation represents the case of :math:`p=\pm inf`.
    
    The Minowksi distance between two histograms :math:`H` and :math:`H'` of size :math:`m` is
    defined as:
    
    .. math::
    
        d_p(H, H') = \left(\sum_{m=1}^M|H_m - H'_m|^p  
            \right)^{\frac{1}{p}}

    *Attributes:*
    
    - a real metric
    
    *Attributes for normalized histograms:*
    
    - :math:`d(H, H')\in[0, \sqrt[p]{2}]`
    - :math:`d(H, H) = 0`
    - :math:`d(H, H') = d(H', H)`
    
    *Attributes for not-normalized histograms:*
    
    - :math:`d(H, H')\in[0, \infty)`
    - :math:`d(H, H) = 0`
    - :math:`d(H, H') = d(H', H)`
    
    *Attributes for not-equal histograms:*
    
    - not applicable
    
    Parameters
    ----------
    h1 : sequence
        The first histogram.
    h2 : sequence
        The second histogram.
    p : float
        The :math:`p` value in the Minowksi distance formula.
    
    Returns
    -------
    minowski : float
        Minowski distance.
    
    Raises
    ------
    ValueError
        If ``p`` is zero.
    """
    h1, h2 = __prepare_histogram(h1, h2)
    if 0 == p: raise ValueError('p can not be zero')
    elif int == type(p):
        if p > 0 and p < 25: return __minowski_low_positive_integer_p(h1, h2, p)
        elif p < 0 and p > -25: return __minowski_low_negative_integer_p(h1, h2, p)
    return math.pow(scipy.sum(scipy.power(scipy.absolute(h1 - h2), p)), 1./p) 
Example #30
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 4 votes vote down vote up
def chebyshev_neg(h1, h2): # 12 us @array, 36 us @list \w 100 bins
    r"""
    Chebyshev negative distance.
    
    Also Tchebychev distance, Minimum or :math:`L_{-\infty}` metric; equal to Minowski
    distance with :math:`p=-\infty`. For the case of :math:`p=+\infty`, use `chebyshev`.
    
    The Chebyshev distance between two histograms :math:`H` and :math:`H'` of size :math:`m` is
    defined as:
    
    .. math::
    
        d_{-\infty}(H, H') = \min_{m=1}^M|H_m-H'_m|
    
    *Attributes:*

    - semimetric (triangle equation satisfied?)
    
    *Attributes for normalized histograms:*

    - :math:`d(H, H')\in[0, 1]`
    - :math:`d(H, H) = 0`
    - :math:`d(H, H') = d(H', H)`
    
    *Attributes for not-normalized histograms:*

    - :math:`d(H, H')\in[0, \infty)`
    - :math:`d(H, H) = 0`
    - :math:`d(H, H') = d(H', H)`
    
    *Attributes for not-equal histograms:*

    - not applicable
    
    Parameters
    ----------
    h1 : sequence
        The first histogram.
    h2 : sequence
        The second histogram.
    
    Returns
    -------
    chebyshev_neg : float
        Chebyshev negative distance.
    
    See also
    --------
    minowski, chebyshev
    """
    h1, h2 = __prepare_histogram(h1, h2)
    return min(scipy.absolute(h1 - h2))