specparam.SpectralTimeEventModel¶
- class specparam.SpectralTimeEventModel(*args, **kwargs)[source]¶
Model a set of event 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. Threshold is defined in relative units of the power spectrum (standard deviation).
- aperiodic_mode{‘fixed’, ‘knee’} or Mode
Which approach to take for fitting the aperiodic component.
- periodic_mode{‘gaussian’, ‘skewed_gaussian’, ‘cauchy’} or Mode
Which approach to take for fitting the periodic component.
- algorithm{‘spectral_fit’} or Algorithm
The fitting algorithm to use.
- algorithm_settingsdict
Setting for the algorithm.
- metricsMetrics or list of Metric or list or str
Metrics definition(s) to use to evaluate the model.
- bandsBands or dict or int or None, optional
Bands object with band definitions, or definition that can be turned into a Bands object.
- debugbool, optional, default: False
Whether to run in debug mode. If in debug, any errors encountered during fitting will raise an error.
- verbosebool, optional, default: True
Verbosity mode. If True, prints out warnings and general status updates.
- **model_kwargs
Additional model fitting related keyword arguments. These are passed into the algorithm object.
Notes
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 event object inherits from the time model, overwriting the data and results objects with versions for fitting models across events. Event related, temporally organized results are collected into the results.event_time_results attribute, which may include sub-selecting peaks per band (depending on settings). Note that the results.event_group_results attribute is also available, which maintains the full model results.
- Attributes:
- algorithmAlgorithm
Algorithm object with model fitting settings and procedures.
- modesModes
Modes object with fit mode definitions.
- dataData
Data object with spectral data and metadata.
- resultsResults
Results object with model fit results and metrics.
Methods
__init__(*args, **kwargs)Initialize event model object.
add_data(freqs, spectrograms[, freq_range, ...])Add data (frequencies and spectrograms) to the current object.
add_modes(aperiodic_mode, periodic_mode)Add modes definition to the object.
convert_results([bands])Convert results to be organized across time & events.
copy()Return a copy of the current object.
fit([freqs, spectrograms, freq_range, ...])Fit a set of events.
get_data([component, space])Get a data component.
get_group(event_inds, window_inds[, output_type])Get a new model object with the specified sub-selection of model fits.
get_metrics(category[, measure])Get requested metric(s) from the object.
get_model([event_ind, window_ind, regenerate])Get a model fit object for a specified index.
get_params(component[, field])Return model fit parameters for specified feature(s).
load(file_name[, file_path, convert_results])Load data from file(s).
plot([save_fig, file_name, file_path])Plot a figure with subplots visualizing the parameters from a SpectralTimeEventModel object.
print_report_issue([concise])Prints instructions on how to report bugs and/or problematic fits.
print_results([concise])Print out SpectralTimeEventModel results.
print_settings([description, concise])Print out the current settings.
report([freqs, spectrograms, freq_range, ...])Fit a set of events and display a report, with a plot and printed results.
save(file_name[, file_path, append, ...])Save out results and/or settings from event object.
save_model_report(event_index, window_index, ...)"Save out an individual model report for a specified model fit.
save_report(file_name[, file_path, add_settings])Generate and save out a PDF report for models of a set of events.
to_df([bands])Convert and extract the model results as a pandas object.
- add_data(freqs, spectrograms, freq_range=None, clear_results=True)[source]¶
Add data (frequencies and spectrograms) to the current object.
- Parameters:
- freqs1d array
Frequency values for the power spectra, in linear space.
- spectrograms3d array or list of 2d array
Matrix of power values, in linear space. If list of 2d arrays, each should be have the same shape of [n_freqs, n_time_windows]. If 3d array, should have shape [n_events, n_freqs, n_time_windows].
- 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, unless explicitly set not to.
- add_modes(aperiodic_mode, periodic_mode)¶
Add modes definition to the object.
- Parameters:
- aperiodic_modeMode or str
Mode for aperiodic component, or string specifying which mode to use.
- periodic_modeMode or str
Mode for periodic component, or string specifying which mode to use.
- convert_results(bands=None)[source]¶
Convert results to be organized across time & events.
- Parameters:
- bandsBands or dict or int, optional
How to organize peaks into bands. If Bands or dict, uses band definitions. If int, extracts the first ‘n’ peaks. If not provided, uses band definition available in object.
- copy()¶
Return a copy of the current object.
- fit(freqs=None, spectrograms=None, freq_range=None, bands=None, n_jobs=1, progress=None, prechecks=True, convert_results=True)[source]¶
Fit a set of events.
- Parameters:
- freqs1d array, optional
Frequency values for the power_spectra, in linear space.
- spectrograms3d array or list of 2d array
Matrix of power values, in linear space. If list of 2d arrays, each should be have the same shape of [n_freqs, n_time_windows]. If 3d array, should have shape [n_events, n_freqs, n_time_windows].
- freq_rangelist of [float, float], optional
Frequency range to fit the model to. If not provided, fits the entire given range.
- bandsBands or dict or int, optional
How to organize peaks into bands. If Bands or dict, uses band definitions. If int, extracts the first ‘n’ peaks.
- 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.
- prechecksbool, optional, default: True
Whether to run model fitting pre-checks.
- convert_resultsbool, optional, default: True
Whether to convert results per spectrogram window to be organized over time.
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(event_inds, window_inds, output_type='event')[source]¶
Get a new model object with the specified sub-selection of model fits.
- Parameters:
- event_inds, window_indsarray_like of int or array_like of bool or None
Indices to extract from the object, for event and time windows. If None, selects all available indices.
- output_type{‘time’, ‘group’}, optional
- Type of model object to extract:
‘event’ : SpectralTimeEventObject ‘time’ : SpectralTimeObject ‘group’ : SpectralGroupObject
- Returns:
- outputSpectralTimeEventModel
The requested selection of results data loaded into a new model object.
- get_metrics(category, measure=None)¶
Get requested metric(s) from the object.
- Parameters:
- Name of the specific measure(s) to return.
- Returns:
- metricsdict
Dictionary of requested metrics.
- get_model(event_ind=None, window_ind=None, regenerate=True)[source]¶
Get a model fit object for a specified index.
- Parameters:
- event_indint, optional
Index for which event to extract from.
- window_indint, optional
Index for which time window to extract from.
- regeneratebool, optional, default: False
Whether to regenerate the model fits for the requested model.
- Returns:
- modelSpectralModel
The data and fit results loaded into a model object.
- get_params(component, field=None)¶
Return model fit parameters for specified feature(s).
- Parameters:
- fieldstr or int, optional
Column name / index to extract from selected data, if requested. If str, should align with a parameter label for the component fit mode.
- Returns:
- outndarray
Requested data.
- Raises:
- NoModelError
If there are no model fit results available.
- ValueError
If the input for the field input is not understood.
Notes
When extracting peak parameters, an additional column is appended to the returned array, indicating the index that the peak came from.
- load(file_name, file_path=None, convert_results=True)[source]¶
Load data from file(s).
- Parameters:
- file_namestr
File(s) to load data from.
- file_pathstr, optional
Path to directory to load from. If None, loads from current directory.
- convert_resultsbool, optional, default: True
Whether to convert results to be organized over time.
- plot(save_fig=False, file_name=None, file_path=None, **plot_kwargs)[source]¶
Plot a figure with subplots visualizing the parameters from a SpectralTimeEventModel 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.
- static print_report_issue(concise=False)¶
Prints instructions on how to report bugs and/or problematic fits.
- Parameters:
- concisebool, optional, default: False
Whether to print the report in a concise mode, or not.
- print_results(concise=False)[source]¶
Print out SpectralTimeEventModel results.
- Parameters:
- concisebool, optional, default: False
Whether to print the report in a concise mode, or not.
- print_settings(description=False, concise=False)¶
Print out the current settings.
- Parameters:
- descriptionbool, optional, default: False
Whether to print out a description with current settings.
- concisebool, optional, default: False
Whether to print the report in a concise mode, or not.
- report(freqs=None, spectrograms=None, freq_range=None, bands=None, n_jobs=1, progress=None)[source]¶
Fit a set of events and display a report, with a plot and printed results.
- Parameters:
- freqs1d array, optional
Frequency values for the power_spectra, in linear space.
- spectrograms3d array or list of 2d array
Matrix of power values, in linear space. If a list of 2d arrays, each should be have the same shape of [n_freqs, n_time_windows]. If a 3d array, should have shape [n_events, n_freqs, n_time_windows].
- freq_rangelist of [float, float], optional
Frequency range to fit the model to. If not provided, fits the entire given range.
- bandsBands or dict or int, optional
How to organize peaks into bands. If Bands or dict, uses band definitions. If int, extracts the first ‘n’ peaks.
- 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)[source]¶
Save out results and/or settings from event object. Saves out to a JSON file.
- Parameters:
- file_namestr or FileObject
File to save data to.
- file_pathstr, 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_model_report(event_index, window_index, file_name, file_path=None, add_settings=True, **plot_kwargs)[source]¶
“Save out an individual model report for a specified model fit.
- Parameters:
- event_indint
Index for which event to extract from.
- window_indint
Index for which time window to extract from.
- 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.
- plot_kwargskeyword arguments
Keyword arguments to pass into the plot method.
- save_report(file_name, file_path=None, add_settings=True)[source]¶
Generate and save out a PDF report for models of a set of events.
- 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.
- to_df(bands=None)[source]¶
Convert and extract the model results as a pandas object.
- Parameters:
- bandsBands or dict or int, optional
How to organize peaks into bands. If Bands or dict, uses band definitions. If int, extracts the first ‘n’ peaks. If provided, re-extracts peak features; if not, converts from event_group_results.
- Returns:
- pd.DataFrame
Model results organized into a pandas object.