예제 #1
0
파일: test_fit.py 프로젝트: vlitvak/fooof
def test_adds():
    """Tests methods that add data to FOOOF objects.

    Checks: add_data, add_settings, add_results.
    """

    # Note: uses it's own tfm, to not add stuff to the global one
    tfm = get_tfm()

    # Test adding data
    freqs, pows = np.array([1, 2, 3]), np.array([10, 10, 10])
    tfm.add_data(freqs, pows)
    assert np.all(tfm.freqs == freqs)
    assert np.all(tfm.power_spectrum == np.log10(pows))

    # Test adding settings
    fooof_settings = FOOOFSettings([1, 4], 6, 0, 2, 'fixed')
    tfm.add_settings(fooof_settings)
    for setting in get_description()['settings']:
        assert getattr(tfm, setting) == getattr(fooof_settings, setting)

    # Test adding meta data
    fooof_meta_data = FOOOFMetaData([3, 40], 0.5)
    tfm.add_meta_data(fooof_meta_data)
    for meta_dat in get_description()['meta_data']:
        assert getattr(tfm, meta_dat) == getattr(fooof_meta_data, meta_dat)

    # Test adding results
    fooof_results = FOOOFResults([1, 1], [10, 0.5, 0.5], 0.95, 0.02,
                                 [10, 0.5, 0.25])
    tfm.add_results(fooof_results)
    for setting in get_description()['results']:
        assert getattr(tfm, setting) == getattr(fooof_results,
                                                setting.strip('_'))
예제 #2
0
파일: test_fit.py 프로젝트: pinknoiz/fooof
def test_add_data():
    """Tests method to add data to FOOOF objects."""

    # This test uses it's own FOOOF object, to not add stuff to the global one
    tfm = get_tfm()

    # Test data for adding
    freqs, pows = np.array([1, 2, 3]), np.array([10, 10, 10])

    # Test adding data
    tfm.add_data(freqs, pows)
    assert tfm.has_data
    assert np.all(tfm.freqs == freqs)
    assert np.all(tfm.power_spectrum == np.log10(pows))

    # Test that prior data does not get cleared, when requesting not to clear
    tfm._reset_data_results(True, True, True)
    tfm.add_results(
        FOOOFResults([1, 1], [10, 0.5, 0.5], 0.95, 0.02, [10, 0.5, 0.25]))
    tfm.add_data(freqs, pows, clear_results=False)
    assert tfm.has_data
    assert tfm.has_model

    # Test that prior data does get cleared, when requesting not to clear
    tfm._reset_data_results(True, True, True)
    tfm.add_data(freqs, pows, clear_results=True)
    assert tfm.has_data
    assert not tfm.has_model
예제 #3
0
def avg_fg(fg, avg='mean'):
    """Average across a FOOOFGroup object."""

    if avg == 'mean':
        avg_func = np.nanmean
    elif avg == 'median':
        avg_func = np.nanmedian

    ap_params = avg_func(fg.get_all_data('aperiodic_params'), 0)

    peak_params = avg_func(
        get_band_peak_group(fg.get_all_data('peak_params'), [7, 14], len(fg)),
        0)
    peak_params = peak_params[np.newaxis, :]

    gaussian_params = avg_func(
        get_band_peak_group(fg.get_all_data('gaussian_params'), [7, 14],
                            len(fg)), 0)
    gaussian_params = gaussian_params[np.newaxis, :]

    r2 = avg_func(fg.get_all_data('r_squared'))
    error = avg_func(fg.get_all_data('error'))

    results = FOOOFResults(ap_params, peak_params, r2, error, gaussian_params)

    # Create the new FOOOF object, with settings, data info & results
    fm = FOOOF()
    fm.add_settings(fg.get_settings())
    fm.add_data_info(fg.get_data_info())
    fm.add_results(results)

    return fm
예제 #4
0
파일: fit.py 프로젝트: vlitvak/fooof
    def get_results(self):
        """Return model fit parameters and goodness of fit metrics in a FOOOFResults object.

        Returns
        -------
        FOOOFResults
            Object containing the FOOOF model fit results from the current FOOOF object.
        """

        return FOOOFResults(**{key.strip('_') : getattr(self, key) \
            for key in get_description()['results']})
예제 #5
0
def average_fg(fg, bands, avg_method='mean', generate_model=True):
    """Average across a FOOOFGroup object.

    Parameters
    ----------
    fg : FOOOFGroup
        A FOOOFGroup object with data to average across.
    bands : Bands
        Bands object that defines the frequency bands to collapse peaks across.
    avg : {'mean', 'median'}
        Averaging function to use.
    generate_model : bool, optional, default: True
        Whether to generate the model for the averaged parameters.

    Returns
    -------
    fm : FOOOF
        FOOOF object containing the average results from the FOOOFGroup input.
    """

    if avg_method not in ['mean', 'median']:
        raise ValueError('Requested average method not understood.')
    if not len(fg):
        raise ValueError(
            'Input FOOOFGroup has no fit results - can not proceed.')

    if avg_method == 'mean':
        avg_func = np.nanmean
    elif avg_method == 'median':
        avg_func = np.nanmedian

    ap_params = avg_func(fg.get_params('aperiodic_params'), 0)

    peak_params = np.array([avg_func(get_band_peak_fg(fg, band, 'peak_params'), 0) \
                            for label, band in bands])
    gaussian_params = np.array([avg_func(get_band_peak_fg(fg, band, 'gaussian_params'), 0) \
                                for label, band in bands])

    r2 = avg_func(fg.get_params('r_squared'))
    error = avg_func(fg.get_params('error'))

    results = FOOOFResults(ap_params, peak_params, r2, error, gaussian_params)

    # Create the new FOOOF object, with settings, data info & results
    fm = FOOOF()
    fm.add_settings(fg.get_settings())
    fm.add_meta_data(fg.get_meta_data())
    fm.add_results(results)

    # Generate the model from the average parameters
    if generate_model:
        fm._regenerate_model()

    return fm
예제 #6
0
def test_add_results():
    """Tests method to add results to FOOOF objects."""

    # This test uses it's own FOOOF object, to not add stuff to the global one
    tfm = get_tfm()

    # Test adding results
    fooof_results = FOOOFResults([1, 1], [10, 0.5, 0.5], 0.95, 0.02, [10, 0.5, 0.25])
    tfm.add_results(fooof_results)
    assert tfm.has_model
    for setting in OBJ_DESC['results']:
        assert getattr(tfm, setting) == getattr(fooof_results, setting.strip('_'))
예제 #7
0
def average_fg(fg, bands, avg_method='mean', regenerate=True):
    """Average across model fits in a FOOOFGroup object.

    Parameters
    ----------
    fg : FOOOFGroup
        Object with model fit results to average across.
    bands : Bands
        Bands object that defines the frequency bands to collapse peaks across.
    avg : {'mean', 'median'}
        Averaging function to use.
    regenerate : bool, optional, default: True
        Whether to regenerate the model for the averaged parameters.

    Returns
    -------
    fm : FOOOF
        Object containing the average model results.

    Raises
    ------
    ValueError
        If the requested averaging method is not understood.
    NoModelError
        If there are no model fit results available to average across.
    """

    if avg_method not in ['mean', 'median']:
        raise ValueError("Requested average method not understood.")
    if not fg.has_model:
        raise NoModelError(
            "No model fit results are available, can not proceed.")

    if avg_method == 'mean':
        avg_func = np.nanmean
    elif avg_method == 'median':
        avg_func = np.nanmedian

    # Aperiodic parameters: extract & average
    ap_params = avg_func(fg.get_params('aperiodic_params'), 0)

    # Periodic parameters: extract & average
    peak_params = []
    gauss_params = []

    for band_def in bands.definitions:

        peaks = get_band_peak_fg(fg, band_def, attribute='peak_params')
        gauss = get_band_peak_fg(fg, band_def, attribute='gaussian_params')

        # Check if there are any extracted peaks - if not, don't add
        #   Note that we only check peaks, but gauss should be the same
        if not np.all(np.isnan(peaks)):
            peak_params.append(avg_func(peaks, 0))
            gauss_params.append(avg_func(gauss, 0))

    peak_params = np.array(peak_params)
    gauss_params = np.array(gauss_params)

    # Goodness of fit measures: extract & average
    r2 = avg_func(fg.get_params('r_squared'))
    error = avg_func(fg.get_params('error'))

    # Collect all results together, to be added to FOOOF object
    results = FOOOFResults(ap_params, peak_params, r2, error, gauss_params)

    # Create the new FOOOF object, with settings, data info & results
    fm = FOOOF()
    fm.add_settings(fg.get_settings())
    fm.add_meta_data(fg.get_meta_data())
    fm.add_results(results)

    # Generate the average model from the parameters
    if regenerate:
        fm._regenerate_model()

    return fm