Create FOOOF (fitting oscillations and 1/f) report.

        Parameters
        ----------
        x : ndarray
            vector with frequencies
        y : ndarray
            vector with amplitudes
428309
def report_fooof(self, x, y, suffix):
        
        filename = splitext(self.filename)[0] + '_' + suffix + '_fooof.csv'

        freq = self.frequency
        freq_range = [freq['fo_min_freq'].get_value(),
                      freq['fo_max_freq'].get_value()]
        pk_thresh = freq['fo_pk_thresh'].get_value()
        pk_width = [freq['fo_pk_width_min'].get_value(),
                    freq['fo_pk_width_max'].get_value()]
        max_n_pk = freq['fo_max_n_pk'].get_value()
        min_pk_amp = freq['fo_min_pk_amp'].get_value()
        bg_mode = freq['fo_bg_mode'].get_value()

        if max_n_pk == 0:
            max_n_pk = inf

        if FOOOF is None:
            lg.warning('"fooof" package is required for this function, run "pip install fooof"')
            return

        fm = FOOOF(peak_width_limits=pk_width, max_n_peaks=max_n_pk,
                   min_peak_amplitude=min_pk_amp, peak_threshold=pk_thresh,
                   background_mode=bg_mode)
        fm.fit(x, y, freq_range)

        with open(filename, 'w', newline='') as f:
            lg.info('Writing to ' + str(filename))
            csv_file = writer(f)
            csv_file.writerow(['Wonambi v{}'.format(__version__)])
            csv_file.writerow(['FOOOF - POWER SPECTRUM MODEL'])
            csv_file.writerow('')
            csv_file.writerow(['The model was run on the frequency range '
                              '{} - {} Hz'.format(int(floor(fm.freq_range[0])),
                               int(ceil(fm.freq_range[1])))])
            csv_file.writerow(['Frequency Resolution is {:1.2f} Hz'.format(
                    fm.freq_res)])
            csv_file.writerow('')
            csv_file.writerow(['Background Parameters (offset, ' + \
                    ('knee, ' if fm.background_mode == 'knee' else '') + \
                    'slope): ' + ', '.join(['{:2.4f}'] * \
                    len(fm.background_params_)).format(
                            *fm.background_params_)])
            csv_file.writerow('')
            csv_file.writerow(['{} peaks were found:'.format(
                    len(fm.peak_params_))])
            csv_file.writerow('')
            csv_file.writerow(['Index', 'CF', 'Amp', 'BW'])

            for i, op in enumerate(fm.peak_params_):
                csv_file.writerow([i, op[0], op[1], op[2]])

            csv_file.writerow('')
            csv_file.writerow(['Goodness of fit metrics:'])
            csv_file.writerow(['R^2 of model fit is {:5.4f}'.format(
                    fm.r_squared_)])
            csv_file.writerow(['Root mean squared error is {:5.4f}'.format(
                    fm.error_)])
            csv_file.writerow('')
            csv_file.writerow(['Haller M, Donoghue T, Peterson E, Varma P, '
                               'Sebastian P, Gao R, Noto T, Knight RT, '
                               'Shestyuk A, Voytek B (2018) Parameterizing '
                               'Neural Power Spectra. bioRxiv, 299859. doi: '
                               'https://doi.org/10.1101/299859'])
912796
def _construct_X_M(self, omega, **kwargs):
        """"""
        X = self._construct_X(omega, weighted=True, **kwargs)
        M = np.dot(X.T, X)

        if getattr(self, 'regularization', None) is not None:
            diag = M.ravel(order='K')[::M.shape[0] + 1]
            if self.regularize_by_trace:
                diag += diag.sum() * np.asarray(self.regularization)
            else:
                diag += np.asarray(self.regularization)

        return X, M
1213909
def plot_xft(fignum, XF, T, e, b):
    
    plt.figure(num=fignum)
    plt.clf()
    if not isServer:
        plt.figtext(.02, .01, version_num)
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Susceptibility (m^3/kg)')
    k = 0
    F, X = [], []
    for xf in XF:
        X.append(xf[0])
        F.append(xf[1])
    plt.plot(F, X)
    plt.semilogx()
    plt.title(e + ': B = ' + '%8.1e' % (b) + ' T')

    plt.legend(['%i' % (int(T)) + ' K'])
1147302
def cnst_A0(self, X, Xf=None):
        
        """

        if Xf is None:
            Xf = sl.rfftn(X, axes=self.cri.axisN)
        return self.Wtv[..., np.newaxis] * sl.irfftn(
            self.Gf * Xf[..., np.newaxis], self.cri.Nv, axes=self.cri.axisN)
127473
def funcHrf(varNumVol, varTr):
    
    vecX = np.arange(0, varNumVol, 1)

    # Expected time of peak of HRF [s]:
    varHrfPeak = 6.0 / varTr
    # Expected time of undershoot of HRF [s]:
    varHrfUndr = 12.0 / varTr
    # Scaling factor undershoot (relative to peak):
    varSclUndr = 0.35

    # Gamma pdf for the peak
    vecHrfPeak = gamma.pdf(vecX, varHrfPeak)
    # Gamma pdf for the undershoot
    vecHrfUndr = gamma.pdf(vecX, varHrfUndr)
    # Combine them
    vecHrf = vecHrfPeak - varSclUndr * vecHrfUndr

    # Scale maximum of HRF to 1.0:
    vecHrf = np.divide(vecHrf, np.max(vecHrf))

    return vecHrf
212602
def xstep(self):
        
        """

        self.YU[:] = self.Y - self.U

        b = self.DSf + self.rho*sl.rfftn(self.YU, None, self.cri.axisN)
        if self.cri.Cd == 1:
            self.Xf[:] = sl.solvedbi_sm(self.Df, self.mu + self.rho,
                                        b, self.c, self.cri.axisM)
        else:
            self.Xf[:] = sl.solvemdbi_ism(self.Df, self.mu + self.rho, b,
                                          self.cri.axisM, self.cri.axisC)

        self.X = sl.irfftn(self.Xf, self.cri.Nv, self.cri.axisN)

        if self.opt['LinSolveCheck']:
            Dop = lambda x: sl.inner(self.Df, x, axis=self.cri.axisM)
            if self.cri.Cd == 1:
                DHop = lambda x: np.conj(self.Df) * x
            else:
                DHop = lambda x: sl.inner(np.conj(self.Df), x,
                                          axis=self.cri.axisC)
            ax = DHop(Dop(self.Xf)) + (self.mu + self.rho)*self.Xf
            self.xrrs = sl.rrs(ax, b)
        else:
            self.xrrs = None
257987
def fft_freqs(n_fft, fs):
    
    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)
1155113
public double Function2D(double x, double y) {
        double frequency = initFrequency;
        double amplitude = initAmplitude;
        double sum = 0;

        // octaves
        for (int i = 0; i < octaves; i++) {
            sum += SmoothedNoise(x * frequency, y * frequency) * amplitude;

            frequency *= 2;
            amplitude *= persistence;
        }
        return sum;
    }
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)
419558
def asfreq(obj, freq, method=None, how=None, normalize=False, fill_value=None):
    
    if isinstance(obj.index, PeriodIndex):
        if method is not None:
            raise NotImplementedError("'method' argument is not supported")

        if how is None:
            how = 'E'

        new_obj = obj.copy()
        new_obj.index = obj.index.asfreq(freq, how=how)

    elif len(obj.index) == 0:
        new_obj = obj.copy()
        new_obj.index = obj.index._shallow_copy(freq=to_offset(freq))

    else:
        dti = date_range(obj.index[0], obj.index[-1], freq=freq)
        dti.name = obj.index.name
        new_obj = obj.reindex(dti, method=method, fill_value=fill_value)
        if normalize:
            new_obj.index = new_obj.index.normalize()

    return new_obj
929767
def evaluate(self, x):
        """"""

        if not hasattr(self, '_coefficients'):
            # Graph Fourier transform -> modulation -> inverse GFT.
            c = self.G.igft(self._kernels.evaluate(self.G.e).squeeze())
            c = np.sqrt(self.G.n_vertices) * self.G.U * c[:, np.newaxis]
            self._coefficients = self.G.gft(c)

        shape = x.shape
        x = x.flatten()
        y = np.full((self.n_features_out, x.size), np.nan)
        for i in range(len(x)):
            query = self._coefficients[x[i] == self.G.e]
            if len(query) != 0:
                y[:, i] = query[0]
        return y.reshape((self.n_features_out,) + shape)
251489
def generate(self, x, **kwargs):
    
    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    asserts = []

    # If a data range was specified, check that the input was in that range
    if self.clip_min is not None:
      asserts.append(utils_tf.assert_greater_equal(x,
                                                   tf.cast(self.clip_min,
                                                           x.dtype)))

    if self.clip_max is not None:
      asserts.append(utils_tf.assert_less_equal(x,
                                                tf.cast(self.clip_max,
                                                        x.dtype)))

    # Initialize loop variables
    if self.rand_init:
      eta = tf.random_uniform(tf.shape(x),
                              tf.cast(-self.rand_minmax, x.dtype),
                              tf.cast(self.rand_minmax, x.dtype),
                              dtype=x.dtype)
    else:
      eta = tf.zeros(tf.shape(x))

    # Clip eta
    eta = clip_eta(eta, self.ord, self.eps)
    adv_x = x + eta
    if self.clip_min is not None or self.clip_max is not None:
      adv_x = utils_tf.clip_by_value(adv_x, self.clip_min, self.clip_max)

    if self.y_target is not None:
      y = self.y_target
      targeted = True
    elif self.y is not None:
      y = self.y
      targeted = False
    else:
      model_preds = self.model.get_probs(x)
      preds_max = tf.reduce_max(model_preds, 1, keepdims=True)
      y = tf.to_float(tf.equal(model_preds, preds_max))
      y = tf.stop_gradient(y)
      targeted = False
      del model_preds

    y_kwarg = 'y_target' if targeted else 'y'
    fgm_params = {
        'eps': self.eps_iter,
        y_kwarg: y,
        'ord': self.ord,
        'clip_min': self.clip_min,
        'clip_max': self.clip_max
    }
    if self.ord == 1:
      raise NotImplementedError("It's not clear that FGM is a good inner loop"
                                " step for PGD when ord=1, because ord=1 FGM "
                                " changes only one pixel at a time. We need "
                                " to rigorously test a strong ord=1 PGD "
                                "before enabling this feature.")

    # Use getattr() to avoid errors in eager execution attacks
    FGM = self.FGM_CLASS(
        self.model,
        sess=getattr(self, 'sess', None),
        dtypestr=self.dtypestr)

    def cond(i, _):
      """Iterate until requested number of iterations is completed"""
      return tf.less(i, self.nb_iter)

    def body(i, adv_x):
      """Do a projected gradient step"""
      adv_x = FGM.generate(adv_x, **fgm_params)

      # Clipping perturbation eta to self.ord norm ball
      eta = adv_x - x
      eta = clip_eta(eta, self.ord, self.eps)
      adv_x = x + eta

      # Redo the clipping.
      # FGM already did it, but subtracting and re-adding eta can add some
      # small numerical error.
      if self.clip_min is not None or self.clip_max is not None:
        adv_x = utils_tf.clip_by_value(adv_x, self.clip_min, self.clip_max)

      return i + 1, adv_x

    _, adv_x = tf.while_loop(cond, body, (tf.zeros([]), adv_x), back_prop=True,
                             maximum_iterations=self.nb_iter)

    # Asserts run only on CPU.
    # When multi-GPU eval code tries to force all PGD ops onto GPU, this
    # can cause an error.
    common_dtype = tf.float32
    asserts.append(utils_tf.assert_less_equal(tf.cast(self.eps_iter,
                                                      dtype=common_dtype),
                                              tf.cast(self.eps, dtype=common_dtype)))
    if self.ord == np.inf and self.clip_min is not None:
      # The 1e-6 is needed to compensate for numerical error.
      # Without the 1e-6 this fails when e.g. eps=.2, clip_min=.5,
      # clip_max=.7
      asserts.append(utils_tf.assert_less_equal(tf.cast(self.eps, x.dtype),
                                                1e-6 + tf.cast(self.clip_max,
                                                               x.dtype)
                                                - tf.cast(self.clip_min,
                                                          x.dtype)))

    if self.sanity_checks:
      with tf.control_dependencies(asserts):
        adv_x = tf.identity(adv_x)

    return adv_x
1045784
def create(lr, alpha, momentum=0, weight_decay=0, epsilon=1e-8):
    
    return RMSpropTFFactory(lr=lr, alpha=alpha, momentum=momentum, weight_decay=weight_decay, eps=float(epsilon))
1179720
def from_xarray(cls, arr: "xarray.Dataset") -> "Histogram1D":
        
        kwargs = {'frequencies': arr["frequencies"],
                  'binning': arr["bins"],
                  'errors2': arr["errors2"],
                  'overflow': arr.attrs["overflow"],
                  'underflow': arr.attrs["underflow"],
                  'keep_missed': arr.attrs["keep_missed"]}
        # TODO: Add stats
        return cls(**kwargs)
407639
def multiply_frequencies(signal, fs, frange, calibration_frequencies, attendB):
    """"""
    npts = len(signal)
    padto = 1 << (npts - 1).bit_length()

    X = np.fft.rfft(signal, n=padto)

    npts = padto
    f = np.arange((npts / 2) + 1) / (npts / fs)

    fidx_low = (np.abs(f - frange[0])).argmin()
    fidx_high = (np.abs(f - frange[1])).argmin()

    cal_func = interp1d(calibration_frequencies, attendB)
    roi = f[fidx_low:fidx_high]
    Hroi = cal_func(roi)
    H = np.zeros((len(X),))
    H[fidx_low:fidx_high] = Hroi

    H = smooth(H)
    # print 'H dB max', np.amax(H)

    H = 10 ** ((H).astype(float) / 20)
    # print 'H amp max', np.amax(H)

    # Xadjusted = X.copy()
    # Xadjusted[fidx_low:fidx_high] *= H
    # Xadjusted = smooth(Xadjusted)

    Xadjusted = X * H
    # print 'X max', np.amax(abs(X))
    # print 'Xadjusted max', np.amax(abs(Xadjusted))

    signal_calibrated = np.fft.irfft(Xadjusted)
    return signal_calibrated[:len(signal)]
1329675
def find_frequencies(data, freq=44100, bits=16):
    
    # Fast fourier transform
    n = len(data)
    p = _fft(data)
    uniquePts = numpy.ceil((n + 1) / 2.0)

    # Scale by the length (n) and square the value to get the amplitude
    p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]]
    p[0] = p[0] / 2
    if n % 2 == 0:
        p[-1] = p[-1] / 2

    # Generate the frequencies and zip with the amplitudes
    s = freq / float(n)
    freqArray = numpy.arange(0, uniquePts * s, s)
    return zip(freqArray, p)
1282811
def invcdf(x):
    """"""
    x_flat = np.ravel(x)
    x_trans = np.array([flib.ppnd16(y, 1) for y in x_flat])
    return np.reshape(x_trans, np.shape(x))