Return the spectrum and frequency indexes for real-valued input signal
777449
def calc_spectrum(signal, rate):
    """"""
    npts = len(signal)
    padto = 1 << (npts - 1).bit_length()
    # print 'length of signal {}, pad to {}'.format(npts, padto)
    npts = padto

    sp = np.fft.rfft(signal, n=padto) / npts
    # print('sp len ', len(sp))
    freq = np.arange((npts / 2) + 1) / (npts / rate)
    # print('freq len ', len(freq))
    return freq, abs(sp)
948197
def frequency_axis_ppm(self):
        
        return numpy.linspace(self.hertz_to_ppm(-self.sw / 2.0),
                              self.hertz_to_ppm(self.sw / 2.0),
                              self.np, endpoint=False)
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)
951950
def rfft2d_freqs(h, w):
    """"""

    fy = np.fft.fftfreq(h)[:, None]
    # when we have an odd input dimension we need to keep one additional
    # frequency and later cut off 1 pixel
    if w % 2 == 1:
        fx = np.fft.fftfreq(w)[: w // 2 + 2]
    else:
        fx = np.fft.fftfreq(w)[: w // 2 + 1]
    return np.sqrt(fx * fx + fy * fy)
96569
private List<Integer>[] getRobustPointList(double[][] spectrogramData) {

        int numX = spectrogramData.length;
        int numY = spectrogramData[0].length;

        double[][] allBanksIntensities = new double[numX][numY];
        int bandwidthPerBank = numY / numFilterBanks;

        for (int b = 0; b < numFilterBanks; b++) {

            double[][] bankIntensities = new double[numX][bandwidthPerBank];

            for (int i = 0; i < numX; i++) {
                System.arraycopy(spectrogramData[i], b * bandwidthPerBank, bankIntensities[i], 0, bandwidthPerBank);
            }

            // get the most robust point in each filter bank
            TopManyPointsProcessorChain processorChain = new TopManyPointsProcessorChain(bankIntensities, 1);
            double[][] processedIntensities = processorChain.getIntensities();

            for (int i = 0; i < numX; i++) {
                System.arraycopy(processedIntensities[i], 0, allBanksIntensities[i], b * bandwidthPerBank,
                                bandwidthPerBank);
            }
        }

        List<int[]> robustPointList = new LinkedList<int[]>();

        // find robust points
        for (int i = 0; i < allBanksIntensities.length; i++) {
            for (int j = 0; j < allBanksIntensities[i].length; j++) {
                if (allBanksIntensities[i][j] > 0) {

                    int[] point = new int[] {i, j};
                    //System.out.println(i+","+frequency);
                    robustPointList.add(point);
                }
            }
        }
        // end find robust points

        List<Integer>[] robustLists = new LinkedList[spectrogramData.length];
        for (int i = 0; i < robustLists.length; i++) {
            robustLists[i] = new LinkedList<>();
        }

        // 
        for (int[] coor : robustPointList) {
            robustLists[coor[0]].add(coor[1]);
        }

        // return the list per frame
        return robustLists;
    }
695905
function convertToObject(spectra) {
    var result={};
    for (var i=0; i<spectra.length; i++) {
        var spectrum=spectra[i];
        result[spectrum.type]=spectrum;
    }
    return result;
}
544284
def ref_frequency(self, context):
        
        num_chans = self._manager.spectral_window_table.getcol(MS.NUM_CHAN)
        ref_freqs = self._manager.spectral_window_table.getcol(MS.REF_FREQUENCY)

        data = np.hstack((np.repeat(rf, bs) for bs, rf in zip(num_chans, ref_freqs)))
        return data.reshape(context.shape).astype(context.dtype)
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)
999055
def spectrogram(timeseries, method_func, **kwargs):
    
    from ...spectrogram import Spectrogram

    # get params
    sampling = timeseries.sample_rate.to('Hz').value
    nproc = kwargs.pop('nproc', 1)
    nfft = kwargs.pop('nfft')
    noverlap = kwargs.pop('noverlap')
    nstride = nfft - noverlap

    # sanity check parameters
    if noverlap >= nfft:
        raise ValueError("overlap must be less than fftlength")

    # set up single process Spectrogram method
    def _psd(series):
        """Calculate a single PSD for a spectrogram
        """
        return method_func(series, nfft=nfft, **kwargs)[1]

    # define chunks
    chunks = []
    x = 0
    while x + nfft <= timeseries.size:
        y = min(timeseries.size, x + nfft)
        chunks.append((x, y))
        x += nstride

    tschunks = (timeseries.value[i:j] for i, j in chunks)

    # calculate PSDs with multiprocessing
    psds = mp_utils.multiprocess_with_queues(nproc, _psd, tschunks)

    # convert PSDs to array with spacing for averages
    numtimes = 1 + int((timeseries.size - nstride) / nstride)
    numfreqs = int(nfft / 2 + 1)
    data = numpy.zeros((numtimes, numfreqs), dtype=timeseries.dtype)
    data[:len(psds)] = psds

    # create output spectrogram
    unit = fft_utils.scale_timeseries_unit(
        timeseries.unit, scaling=kwargs.get('scaling', 'density'))
    out = Spectrogram(numpy.empty((numtimes, numfreqs),
                                  dtype=timeseries.dtype),
                      copy=False, dt=nstride * timeseries.dt, t0=timeseries.t0,
                      f0=0, df=sampling/nfft, unit=unit,
                      name=timeseries.name, channel=timeseries.channel)

    # normalize over-dense grid
    density = nfft // nstride
    weights = get_window('triangle', density)
    for i in range(numtimes):
        # get indices of overlapping columns
        x = max(0, i+1-density)
        y = min(i+1, numtimes-density+1)
        if x == 0:
            wgt = weights[-y:]
        elif y == numtimes - density + 1:
            wgt = weights[:y-x]
        else:
            wgt = weights
        # calculate weighted average
        out.value[i, :] = numpy.average(data[x:y], axis=0, weights=wgt)

    return out
640617
def corr2(X):
    ''' 
    '''
    X = np.atleast_3d(X)
    N = X.shape[0]
    D = X.shape[2]

    if D == 1:
        return np.zeros(N, dtype=np.float)

    trii = np.triu_indices(D, k=1)
    DD = len(trii[0])
    r = np.zeros((N, DD))
    for i in np.arange(N):
        rmat = np.corrcoef(X[i])  # get the ith window from each signal, result will be DxD
        r[i] = rmat[trii]
    return r
652841
def _get_index(self, index=None):
        

        if self.is_freq_type:
            if index is None:
                index = self._on
            return index, index.asi8
        return index, index
257987
def fft_freqs(n_fft, fs):
    
    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)
126097
def frequency_axis(self):
        
        return numpy.linspace(-self.sw / 2, self.sw / 2, self.np, endpoint=False)
1180377
def function(self,p):
        """"""
        return 0.5 + 0.5*np.sin(p.frequency*2*pi*self.pattern_y + p.phase)
682125
def min_freq(self):
        
        i = np.unravel_index(np.argmin(self.bands), self.bands.shape)

        return self.qpoints[i[1]], self.bands[i]
943023
def _get_arrays(self, wavelengths, **kwargs):
        """"""
        x = self._validate_wavelengths(wavelengths)
        y = self(x, **kwargs)

        if isinstance(wavelengths, u.Quantity):
            w = x.to(wavelengths.unit, u.spectral())
        else:
            w = x

        return w, y
429986
def spectral_pars_from_catalog(cat):
    """"""

    spectrum_type = cat['SpectrumType']
    pars = get_function_defaults(cat['SpectrumType'])
    par_idxs = {k: i for i, k in
                enumerate(get_function_par_names(cat['SpectrumType']))}

    for k in pars:
        pars[k]['value'] = cat['param_values'][par_idxs[k]]

    if spectrum_type == 'PowerLaw':

        pars['Index']['value'] *= -1.0
        pars['Index']['scale'] = -1.0
        pars['Scale']['scale'] = 1.0
        pars['Index']['max'] = max(5.0, pars['Index']['value'] + 1.0)
        pars['Index']['min'] = min(0.0, pars['Index']['value'] - 1.0)
        pars['Prefactor'] = make_parameter_dict(pars['Prefactor'])
        pars['Scale'] = make_parameter_dict(pars['Scale'], True, False)
        pars['Index'] = make_parameter_dict(pars['Index'], False, False)

    elif spectrum_type == 'LogParabola':

        pars['norm'] = make_parameter_dict(pars['norm'], False, True)
        pars['Eb'] = make_parameter_dict(pars['Eb'], True, False)
        pars['alpha'] = make_parameter_dict(pars['alpha'], False, False)
        pars['beta'] = make_parameter_dict(pars['beta'], False, False)

    elif spectrum_type == 'PLSuperExpCutoff':

        pars['Index1']['value'] *= -1.0
        pars['Index1']['scale'] = -1.0
        pars['Index2']['scale'] = 1.0
        pars['Prefactor'] = make_parameter_dict(pars['Prefactor'])
        pars['Scale'] = make_parameter_dict(pars['Scale'], True, False)
        pars['Index1'] = make_parameter_dict(pars['Index1'], False, False)
        pars['Index2'] = make_parameter_dict(pars['Index2'], False, False)
        pars['Cutoff'] = make_parameter_dict(pars['Cutoff'], False, True)

    elif spectrum_type == 'PLSuperExpCutoff2':

        pars['Index1']['value'] *= -1.0
        pars['Index1']['scale'] = -1.0
        pars['Index2']['scale'] = 1.0
        pars['Prefactor'] = make_parameter_dict(pars['Prefactor'])
        pars['Scale'] = make_parameter_dict(pars['Scale'], True, False)
        pars['Index1'] = make_parameter_dict(pars['Index1'], False, False)
        pars['Index2'] = make_parameter_dict(pars['Index2'], False, False)
        pars['Expfactor'] = make_parameter_dict(pars['Expfactor'], False, True)
    else:
        raise Exception('Unsupported spectral type:' + spectrum_type)

    return pars