Exemple #1
0
def _progress(iterable, progress, n_to_run):
    """Add a progress bar to an iterable to be processed.

    Parameters
    ----------
    iterable : list or iterable
        Iterable object to potentially apply progress tracking to.
    progress : {None, 'tqdm', 'tqdm.notebook'}
        Which kind of progress bar to use. If None, no progress bar is used.
    n_to_run : int
        Number of jobs to complete.

    Returns
    -------
    pbar : iterable or tqdm object
        Iterable object, with tqdm progress functionality, if requested.

    Raises
    ------
    ValueError
        If the input for `progress` is not understood.

    Notes
    -----
    The explicit `n_to_run` input is required as tqdm requires this in the parallel case.
    The `tqdm` object that is potentially returned acts the same as the underlying iterable,
    with the addition of printing out progress every time items are requested.
    """

    # Check progress specifier is okay
    tqdm_options = ['tqdm', 'tqdm.notebook']
    if progress is not None and progress not in tqdm_options:
        raise ValueError("Progress bar option not understood.")

    # Set the display text for the progress bar
    pbar_desc = 'Running FOOOFGroup'

    # Use a tqdm, progress bar, if requested
    if progress:

        # Try loading the tqdm module
        tqdm = safe_import(progress)

        if not tqdm:

            # If tqdm isn't available, proceed without a progress bar
            print(("A progress bar requiring the 'tqdm' module was requested, "
                   "but 'tqdm' is not installed. \nProceeding without using a progress bar."))
            pbar = iterable

        else:

            # If tqdm loaded, apply the progress bar to the iterable
            pbar = tqdm.tqdm(iterable, desc=pbar_desc, total=n_to_run, dynamic_ncols=True)

    # If progress is None, return the original iterable without a progress bar applied
    else:
        pbar = iterable

    return pbar
Exemple #2
0
def _progress(iterable, verbose, n_to_run):
    """Add a progress bar to an iterable to be processed.

    Parameters
    ----------
    iterable : list or iterable
        Iterable object to potentially apply progress tracking to.
    verbose : 'tqdm', 'tqdm_notebook' or boolean
        Which type of verbosity to do.
    n_to_run : int
        Number of jobs to complete.

    Returns
    -------
    pbar : iterable or tqdm object
        Iterable object, with TQDM progress functionality, if requested.

    Notes
    -----
    The explicit n_to_run input is required as tqdm requires this in the parallel case.
    The `tqdm` object that is potentially returned acts the same as the underlying iterable,
    with the addition of printing out progress everytime items are requested.
    """

    # Check verbose specifier is okay
    tqdm_options = ['tqdm', 'tqdm_notebook']
    if not isinstance(verbose, bool) and not verbose in tqdm_options:
        #print('Verbose option not understood. Proceeding without any.')
        raise ValueError('Verbose option not understood.')

    if verbose:

        # Progress bar options, using tqdm
        if verbose in tqdm_options:

            # Get tqdm, and set which approach to use from tqdm
            #   Approch to use from tqdm should be what's specified in 'verbose'
            tqdm_mod = safe_import('tqdm')
            tqdm_type = verbose

            # Pulls out the specific tqdm approach to be used from the tqdm module, if available
            tqdm = getattr(tqdm_mod, tqdm_type) if tqdm_mod else None

            if not tqdm:
                print('tqdm requested but is not installed. Proceeding without progress bar.')
                pbar = iterable
            else:
                pbar = tqdm(iterable, desc='Running FOOOFGroup:', total=n_to_run,
                            dynamic_ncols=True)

        # If 'verbose' was just 'True', print out a marker of what is being run (no progress bar)
        else:
            print('Running FOOOFGroup across {} power spectra.'.format(n_to_run))
            pbar = iterable

    else:
        pbar = iterable

    return pbar
Exemple #3
0
def test_style_spectrum_plot(skip_if_no_mpl):

    # Create a dummy plot and style it
    from fooof.core.modutils import safe_import
    plt = safe_import('.pyplot', 'matplotlib')
    _, ax = plt.subplots()
    style_spectrum_plot(ax, False, False)

    # Check that axis labels are added - use as proxy that it ran correctly
    assert ax.xaxis.get_label().get_text()
    assert ax.yaxis.get_label().get_text()
Exemple #4
0
"""Plots for FOOOF object."""

import os
import numpy as np

from fooof.plts.templates import plot_spectrum
from fooof.core.funcs import gaussian_function
from fooof.core.modutils import safe_import, check_dependency

plt = safe_import('.pyplot', 'matplotlib')

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


@check_dependency(plt, 'matplotlib')
def plot_fm(fm,
            plt_log=False,
            save_fig=False,
            file_name='FOOOF_fit',
            file_path='',
            ax=None):
    """Plot the original power spectrum, and full model fit from FOOOF object.

    Parameters
    ----------
    fm : FOOOF() object
        FOOOF object, containing a power spectrum and (optionally) results from fitting.
    plt_log : boolean, optional
        Whether or not to plot the frequency axis in log space. default: False
    save_fig : boolean, optional
Exemple #5
0
def skip_if_no_mpl():
    if not safe_import('matplotlib'):
        pytest.skip('Matplotlib not availabe: skipping test.')
Exemple #6
0
"""Plots for FOOOFGroup object.

Notes
-----
This file contains plotting functions that take as input a FOOOFGroup() object.
"""

import os

from fooof.core.io import fname, fpath
from fooof.core.modutils import safe_import, check_dependency
from fooof.plts.templates import plot_scatter_1, plot_scatter_2, plot_hist

plt = safe_import('.pyplot', 'matplotlib')
gridspec = safe_import('.gridspec', 'matplotlib')

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

@check_dependency(plt, 'matplotlib')
def plot_fg(fg, save_fig=False, file_name='FOOOF_group_fit', file_path=None):
    """Plots a figure with subplots covering the group results from a FOOOFGroup object.

    Parameters
    ----------
    fg : FOOOFGroup() object
        FOOOFGroup object, containing results from fitting a group of power spectra.
    save_fig : boolean, optional, default: False
        Whether to save out a copy of the plot.
    file_name : str, optional
        Name to give the saved out file.
Exemple #7
0
import numpy as np

from fooof.core.utils import nearest_ind
from fooof.core.errors import NoModelError
from fooof.core.funcs import gaussian_function
from fooof.core.modutils import safe_import, check_dependency
from fooof.sim.gen import gen_aperiodic
from fooof.plts.utils import check_ax
from fooof.plts.spectra import plot_spectrum
from fooof.plts.settings import PLT_FIGSIZES, PLT_COLORS
from fooof.plts.style import check_n_style, style_spectrum_plot
from fooof.analysis.periodic import get_band_peak_fm
from fooof.utils.params import compute_knee_frequency, compute_fwhm

plt = safe_import('.pyplot', 'matplotlib')
mpatches = safe_import('.patches', 'matplotlib')

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


@check_dependency(plt, 'matplotlib')
def plot_annotated_peak_search(fm, plot_style=style_spectrum_plot):
    """Plot a series of plots illustrating the peak search from a flattened spectrum.

    Parameters
    ----------
    fm : FOOOF
        FOOOF object, with model fit, data and settings available.
    plot_style : callable, optional, default: style_spectrum_plot
Exemple #8
0
"""Tests for fooof.plts.utils."""

import os

from fooof.core.modutils import safe_import

from fooof.tests.tutils import plot_test
from fooof.tests.settings import TEST_PLOTS_PATH

from fooof.plts.utils import *

mpl = safe_import('matplotlib')

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

def test_check_ax(skip_if_no_mpl):

    figsize = [5., 5.]
    ax = check_ax(None, figsize=figsize)

    assert isinstance(ax, mpl.axes.Axes)
    assert figsize == [ax.get_figure().get_figwidth(),
                       ax.get_figure().get_figheight()]

def test_set_alpha(skip_if_no_mpl):

    alpha = set_alpha(100)
    assert isinstance(alpha, float)

@plot_test