Exemple #1
0
    def _regenerate_model(self):
        """Regenerate model fit from parameters."""

        self._ap_fit = gen_aperiodic(self.freqs, self.aperiodic_params_)
        self._peak_fit = gen_peaks(self.freqs,
                                   np.ndarray.flatten(self._gaussian_params))
        self.fooofed_spectrum_ = self._peak_fit + self._ap_fit
Exemple #2
0
    def _robust_ap_fit(self, freqs, power_spectrum):
        """Fit the aperiodic component of the power spectrum robustly, ignoring outliers.

        Parameters
        ----------
        freqs : 1d array
            Frequency values for the power spectrum, in linear scale.
        power_spectrum : 1d array
            Power values, in log10 scale.

        Returns
        -------
        aperiodic_params : 1d array
            Parameter estimates for aperiodic fit.
        """

        # Do a quick, initial aperiodic fit
        popt = self._simple_ap_fit(freqs, power_spectrum)
        initial_fit = gen_aperiodic(freqs, popt)

        # Flatten power_spectrum based on initial aperiodic fit
        flatspec = power_spectrum - initial_fit

        # Flatten outliers - any points that drop below 0
        flatspec[flatspec < 0] = 0

        # Use percential threshold, in terms of # of points, to extract and re-fit
        perc_thresh = np.percentile(flatspec, self._ap_percentile_thresh)
        perc_mask = flatspec <= perc_thresh
        freqs_ignore = freqs[perc_mask]
        spectrum_ignore = power_spectrum[perc_mask]

        # Second aperiodic fit - using results of first fit as guess parameters
        #  See note in _simple_ap_fit about warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            aperiodic_params, _ = curve_fit(get_ap_func(self.aperiodic_mode),
                                            freqs_ignore,
                                            spectrum_ignore,
                                            p0=popt,
                                            maxfev=5000,
                                            bounds=self._ap_bounds)

        return aperiodic_params
Exemple #3
0
    def fit(self, freqs=None, power_spectrum=None, freq_range=None):
        """Fit the full power spectrum as a combination of periodic and aperiodic components.

        Parameters
        ----------
        freqs : 1d array, optional
            Frequency values for the power spectrum, in linear space.
        power_spectrum : 1d array, optional
            Power values, which must be input in linear space.
        freq_range : list of [float, float], optional
            Frequency range to restrict power spectrum to. If not provided, keeps the entire range.

        Notes
        -----
        Data is optional if data has been already been added to FOOOF object.
        """

        # If freqs & power_spectrum provided together, add data to object.
        if freqs is not None and power_spectrum is not None:
            self.add_data(freqs, power_spectrum, freq_range)
        # If power spectrum provided alone, add to object, and use existing frequency data
        #  Note: be careful passing in power_spectrum data like this:
        #    It assumes the power_spectrum is already logged, with correct freq_range.
        elif isinstance(power_spectrum, np.ndarray):
            self.power_spectrum = power_spectrum

        # Check that data is available
        if self.freqs is None or self.power_spectrum is None:
            raise ValueError('No data available to fit - can not proceed.')

        # Check and warn about width limits (if in verbose mode)
        if self.verbose:
            self._check_width_limits()

        # In rare cases, the model fails to fit. Therefore it's in a try/except
        #  Cause of failure: RuntimeError, failure to find parameters in curve_fit
        try:

            # Fit the aperiodic component
            self.aperiodic_params_ = self._robust_ap_fit(
                self.freqs, self.power_spectrum)
            self._ap_fit = gen_aperiodic(self.freqs, self.aperiodic_params_)

            # Flatten the power_spectrum using fit aperiodic fit
            self._spectrum_flat = self.power_spectrum - self._ap_fit

            # Find peaks, and fit them with gaussians
            self._gaussian_params = self._fit_peaks(
                np.copy(self._spectrum_flat))

            # Calculate the peak fit
            #  Note: if no peaks are found, this creates a flat (all zero) peak fit.
            self._peak_fit = gen_peaks(
                self.freqs, np.ndarray.flatten(self._gaussian_params))

            # Create peak-removed (but not flattened) power spectrum.
            self._spectrum_peak_rm = self.power_spectrum - self._peak_fit

            # Run final aperiodic fit on peak-removed power spectrum
            #   Note: This overwrites previous aperiodic fit
            self.aperiodic_params_ = self._simple_ap_fit(
                self.freqs, self._spectrum_peak_rm)
            self._ap_fit = gen_aperiodic(self.freqs, self.aperiodic_params_)

            # Create full power_spectrum model fit
            self.fooofed_spectrum_ = self._peak_fit + self._ap_fit

            # Convert gaussian definitions to peak parameters
            self.peak_params_ = self._create_peak_params(self._gaussian_params)

            # Calculate R^2 and error of the model fit.
            self._calc_r_squared()
            self._calc_rmse_error()

        # Catch failure, stemming from curve_fit process
        except RuntimeError:

            # Clear any interim model results that may have run
            #  Partial model results shouldn't be interpreted in light of overall failure
            self._reset_data_results(clear_freqs=False,
                                     clear_spectrum=False,
                                     clear_results=True)

            # Print out status
            if self.verbose:
                print('Model fitting was unsuccessful.')
Exemple #4
0
###################################################################################################
#
# The FOOOF object stores most of the intermediate steps internally.
#
# For this notebook, we will first fit the full model, as normal, but then step through,
# and visualize each step the algorithm takes to come to that final fit.
#

# Fit the FOOOF model
fm.fit(freqs, spectrum, [3, 40])

###################################################################################################

# Do an initial aperiodic signal fit - a robust fit, that excludes outliers
#  This recreates an initial fit that isn't ultimately stored in the FOOOF object)
init_ap_fit = gen_aperiodic(fm.freqs,
                            fm._robust_ap_fit(fm.freqs, fm.power_spectrum))

# Plot the initial aperiodic fit
_, ax = plt.subplots(figsize=(12, 10))
plot_spectrum(fm.freqs,
              fm.power_spectrum,
              plt_log,
              label='Original Power Spectrum',
              ax=ax)
plot_spectrum(fm.freqs,
              init_ap_fit,
              plt_log,
              label='Initial Aperiodic Fit',
              ax=ax)

###################################################################################################