Compute the log of the magnitude spectrum of frames
487353
def log_magnitude_spectrum(frames):
    """"""
    return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))
923658
def _calc_fourier_spectrum(self, fa_length=None):
        """"""

        if fa_length is None:
            # Use the next power of 2 for the length
            n = 1
            while n < self.accels.size:
                n <<= 1
        else:
            n = fa_length

        self._fourier_amps = np.fft.rfft(self._accels, n)

        freq_step = 1. / (2 * self._time_step * (n / 2))
        self._freqs = freq_step * np.arange(1 + n / 2)
1291382
def _compute_magnitude_scaling(self, rup, C):
        
        U, SS, NS, RS = self._get_fault_type_dummy_variables(rup)
        if rup.mag <= C['Mh']:
            return C['e1'] * U + C['e2'] * SS + C['e3'] * NS + C['e4'] * RS + \
                C['e5'] * (rup.mag - C['Mh']) + \
                C['e6'] * (rup.mag - C['Mh']) ** 2
        else:
            return C['e1'] * U + C['e2'] * SS + C['e3'] * NS + C['e4'] * RS + \
                C['e7'] * (rup.mag - C['Mh'])
427086
def hsll(wnd, res=20, neighbors=2):
  
  spectrum = dB20(rfft(wnd, res * len(wnd)))
  first_peak = next(get_peaks(spectrum, neighbors=neighbors))
  return max(spectrum[first_peak:]) - spectrum[0]
448991
def log_(t, alpha=1, beta=1):
    """"""
    return beta * np.log(alpha * np.maximum(0, t - 10 * beta) + 1)
728163
def _compute_magnitude(self, rup, C):
        
        return C['c1'] + C['c2'] * (rup.mag - 6.0) +\
            (C['c3'] * np.log(rup.mag / 6.0))
941538
def moving_frequency(self, data_frame):
        
        f = []
        for i in range(0, (data_frame.td[-1].astype('int') - self.window)):
            f.append(sum(data_frame.action_type[(data_frame.td >= i) & (data_frame.td < (i + self.window))] == 1) /
                     float(self.window))

        diff_mov_freq = (np.array(f[1:-1]) - np.array(f[0:-2])) / np.array(f[0:-2])

        duration = math.ceil(data_frame.td[-1])

        return diff_mov_freq, duration
1039074
def _parse_motion(block, **kwargs):
    """"""
    _, fa_length, time_step, name, fmt = parse_fixed_width(
        [(5, int), (5, int), (10, float), (30, to_str), (30, to_str)], block)

    scale, pga, _, header_lines, _ = parse_fixed_width(
        3 * [(10, to_float)] + 2 * [(5, int)], block)

    m = re.search(r'(\d+)\w(\d+)\.\d+', fmt)
    count_per_line = int(m.group(1))
    width = int(m.group(2))

    fname = os.path.join(os.path.dirname(kwargs['fname']), name)
    accels = np.genfromtxt(
        fname,
        delimiter=(count_per_line * [width]),
        skip_header=header_lines, )

    if np.isfinite(scale):
        pass
    elif np.isfinite(pga):
        scale = pga / np.abs(accels).max()
    else:
        scale = 1.

    accels *= scale
    m = motion.TimeSeriesMotion(fname, '', time_step, accels, fa_length)

    return m
508213
def _fourier(self):
        

        freq_bin_upper = 2000
        freq_bin_lower = 40
        fs = self._metadata['fs']
        Y_transformed = {}
        for key in self.Y_dict.keys():
            # normalize by fs, bins have units strain/Hz
            fs = self._metadata["fs"]
            Y_transformed[key] = (1./fs)*np.fft.fft(self.Y_dict[key])[freq_bin_lower:freq_bin_upper]
        self.Y_transformed = Y_transformed
        # add in transform metadata
        self._metadata["dF"] = 1./self._metadata["T"]

        # because we are in the fourier domain, we will need the psd
        self.psd = load_psd()[freq_bin_lower:freq_bin_upper]
        dF = self._metadata['dF']
        self.sigma = convert_psd_to_sigma(self.psd, dF)
389129
def stSpectralRollOff(X, c, fs):
    """"""
    totalEnergy = numpy.sum(X ** 2)
    fftLength = len(X)
    Thres = c*totalEnergy
    # Ffind the spectral rolloff as the frequency position 
    # where the respective spectral energy is equal to c*totalEnergy
    CumSum = numpy.cumsum(X ** 2) + eps
    [a, ] = numpy.nonzero(CumSum > Thres)
    if len(a) > 0:
        mC = numpy.float64(a[0]) / (float(fftLength))
    else:
        mC = 0.0
    return (mC)
50566
def spectral_entropy(data, numOfShortBlocks=10):
    """"""
    data = np.mean(data, axis=1)

    nFFT = len(data) // 2
    X = FFT(data, nFFT)
    L = len(X)                         # number of frame data
    Eol = np.sum(X ** 2)            # total spectral energy

    subWinLength = int(np.floor(L / numOfShortBlocks))   # length of sub-frame
    if L != subWinLength * numOfShortBlocks:
        X = X[0:subWinLength * numOfShortBlocks]

    # define sub-frames (using matrix reshape)
    subWindows = X.reshape(subWinLength, numOfShortBlocks, order='F').copy()

    # compute spectral sub-energies
    s = np.sum(subWindows ** 2, axis=0) / (Eol + EPSILON)

    # compute spectral entropy
    return -np.sum(s * np.log2(s + EPSILON))
1018993
def check_and_format_logs_params(start, end, tail):
    """"""
    def _decode_duration_type(duration_type):
        durations = {'m': 'minutes', 'h': 'hours', 'd': 'days', 'w': 'weeks'}
        return durations[duration_type]

    if not start:
        if tail:
            start_dt = maya.now().subtract(seconds=300).datetime(naive=True)
        else:
            start_dt = maya.now().subtract(days=1).datetime(naive=True)
    elif start and start[-1] in ['m', 'h', 'd', 'w']:
        value = int(start[:-1])
        start_dt = maya.now().subtract(
            **{_decode_duration_type(start[-1]): value}).datetime(naive=True)
    elif start:
        start_dt = maya.parse(start).datetime(naive=True)

    if end and end[-1] in ['m', 'h', 'd', 'w']:
        value = int(end[:-1])
        end_dt = maya.now().subtract(
            **{_decode_duration_type(end[-1]): value}).datetime(naive=True)
    elif end:
        end_dt = maya.parse(end).datetime(naive=True)
    else:
        end_dt = None
    return start_dt, end_dt
163968
def log_weights(self):
        """"""
        m = self.kernel.feature_log_prob_[self._match_class_pos()]
        u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()]

        return self._prob_inverse_transform(m - u)
403661
def fourier(self, freq=None):
        
        def get(y, freq):
            y = y - mean(y)
            nframes = len(y)
            ft = fft.fft(y)
            ft = ft[0:int(fix(nframes/2))]
            ampFt = 2*abs(ft)/nframes
            amp = ampFt[freq]
            ampSum = sqrt(sum(ampFt**2))
            co = amp / ampSum
            ph = -(pi/2) - angle(ft[freq])
            if ph < 0:
                ph += pi * 2
            return array([co, ph])

        if freq >= int(fix(size(self.index)/2)):
            raise Exception('Requested frequency, %g, is too high, '
                            'must be less than half the series duration' % freq)

        index = ['coherence', 'phase']
        return self.map(lambda x: get(x, freq), index=index)
46975
def psd(ts, nperseg=1500, noverlap=1200, plot=True):
    """"""
    ts = ts.squeeze()
    if ts.ndim is 1:
        ts = ts.reshape((-1, 1))
    fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
    window = signal.hamming(nperseg, sym=False)
    nfft = max(256, 2**np.int(np.log2(nperseg) + 1))
    freqs, pxx = signal.welch(ts, fs, window, nperseg, noverlap, nfft,
                              detrend='linear', axis=0)
    # Discard estimates for freq bins that are too low for the window size.
    # (require two full cycles to fit within the window)
    index = np.nonzero(freqs >= 2.0*fs/nperseg)[0][0]
    if index > 0:
        freqs = freqs[index:]
        pxx = pxx[index:]
    # Discard estimate for last freq bin as too high for Nyquist frequency:
    freqs = freqs[:-1]
    pxx = pxx[:-1]
    if plot is True:
        _plot_psd(ts, freqs, pxx)
    return freqs, pxx
905814
def _fftconv(a, b, axes=(0, 1)):
    """"""

    if cp.isrealobj(a) and cp.isrealobj(b):
        fft = cp.fft.rfftn
        ifft = cp.fft.irfftn
    else:
        fft = cp.fft.fftn
        ifft = cp.fft.ifftn
    dims = cp.maximum(cp.asarray([a.shape[i] for i in axes]),
                      cp.asarray([b.shape[i] for i in axes]))
    dims = [int(d) for d in dims]
    af = fft(a, dims, axes)
    bf = fft(b, dims, axes)
    return ifft(af * bf, dims, axes)
988955
def hilbert_amplitude(ts):
    """"""
    output = np.abs(signal.hilbert(signal.detrend(ts, axis=0), axis=0))
    return Timeseries(output, ts.tspan, labels=ts.labels)