specparam.SpectralTimeModel

class specparam.SpectralTimeModel(*args, **kwargs)[source]

Model a spectrogram as a combination of aperiodic and periodic components.

WARNING: frequency and power values inputs must be in linear space.

Passing in logged frequencies and/or power spectra is not detected, and will silently produce incorrect results.

Parameters:
peak_width_limitstuple of (float, float), optional, default: (0.5, 12.0)

Limits on possible peak width, in Hz, as (lower_bound, upper_bound).

max_n_peaksint, optional, default: inf

Maximum number of peaks to fit.

min_peak_heightfloat, optional, default: 0

Absolute threshold for detecting peaks. This threshold is defined in absolute units of the power spectrum (log power).

peak_thresholdfloat, optional, default: 2.0

Relative threshold for detecting peaks. This threshold is defined in relative units of the power spectrum (standard deviation).

aperiodic_mode{‘fixed’, ‘knee’}

Which approach to take for fitting the aperiodic component.

verbosebool, optional, default: True

Verbosity mode. If True, prints out warnings and general status updates.

Notes

  • Commonly used abbreviations used in this module include: CF: center frequency, PW: power, BW: Bandwidth, AP: aperiodic

  • Input power spectra must be provided in linear scale. Internally they are stored in log10 scale, as this is what the model operates upon.

  • Input power spectra should be smooth, as overly noisy power spectra may lead to bad fits. For example, raw FFT inputs are not appropriate. Where possible and appropriate, use longer time segments for power spectrum calculation to get smoother power spectra, as this will give better model fits.

  • The gaussian params are those that define the gaussian of the fit, where as the peak params are a modified version, in which the CF of the peak is the mean of the gaussian, the PW of the peak is the height of the gaussian over and above the aperiodic component, and the BW of the peak, is 2*std of the gaussian (as ‘two sided’ bandwidth).

  • The time object inherits from the group model, which in turn inherits from the model object. As such it also has data attributes defined on the model object, as well as additional attributes that are added to the group object (see notes and attribute list in SpectralGroupModel).

  • Notably, while this object organizes the results into the time_results attribute, which may include sub-selecting peaks per band (depending on settings) the group_results attribute is also available, which maintains the full model results.

Attributes:
freqs1d array

Frequency values for the spectrogram.

spectrogram2d array

Data attribute view on the power spectra, transposed to spectrogram orientation.

freq_rangelist of [float, float]

Frequency range of the spectrogram, as [lowest_freq, highest_freq].

freq_resfloat

Frequency resolution of the spectrogram.

time_resultsdict

Results of the model fit across each time window.

__init__(*args, **kwargs)[source]

Initialize object with desired settings.

Methods

__init__(*args, **kwargs)

Initialize object with desired settings.

add_data(freqs, power_spectra[, freq_range, ...])

Add data (frequencies and power spectrum values) to the current object.

add_meta_data(meta_data)

Add data information into object from a SpectrumMetaData object.

add_results(results)

Add results data into object.

add_settings(settings)

Add settings into object from a ModelSettings object.

convert_results(peak_org)

Convert the model results to be organized across time windows.

copy()

Return a copy of the current object.

drop(inds)

Drop one or more model fit results from the object.

fit([freqs, spectrogram, freq_range, ...])

Fit a spectrogram.

get_data([component, space])

Get a data component.

get_group(inds[, output_type])

Get a new model object with the specified sub-selection of model fits.

get_meta_data()

Return data information from the current object.

get_model(ind[, regenerate])

Get a model fit object for a specified index.

get_params(name[, col])

Return model fit parameters for specified feature(s).

get_results()

Return the results run across a spectrogram.

get_run_modes()

Return run modes of the current object.

get_settings()

Return user defined settings of the current object.

load(file_name[, file_path, peak_org])

Load time data from file.

plot([plot_type, save_fig, file_name, file_path])

Plot a figure with subplots visualizing the parameters from a SpectralTimeModel object.

print_results([print_type, concise])

Print out SpectralTimeModel results.

report([freqs, spectrogram, freq_range, ...])

Fit a spectrogram and display a report, with a plot and printed results.

save(file_name[, file_path, append, ...])

Save out results and/or settings from group object.

save_report(file_name[, file_path, add_settings])

Generate and save out a PDF report for models of a spectrogram.

set_check_modes([check_freqs, check_data])

Set check modes, which controls if an error is raised based on check on the inputs.

set_debug_mode(debug)

Set debug mode, which controls if an error is raised if model fitting is unsuccessful.

set_run_modes(debug, check_freqs, check_data)

Simultaneously set all run modes.

to_df([peak_org])

Convert and extract the model results as a pandas object.

Attributes

has_data

Indicator for if the object contains data.

has_model

Indicator for if the object contains model fits.

n_null_

How many model fits are null.

n_peaks_

How many peaks were fit for each model.

n_time_windows

How many time windows are included in the model object.

null_inds_

The indices for model fits that are null.

spectrogram

Data attribute view on the power spectra, transposed to spectrogram orientation.

add_data(freqs, power_spectra, freq_range=None, clear_results=True)

Add data (frequencies and power spectrum values) to the current object.

Parameters:
freqs1d array

Frequency values for the power spectra, in linear space.

power_spectra2d array, shape=[n_power_spectra, n_freqs]

Matrix of power values, in linear space.

freq_rangelist of [float, float], optional

Frequency range to restrict power spectra to. If not provided, keeps the entire range.

clear_resultsbool, optional, default: True

Whether to clear prior results, if any are present in the object. This should only be set to False if data for the current results are being re-added.

Notes

If called on an object with existing data and/or results these will be cleared by this method call.

add_meta_data(meta_data)

Add data information into object from a SpectrumMetaData object.

Parameters:
meta_dataSpectrumMetaData

A meta data object containing meta data information.

add_results(results)

Add results data into object.

Parameters:
resultslist of list of FitResults

List of data objects containing the results from fitting power spectrum models.

add_settings(settings)

Add settings into object from a ModelSettings object.

Parameters:
settingsModelSettings

A data object containing the settings for a power spectrum model.

convert_results(peak_org)

Convert the model results to be organized across time windows.

Parameters:
peak_orgint or Bands

How to organize peaks. If int, extracts the first n peaks. If Bands, extracts peaks based on band definitions.

copy()

Return a copy of the current object.

drop(inds)

Drop one or more model fit results from the object.

Parameters:
indsint or array_like of int or array_like of bool

Indices to drop model fit results for.

Notes

This method sets the model fits as null, and preserves the shape of the model fits.

fit(freqs=None, spectrogram=None, freq_range=None, peak_org=None, n_jobs=1, progress=None)

Fit a spectrogram.

Parameters:
freqs1d array, optional

Frequency values for the spectrogram, in linear space.

spectrogram2d array, shape: [n_freqs, n_time_windows], optional

Spectrogram of power spectrum values, in linear space.

freq_rangelist of [float, float], optional

Frequency range to fit the model to. If not provided, fits the entire given range.

peak_orgint or Bands

How to organize peaks. If int, extracts the first n peaks. If Bands, extracts peaks based on band definitions.

n_jobsint, optional, default: 1

Number of jobs to run in parallel. 1 is no parallelization. -1 uses all available cores.

progress{None, ‘tqdm’, ‘tqdm.notebook’}, optional

Which kind of progress bar to use. If None, no progress bar is used.

Notes

Data is optional, if data has already been added to the object.

get_data(component='full', space='log')

Get a data component.

Parameters:
component{‘full’, ‘aperiodic’, ‘peak’}
Which data component to return.

‘full’ - full power spectrum ‘aperiodic’ - isolated aperiodic data component ‘peak’ - isolated peak data component

space{‘log’, ‘linear’}
Which space to return the data component in.

‘log’ - returns in log10 space. ‘linear’ - returns in linear space.

Returns:
output1d array

Specified data component, in specified spacing.

Notes

The ‘space’ parameter doesn’t just define the spacing of the data component values, but rather defines the space of the additive data definition such that power_spectrum = aperiodic_component + peak_component. With space set as ‘log’, this combination holds in log space. With space set as ‘linear’, this combination holds in linear space.

get_group(inds, output_type='time')

Get a new model object with the specified sub-selection of model fits.

Parameters:
indsarray_like of int or array_like of bool

Indices to extract from the object.

output_type{‘time’, ‘group’}, optional
Type of model object to extract:

‘time’ : SpectralTimeObject ‘group’ : SpectralGroupObject

Returns:
outputSpectralTimeModel or SpectralGroupModel

The requested selection of results data loaded into a new model object.

get_meta_data()

Return data information from the current object.

Returns:
SpectrumMetaData

Object containing meta data from the current object.

get_model(ind, regenerate=True)

Get a model fit object for a specified index.

Parameters:
indint

The index of the model from group_results to access.

regeneratebool, optional, default: False

Whether to regenerate the model fits for the requested model.

Returns:
modelSpectralModel

The FitResults data loaded into a model object.

get_params(name, col=None)

Return model fit parameters for specified feature(s).

Parameters:
name{‘aperiodic_params’, ‘peak_params’, ‘gaussian_params’, ‘error’, ‘r_squared’}

Name of the data field to extract across the group.

col{‘CF’, ‘PW’, ‘BW’, ‘offset’, ‘knee’, ‘exponent’} or int, optional

Column name / index to extract from selected data, if requested. Only used for name of {‘aperiodic_params’, ‘peak_params’, ‘gaussian_params’}.

Returns:
outndarray

Requested data.

Raises:
NoModelError

If there are no model fit results available.

ValueError

If the input for the col input is not understood.

Notes

When extracting peak information (‘peak_params’ or ‘gaussian_params’), an additional column is appended to the returned array, indicating the index that the peak came from.

get_results()

Return the results run across a spectrogram.

get_run_modes()

Return run modes of the current object.

Returns:
ModelRunModes

Object containing the run modes from the current object.

get_settings()

Return user defined settings of the current object.

Returns:
ModelSettings

Object containing the settings from the current object.

property has_data

Indicator for if the object contains data.

property has_model

Indicator for if the object contains model fits.

load(file_name, file_path=None, peak_org=None)

Load time data from file.

Parameters:
file_namestr

File to load data from.

file_pathstr, optional

Path to directory to load from. If None, loads from current directory.

peak_orgint or Bands

How to organize peaks. If int, extracts the first n peaks. If Bands, extracts peaks based on band definitions.

property n_null_

How many model fits are null.

property n_peaks_

How many peaks were fit for each model.

property n_time_windows

How many time windows are included in the model object.

property null_inds_

The indices for model fits that are null.

plot(plot_type='time', save_fig=False, file_name=None, file_path=None, **plot_kwargs)[source]

Plot a figure with subplots visualizing the parameters from a SpectralTimeModel object.

Parameters:
**plot_kwargs

Keyword arguments to apply to the plot.

Raises:
NoModelError

If the model object does not have model fit data available to plot.

print_results(print_type='time', concise=False)[source]

Print out SpectralTimeModel results.

Parameters:
print_type{‘time’, ‘group’}

Which format to print results out in.

concisebool, optional, default: False

Whether to print the report in a concise mode, or not.

report(freqs=None, spectrogram=None, freq_range=None, peak_org=None, report_type='time', n_jobs=1, progress=None)[source]

Fit a spectrogram and display a report, with a plot and printed results.

Parameters:
freqs1d array, optional

Frequency values for the spectrogram, in linear space.

spectrogram2d array, shape: [n_freqs, n_time_windows], optional

Spectrogram of power spectrum values, in linear space.

freq_rangelist of [float, float], optional

Frequency range to fit the model to. If not provided, fits the entire given range.

peak_orgint or Bands

How to organize peaks. If int, extracts the first n peaks. If Bands, extracts peaks based on band definitions.

n_jobsint, optional, default: 1

Number of jobs to run in parallel. 1 is no parallelization. -1 uses all available cores.

progress{None, ‘tqdm’, ‘tqdm.notebook’}, optional

Which kind of progress bar to use. If None, no progress bar is used.

Notes

Data is optional, if data has already been added to the object.

save(file_name, file_path=None, append=False, save_results=False, save_settings=False, save_data=False)

Save out results and/or settings from group object. Saves out to a JSON file.

Parameters:
file_namestr or FileObject

File to save data to.

file_pathPath or str, optional

Path to directory to load from. If None, saves to current directory.

appendbool, optional, default: False

Whether to append to an existing file, if available. This option is only valid (and only used) if ‘file_name’ is a str.

save_resultsbool, optional

Whether to save out model fit results.

save_settingsbool, optional

Whether to save out settings.

save_databool, optional

Whether to save out power spectra data.

Raises:
ValueError

If the data or save file specified are not understood.

save_report(file_name, file_path=None, add_settings=True)[source]

Generate and save out a PDF report for models of a spectrogram.

Parameters:
file_namestr

Name to give the saved out file.

file_pathstr, optional

Path to directory to save to. If None, saves to current directory.

add_settingsbool, optional, default: True

Whether to add a print out of the model settings to the end of the report.

set_check_modes(check_freqs=None, check_data=None)

Set check modes, which controls if an error is raised based on check on the inputs.

Parameters:
check_freqsbool, optional

Whether to run in check freqs mode, which checks the frequency data.

check_databool, optional

Whether to run in check data mode, which checks the power spectrum values data.

set_debug_mode(debug)

Set debug mode, which controls if an error is raised if model fitting is unsuccessful.

Parameters:
debugbool

Whether to run in debug mode.

set_run_modes(debug, check_freqs, check_data)

Simultaneously set all run modes.

Parameters:
debugbool

Whether to run in debug mode.

check_freqsbool

Whether to run in check freqs mode.

check_databool

Whether to run in check data mode.

property spectrogram

Data attribute view on the power spectra, transposed to spectrogram orientation.

to_df(peak_org=None)[source]

Convert and extract the model results as a pandas object.

Parameters:
peak_orgint or Bands, optional

How to organize peaks. If int, extracts the first n peaks. If Bands, extracts peaks based on band definitions. If provided, re-extracts peak features; if not provided, converts from time_results.

Returns:
pd.DataFrame

Model results organized into a pandas object.

Examples using specparam.SpectralTimeModel

06: Fitting Models over Time

06: Fitting Models over Time