API#
Technical reference for all functions, classes, and modules in HMP.
Models#
EventModelEventModel.EM()EventModel.distribution_pdf()EventModel.estim_probs()EventModel.fit()EventModel.gen_random_stages()EventModel.get_channel_time_parameters_expectation()EventModel.group_constructor()EventModel.scale_parameters()EventModel.transform()EventModel.xrchannel_parsEventModel.xrlikelihoodsEventModel.xrtime_parsEventModel.xrtime_pars_devEventModel.xrtraces
- Eliminative estimation method
- Cumulative estimation method
Transformer module#
Input/output module#
EEG/MEG Data Processing Utilities.
This module provides functions for reading, processing, and saving EEG/MEG data using MNE, xarray, and pandas. It supports reading raw or epoched data, event/response detection, reaction time trimming, epoch cropping, metadata handling, and conversion to xarray Datasets for fitting hmp models. Additional utilities are provided for saving/loading data and models, and exporting event probabilities.
- hmp.io.hmp_data_format(data, sfreq, tmin, tmax, events=None, participants=None, epochs=None, channel=None, metadata=None)#
Convert data to the expected xarray Dataset format.
This function reshapes a 3D or 4D matrix with dimensions (participant) * trial * channel * sample into an xarray Dataset.
- Parameters:
data (np.ndarray) – 4D or 3D matrix with dimensions (participant) * trial * channel * sample.
sfreq (float) – Sampling frequency of the data.
events (np.ndarray, optional) – Description for each epoch and participant that need to be stored (e.g. condition)
participants (list, optional) – List of participant indices if multiple ones are processed
epochs (list, optional) – List of epoch indices.
channel (list, optional) – List of channel indices.
metadata (DataFrame, optional) – Metadata associated with the epochs. Should be a pandas DataFrame.
- Returns:
An xarray Dataset containing the reshaped data, with appropriate dimensions and attributes.
- Return type:
xr.Dataset
- hmp.io.read_mne_data(pfiles=[], event_id=None, resp_id=None, data_format='raw', sfreq=None, subj_name=None, metadata=None, events_provided=None, verbose=True, tmin=-0.2, tmax=5, high_pass=None, low_pass=None, pick_channels='eeg', reference=None, bids_parameters={}, preprocessing_fn=None, dtype=<class 'numpy.float32'>)#
Read EEG/MEG data format (.fif or .bdf) using MNE’s integrated function.
Notes
Only EEG or MEG data are selected (other channel types are discarded).
All times are expressed in seconds.
If multiple files are provided in
pfiles, each participant’s data is read and processed sequentially.For non-epoched data: Reaction Times are only computed if the response trigger is in the epoching window (determined by
tminandtmax).
## Procedure:
If data is not already epoched:
The data is filtered using the specified
low_passandhigh_passparameters.If no events are provided, events are detected in the stimulus channel and only those with IDs in
event_idandresp_idare kept.Downsampling is performed if
sfreqis lower than the data’s sampling frequency.Epochs are created based on stimulus onsets (
event_id) and thetmin/tmaxwindow. Epochs with ‘BAD’ annotations are removed. Baseline correction is applied fromtminto stimulus onset (time 0).
- Parameters:
pfiles (str or list of str) – Path(s) to EEG files to read. Can be a single file path or a list of file paths. If empty list, assumes bids format
event_id (dict, optional) – Dictionary mapping condition names (keys) to event codes (values).
resp_id (dict, optional) – Dictionary mapping response names (keys) to event codes (values).
data_format (str, default=epochs) – What MNE compatible data type, can be ‘epochs’, ‘raw’ or ‘bids’.
sfreq (float, optional) – Desired sampling frequency for downsampling.
subj_name (list of str, optional) – List of subject identifiers. If not provided, defaults to “S0”, “S1”, etc.
metadata (list of pandas.DataFrame, optional) – List of metadata DataFrames corresponding to each participant.
events_provided (np.ndarray, optional) – Array with 3 columns: [sample of the event, initial value of the channel, event code]. Used if automated event detection is not suitable.
verbose (bool, default=True) – Whether to display MNE’s messages.
tmin (float, default=-0.2) – Start time (in seconds) relative to stimulus onset for epoching.
tmax (float, default=5) – End time (in seconds) relative to stimulus onset for epoching.
high_pass (float, optional) – High-pass filter cutoff frequency.
low_pass (float, optional) – Low-pass filter cutoff frequency.
pick_channels (str or list, default="eeg") – Channels to retain. Use “eeg”/”meg” to keep only EEG/MEG channels or provide a list of channel names.
reference (str, optional) – Reference to use for EEG data. If None, the existing reference is kept.
bids_parameters (dict, optional) – Bids root path (‘root’), datatype (‘datatype”) to analyze. A filter can also be applied to subjects, tasks and sessions
preprocessing_fn (callable, optional) – A user defined function preprocessing the raw data before epoching
dtype (np.DTypeLike) – Precision, use np.float32 or np.int64
- Returns:
epoch_data – An xarray Dataset containing the processed EEG/MEG data, events, channels, and participants. Metadata and epoch indices are preserved. The chosen sampling frequency is stored as an attribute.
- Return type:
xarray.Dataset
- hmp.io.read_raw_and_epoch(participant, subj_idx, event_id, resp_id, sfreq, metadata, events_provided, verbose, tmin, tmax, high_pass, low_pass, pick_channels, bids_parameters, preprocessing_fn)#
- hmp.io.save_eventprobs_csv(estimates, filename)#
Save event probability estimates to a CSV file.
- Parameters:
estimates (xarray.DataArray or xarray.Dataset) – The event probability estimates to save.
filename (str) – The path to the CSV file where the estimates will be saved.
Distributions module#
Classes for several probability distributions (Gamma, Lognormal, Wald, Weibull).
- class hmp.distributions.Gamma(shape=2)#
Bases:
objectDefine a gamma distribution.
This class represents a gamma distribution with a specified shape parameter.
- Parameters:
shape (float, optional) – The shape parameter of the gamma distribution (default is 2).
- shape#
The shape parameter of the gamma distribution.
- Type:
float
- pdf#
The probability density function from scipy.stats.gamma.
- Type:
function
- shift#
An integer by which to shift the distribution so that
(p(0) <- p(shift), p(1) <- p(1 + shift), ..., p(D) <- p(D + shift)). Default is 1- Type:
int
- scale_to_mean(scale: float) float#
Compute the mean of the distribution given a scale parameter.
- mean_to_scale(mean: float) float#
Compute the scale parameter of the distribution given a mean.
- mean_to_scale(mean)#
Compute the scale associated with a given mean and shape.
- Parameters:
mean (float) – The mean value of the distribution.
- Returns:
The calculated scale parameter.
- Return type:
float
- scale_to_mean(scale)#
Compute the mean associated with a given scale and shape parameters.
- Parameters:
scale (float) – The scale parameter of the distribution.
- Returns:
The calculated mean value.
- Return type:
float
- class hmp.distributions.Lognormal(shape)#
Bases:
objectDefine a Lognormal distribution.
- Parameters:
shape (float) – The shape parameter of the lognormal distribution.
- shape#
The shape parameter of the distribution.
- Type:
float
- pdf#
The probability density function from scipy.stats.lognorm.
- Type:
function
- shift#
An integer by which to shift the distribution so that
(p(0) <- p(shift), p(1) <- p(1 + shift), ..., p(D) <- p(D + shift)). Default is 1- Type:
int
- scale_to_mean(scale: float) float#
Compute the mean of the distribution given a scale parameter.
- mean_to_scale(mean: float) float#
Compute the scale parameter of the distribution given a mean.
- mean_to_scale(mean)#
Compute the scale associated with a given mean and shape.
- Parameters:
mean (float) – The mean value of the distribution.
- Returns:
The calculated scale parameter.
- Return type:
float
- scale_to_mean(scale)#
Compute the mean associated with a given scale and shape parameters.
- Parameters:
scale (float) – The scale parameter of the distribution.
- Returns:
The calculated mean value.
- Return type:
float
- class hmp.distributions.Wald(shape)#
Bases:
objectDefine a Wald distribution (aka inverse Gaussian).
- Parameters:
shape (float) – The shape parameter of the Wald distribution.
- shape#
The shape parameter of the distribution.
- Type:
float
- pdf#
The probability density function from scipy.stats.invgauss.
- Type:
function
- shift#
An integer by which to shift the distribution so that
(p(0) <- p(shift), p(1) <- p(1 + shift), ..., p(D) <- p(D + shift)). Default is 1- Type:
int
- scale_to_mean(scale: float) float#
Compute the mean of the distribution given a scale parameter.
- mean_to_scale(mean: float) float#
Compute the scale parameter of the distribution given a mean.
- mean_to_scale(mean)#
Compute the scale associated with a given mean and shape.
- Parameters:
mean (float) – The mean value of the distribution.
- Returns:
The calculated scale parameter.
- Return type:
float
- scale_to_mean(scale)#
Compute the mean associated with a given scale and shape parameters.
- Parameters:
scale (float) – The scale parameter of the distribution.
- Returns:
The calculated mean value.
- Return type:
float
- class hmp.distributions.Weibull(shape)#
Bases:
objectDefine a Weibull distribution.
- Parameters:
shape (float) – The shape parameter of the Wald distribution.
- shape#
The shape parameter of the distribution.
- Type:
float
- pdf#
The probability density function from scipy.stats.weibull_min.
- Type:
function
- shift#
An integer by which to shift the distribution so that
(p(0) <- p(shift), p(1) <- p(1 + shift), ..., p(D) <- p(D + shift)). Default is 0- Type:
int
- scale_to_mean(scale: float) float#
Compute the mean of the distribution given a scale parameter.
- mean_to_scale(mean: float) float#
Compute the scale parameter of the distribution given a mean.
- mean_to_scale(mean)#
Compute the scale associated with a given mean and shape.
- Parameters:
mean (float) – The mean value of the distribution.
- Returns:
The calculated scale parameter.
- Return type:
float
- scale_to_mean(scale)#
Compute the mean associated with a given scale and shape parameters.
- Parameters:
scale (float) – The scale parameter of the distribution.
- Returns:
The calculated mean value.
- Return type:
float
Patterns module#
Classes for generating and representing templates for HMP event detection.
including a half-sine wave template (HalfSine) and an arbitrary waveform template (Arbitrary).
Classes#
- HalfSine
Generates a normalized half-sine wave template for use in signal processing or event detection.
- Arbitrary
Allows the use of any arbitrary pattern as a template.
Both classes provide methods to create expected templates based on sampling frequency and other parameters, and store relevant metadata such as template width and censoring location for model fitting procedures.
- class hmp.patterns.Arbitrary(sfreq, width, location, template)#
Bases:
objectRepresents an arbitrary template.
- sfreq#
Sampling frequency in Hz.
- Type:
float
- width#
Number of samples in the template.
- Type:
int
- location#
How much samples should be censored in the EM() step of model fitting.
- Type:
int
- template#
The arbitrary template.
- Type:
np.ndarray
- classmethod create_expected(sfreq, template, location=None)#
Create an Arbitrary instance with the expected parameters.
- Parameters:
sfreq (float) – Sampling frequency in Hz.
template (np.ndarray) – The arbitrary waveform template.
location (float, optional) – How much milliseconds should be censored in the EM() step of model fitting. Default is width of the event. Shorter values than width allow overlap of neighboring events but might result in the same event being duplicated in several events. Larger values will prevent duplication at the risk of missing neighboring events Censoring is done on samples lower or equal to the location, thus requesting 50ms at 1000Hz will censor up to 50ms
- Returns:
An instance of the Arbitrary class.
- Return type:
-
location:
int#
-
sfreq:
float#
-
template:
ndarray#
-
width:
int#
- class hmp.patterns.HalfSine(sfreq, width, location, template)#
Bases:
objectRepresents a half-sine wave template.
- sfreq#
Sampling frequency in Hz.
- Type:
float
- width#
Number of samples in the half-sine wave.
- Type:
int
- location#
Number of samples censored in the EM() step of model fitting.
- Type:
int
- template#
The half-sine wave template.
- Type:
np.ndarray
- classmethod create_expected(sfreq, width=50, location=None)#
Create a HalfSine instance with the expected parameters.
- Parameters:
sfreq (float) – Sampling frequency of the modelled signal in Hz.
width (float, optional) – Width of the half-sine wave in milliseconds, by default 50 ms (10H). Controls for the precision of the estimate. Shorter values will model narrower half-sines (i.e. higher frequencies), higher values will model wider events (i.e. lower frequencies)
location (float, optional) – How much milliseconds should be censored in the EM() step of model fitting. Default is width of the event. Shorter values than width allow overlap of neighboring events but might result in the same event being duplicated in several events. Larger values will prevent duplication at the risk of missing neighboring events Censoring is done on samples lower or equal to the location, thus requesting 50ms at 1000Hz will censor up to 50ms
- Returns:
An instance of the HalfSine class.
- Return type:
-
location:
int#
-
sfreq:
float#
-
template:
ndarray#
-
width:
int#
TrialData module#
Builds the data to be used in HMP model estimation.
- class hmp.trialdata.TrialData(durations, starts, ends, sfreq, offset, cross_corr, pattern)#
Bases:
objectA class building trial data and its associated properties to use in the estimations.
- durations#
Durations of each trial with corresponding trial coordinates.
- Type:
xr.DataArray
- starts#
Array of start indices for each trial (usually stimulus onsets position in samples).
- Type:
np.ndarray
- ends#
Array of end indices for each trial (usually response onsets position in samples)
- Type:
np.ndarray
- sfreq#
Sampling frequency of the data.
- Type:
float
- offset#
Offset applied to the data.
- Type:
int
- pattern#
Values for the pattern used for the cross-correlation.
- Type:
np.ndarray
- cross_corr#
Cross-correlation values between the data and a given pattern.
- Type:
np.ndarray
-
cross_corr:
ndarray#
-
durations:
DataArray#
-
ends:
ndarray#
- classmethod from_transformer(transformed, pattern, dtype=<class 'numpy.float32'>)#
Create a TrialData instance from transformed data and a given pattern.
- Parameters:
transformed (BaseTransfromer or xr.DataArray) – The transformed object or xarray DataArray containing the transformed data.
pattern (np.ndarray) – The pattern to use for cross-correlation computation.
dtype (np.DTypeLike) – Precision, use np.float32 or np.int64
- Returns:
An instance of TrialData with computed durations, cross-correlation, and metadata.
- Return type:
-
offset:
int#
-
pattern:
ndarray#
-
sfreq:
float#
-
starts:
ndarray#
- hmp.trialdata.cross_correlation(data, starts, ends, pattern, dtype)#
Compute the cross-correlation between the data and a given pattern.
This function calculates the correlation of each sample and the next x samples (depending on sampling frequency and event size) with a given pattern.
- Parameters:
data (np.ndarray) – 2D ndarray with shape (n_samples, n_components).
n_dims (int) – Number of dimensions (components) in the data.
starts (np.ndarray) – Array of start indices for each trial.
ends (np.ndarray) – Array of end indices for each trial.
pattern (np.ndarray) – 1D array representing the pattern to correlate with.
dtype (np.DTypeLike) – Precision, use np.float32 or np.int64
- Returns:
A 2D ndarray with shape (n_samples, n_components) where each cell contains the correlation value with the given pattern.
- Return type:
np.ndarray
Visualization module#
Module containing functions to visualize the results of the HMP model.
- hmp.visu.erp_data(epoched_data, times, channel, n_samples=None, pad=1)#
Create a data array compatible with the plot ERP function.
Optionnally this function can resample the epochs to fit some provided times (e.g. onset of the events).
- Parameters:
epoched_data (xr.Dataset) – Epoched physiological data with dims ‘participant’X ‘epochs’ X ‘channels’X ‘sample’
times (xr.Dataset) – Times between wich to extract or resample the data with dims ‘trial’ X ‘event’
channel (str) – For which channel to extract the data
n_samples (int) – How many sample to resample on if any
pad (int) – padding added to the beginning and the end of the signal
- Returns:
data – array containing the extracted times for each epoch and stage with format epochs X events X sample.
- Return type:
nd.array
- hmp.visu.plot_components_sensor(weights, positions, cmap='Spectral_r')#
Visualize the topomap of the HMP principal components.
- Parameters:
weights (xr.DataArray) – DataArray containing the weights of the principal components. Should have a ‘component’ dimension.
positions (np.ndarray | mne.Info) – Array of x and y positions to plot channels on a head model, or an MNE Info object containing channel location information.
cmap (str, optional) – Colormap to use for the topomap, by default “Spectral_r”.
- Return type:
None
- hmp.visu.plot_erp(times, data, color='k', ax=None, minmax_lines=None, upsample=1, bootstrap=None, label=None)#
Plot the ERP based on the times extracted by HMP.
Either around an event or just stimulus and response and the data extracted from
`erp_data`.- Parameters:
times (xr.Dataset) – Times between wich to extract or resample the data with dims
data (nd.array) – numpy array from the erp_data functino
color (str) – color for the lines
ax (matplotlib.pyplot) – ax on which to draw
minmax_lines (tuple) – Min and max arguments for the vertical lines on the plot
upsample (float) – Upsampling factor for the times
bootstrap (int) – how many bootstrap draw to perform
- hmp.visu.plot_latencies(estimates, init=None, labels=[], colors=['cornflowerblue', 'indianred', 'orange', 'darkblue', 'darkgreen', 'gold'], figsize=False, errs=None, kind='bar', legend=False, max_time=None, as_time=False)#
Plot the average of stage latencies with choosen errors bars.
- Parameters:
estimates (hmp results object) – hmp results object
event_width (float) –
Display size of the event in time unit given sampling frequency.
If drawing a fitted object using hmp you can provide the event_width_sample of fitted hmp (e.g. init.event_width_sample)
labels (tuples | list) – labels to draw on the y axis
colors (ndarray) – array of colors for the different stages
figsize (list | tuple | ndarray) – Length and heigth of the matplotlib plot
errs (str) – Whether to display no error bars (None), standard deviation (‘std’), or standard error (‘se’)
times_to_display (ndarray) – Times to display (e.g. Reaction time or any other relevant time) in the time unit of the fitted data
max_time (float) – limit of the x (time) axe
kind (str) – bar or point
as_time (bool) – if true, plot time (ms) instead of sample.
- hmp.visu.plot_loocv(loocv_estimates, pvals=True, test='t-test', figsize=(16, 5), indiv=True, ax=None, mean=False, additional_points=None)#
Plot the LOOCV results.
- Parameters:
loocv_estimates (ndarray or xarra.DataArray) – results from a call to hmp.utils.loocv()
pvals (bool) – Whether to display the pvalue with the associated test
test (str) – which statistical test to compute for the difference in LOOCV-likelihood (one sample t-test or sign test)
figsize (list | tuple | ndarray) – Length and heigth of the matplotlib plot
indiv (bool) – Whether to plot individual lines
ax (matplotlib.pyplot.ax) – Matplotlib object on which to draw the plot, can be useful if you want to control specific aspects of the plots outside of this function
mean (bool) – Whether to plot the mean
additional_points – Additional likelihood points to be plotted. Should be provided as a list of tuples containing the x coordinate and loocv estimates with a single event, e.g. [(5,estimates)].
- Returns:
ax – if ax was specified otherwise returns the plot
- Return type:
matplotlib.pyplot.ax
- hmp.visu.plot_topo_timecourse(epoch_data, estimates, channel_position, figsize=None, dpi=100, magnify=1, times_to_display='all', cmap='Spectral_r', ylabels=[], xlabel=None, max_time=None, vmin=None, vmax=None, title=False, ax=None, sensors=False, contours=6, event_lines='tab:orange', colorbar=True, topo_size_scaling=False, as_time=False, estimate_method=None, combined=False, group_plot=False)#
Plot the event topographies at the average time of the onset of the next stage.
- Parameters:
epoch_data (xr.DataArray) – The original EEG data in HMP format.
estimates (xr.DataArray) – The result from a fitted HMP model.
channel_position (np.ndarray) – Either a 2D array with dimensions (channel, [x, y]) storing channel locations in meters or an MNE info object containing digit points for channel locations.
figsize (tuple | list | np.ndarray, optional) – Length and height of the matplotlib plot.
dpi (int, optional) – DPI of the matplotlib plot.
magnify (float, optional) – How much the events should be enlarged. Useful to zoom on topographies. Providing any value other than 1 will change the displayed size of the event.
times_to_display (str | np.ndarray, optional) – Times to display (e.g., reaction time or any other relevant time) in the time unit of the fitted data. If ‘all’, plots the times of all events.
cmap (str, optional) – Colormap of matplotlib, used to change the colors on topographies
ylabels (dict | list, optional) – Dictionary with {label_name: label_values}, e.g., {‘Condition’: [‘Speed’, ‘Accuracy’]}.
xlabel (str, optional) – Label of the x-axis. Default is None, which gives “Time (sample)” or “Time (ms)” if as_time is True.
max_time (float, optional) – Limit of the x (time) axis.
vmin (float, optional) – Minimum value for the colormap. If not explicitly set, uses the minimum across all topographies.
vmax (float, optional) – Maximum value for the colormap. If not explicitly set, uses the maximum across all topographies.
title (str | bool, optional) – Title of the plot. If False, no title is displayed.
ax (plt.Axes, optional) – Matplotlib Axes object on which to draw the plot. Useful for controlling specific aspects of the plots outside of this function.
sensors (bool, optional) – Whether to plot the sensors on the topographies.
contours (int | np.ndarray, optional) – The number of contour lines to draw.
event_lines (str | bool, optional) – Whether to plot lines and shading to indicate the moment of the event. If True, uses “tab:orange”. If set as a color, uses the specified color.
colorbar (bool, optional) – Whether a colorbar is plotted.
topo_size_scaling (bool, optional) – Whether to scale the size of the topographies with the event size. If True, the size of topographies depends on the total plotted time interval. If False, it is only dependent on magnify.
as_time (bool, optional) – If True, plot time in milliseconds instead of samples. Ignored if times are provided as an array.
linecolors (str, optional) – Color of the lines in the plot.
estimate_method (str, optional) – ‘max’ or ‘mean’. Either take the max probability of each event on each trial, or the weighted average.
combined (bool, optional) – Whether to combine groups by averaging across them (True) or plot each group (False, default).
- Returns:
The matplotlib Axes object containing the plot.
- Return type:
plt.Axes
Utils module#
Functions to transform the input data and the estimates.
- hmp.utils.centered_activity(data, times, channel, event, n_samples=None, cut_after_event=0, baseline=0, cut_before_event=0, event_width=0)#
Parse the single trial signal of channel in a given number of sample around one event.
- Parameters:
data (xr.Dataset) – HMP data (untransformed but with trial and participant stacked)
times (xr.DataArray) – Onset times in sample as computed using event_times()
channel (list) – channel to pick for the parsing of the signal, must be a list even if only one
event (int) – Which event is used to parse the signal
n_samples (int) – How many sample to record after the event (default = maximum duration between event and the consecutive event)
cut_after_event (int) – Which event after
`event`to cut sample off, if 1 (Default) cut at the next eventbaseline (int) – How much sample should be kept before the event
cut_before_event (int) – At which previous event to cut sample from,
`baseline`if 0 (Default), no effect if baseline = 0event_width (int) – Duration of the fitted events, used when cut_before_event is True
- Returns:
centered_data – Xarray dataset with electrode value (data) and trial event time (time) and with trial * sample dimension
- Return type:
xr.Dataset
- hmp.utils.compute_csd(epoch_data, info)#
Compute laplacian using MNE’s function.
- Parameters:
epoch_data (xr.Dataset) – Data read through the HMP IO module
info (Info) – Info object from MNE
- Returns:
epoch_data (xr.Dataset) – Updated dataset with CSD values
eeg_info (Info) – Updated info ubject with correct units given CSD transform
- hmp.utils.condition_selection(transformed, condition_string, variable='event', method='equal')#
Select a subset from transformed_data.
The function selects epochs for which ‘condition_string’ is in ‘variable’ based on ‘method’.
- Parameters:
transformed (xr.Dataset) – transformed EEG data for hmp from the hmp.preprocessing classes
condition_string (str | num) – condition indicator for selection
variable (str) – variable present in transformed.data that is used for condition selection
method (str) – ‘equal’ selects equal trial, ‘contains’ selects trial in which conditions_string appears in variable
- Returns:
data – Subset of transformed_data.
- Return type:
xr.Dataset
- hmp.utils.condition_selection_epoch(epoch_data, condition_string, variable='event', method='equal')#
Select a subset from epoch_data.
The function selects epochs for which ‘condition_string’ is in ‘variable’ based on ‘method’.
- Parameters:
epoch_data (xr.Dataset) – Epoched EEG data for hmp
condition_string (str | num) – condition indicator for selection
variable (str) – variable present in transformed_data that is used for condition selection
method (str) – ‘equal’ selects equal trial, ‘contains’ selects trial in which conditions_string appears in variable
- Returns:
data – Subset of transformed_data.
- Return type:
xr.Dataset
- hmp.utils.event_channels(epoch_data, estimates, mean=True, peak=True, estimate_method='max', template=None)#
Compute topographies for each trial.
- Parameters:
epoch_data (xr.Dataset) – Epoched data
estimates (xr.Dataset) – estimated model parameters and event probabilities
mean (bool) – if True mean will be computed instead of single-trial channel activities
peak (bool) – if true, return topography at peak of the event. If false, return topographies weighted by a normalized template.
estimate_method (string) – ‘max’ or ‘mean’, either take the max probability of each event on each trial, or the weighted average.
template (np.array) – Expected shape of the event, typically the template attribute from hmp.patterns
- Returns:
- event_values: xr.DataArray
array containing the values of each electrode at the most likely transition time contains nans for missing events
- hmp.utils.event_times(estimates, duration=False, mean=False, add_rt=False, as_time=False, errorbars=None, estimate_method='max', add_stim=False, remove_offset=False)#
Compute the likeliest peak times for each event.
- Parameters:
estimates (xr.Dataset) – Estimated instance of an HMP model
duration (bool) – Whether to compute peak location (False) or inter-peak duration (True)
mean (bool) – Whether to compute the mean (True) or return the single trial estimates Note that mean and errorbars cannot both be true.
add_rt (bool) – whether to append the last stage up to the RT
as_time (bool) – if true, return time (ms) instead of sample
errorbars (str) – calculate 95% confidence interval (‘ci’), standard deviation (‘std’), standard error (‘se’) on the times or durations, or None. Note that mean and errorbars cannot both be true.
estimate_method (string) – ‘max’ or ‘mean’, either take the max probability of each event on each trial, or the weighted average.
add_stim (bool) – Adding stimulus as the first event (True) or let the first estimated HMP event be the first one (False, default)
remove_offset (bool) – Whether to remove the eventual offset added to the reaction time
- Returns:
times – Transition event peak or stage duration with trial*event dimensions or only event dimension if mean = True contains nans for missing stages.
- Return type:
xr.DataArray
- hmp.utils.participant_selection(transformed, participant)#
Select a participant from transformed_data.
- Parameters:
transformed (xr.Dataset or hmp.transformers) – transformed EEG data for hmp
participant (str | num) – Name of the participant
- Returns:
data – Subset of transformed_data.
- Return type:
xr.Dataset
Simulations module#
Generating synthetic data to test HMP.
- hmp.simulations.available_sources()#
List available sources for sample subject in MNE.
- hmp.simulations.classification_true(true_topologies, test_topologies)#
Classifies events as belonging to one of the true events.
- Parameters:
true_topologies (xarray.DataArray) – Topologies for the true events simulated, obtained from utils.event_channels(epoch_data, test_estimates, mean=True).
test_topologies (xarray.DataArray) – Topologies for the events found in the estimation procedure, obtained from utils.event_channels(epoch_data, true_estimates, true_init, mean=True).
- Return type:
tuple[ndarray,ndarray]- Returns:
idx_true_positive (np.ndarray) – Indices of the true events found in the test estimation.
corresp_true_idx (np.ndarray) – Indices in the test estimate that correspond to the true events.
- hmp.simulations.demo()#
Create example data for the tutorials.
- hmp.simulations.event_shape(event_width, event_width_samples, steps)#
Compute the template of a half-sine with given frequency f and sampling frequency.
- hmp.simulations.positions()#
Recovering position of the simulated electrodes.
- hmp.simulations.sim_info()#
Recovering MNE’s info file for simulated data.
- hmp.simulations.simulate(sources, n_trials, n_jobs, file, relations=None, data_type='eeg', n_subj=1, path='.', overwrite=False, verbose=False, noise=True, times=None, seed=None, sfreq=100.0, save_snr=False, save_noiseless=False, event_length_samples=None, proportions=None)#
Simulate n_trials of EEG and/or MEG using MNE’s tools based on the specified sources.
- Parameters:
sources (list) –
2D or 3D list with dimensions (n_subjects * ) sources * source_parameters. Source parameters should contain: - the name of the source (see the output of available_sources()). - the duration of the event (in frequency, usually 10Hz). - the amplitude or strength of the signal from the source, expressed in nAM (e.g., 1e-8 ). - the duration of the preceding stage as a scipy.stats distribution
(e.g., scipy.stats.gamma(a, scale)).
n_trials (int) – Number of trials to simulate.
n_jobs (int) – Number of jobs to use with MNE’s function (multithreading).
file (str) – Name of the file to be saved (number of the subject will be added).
relations (list, optional) – List of integers describing to which previous event each event is connected. 1 means stimulus, 2 means one event after stimulus, etc. One event cannot be connected to an upcoming one.
data_type (str, optional) – Type of data to simulate. Options are “eeg”, “meg”, or “eeg/meg”. Default is “eeg”.
n_subj (int, optional) – Number of subjects to simulate. Default is 1.
path (str, optional) – Path where to save the data. Default is the current directory.
overwrite (bool, optional) – Whether to overwrite existing files. Default is False.
verbose (bool, optional) – Whether to display MNE’s output. Default is False.
noise (bool, optional) – Whether to add noise to the simulated sources. Default is True.
times (np.ndarray, optional) – Deterministic simulation of event transition times. Format is (n_sources, n_trials).
seed (int, optional) – Random seed for reproducibility. Default is None.
sfreq (float, optional) – Sampling frequency in Hz. Default is 100.0.
save_snr (bool, optional) – Whether to save the signal-to-noise ratio (SNR) at peak value and electrode noise. Default is False.
save_noiseless (bool, optional) – Whether to save the noiseless version of the simulated data. Default is False.
event_length_samples (list, optional) – List of event lengths in samples for each source (e.g. to simulate longer sinewaves). Default is None.
proportions (list, optional) – List of proportions of trials with each source. Default is None.
- Returns:
A list of file names (file + number of subject) and associated metadata.
- Return type:
list
- hmp.simulations.simulated_times_and_parameters(generating_events, model, trial_data, resampling_freq=None, data=None)#
Recover the generating HMP parameters from the simulated EEG data.
- Parameters:
generating_events (np.ndarray) – Times of the simulated events created by the function simulate().
model (hmp) – Initialized EventModel.
trial_data (TrialData) – Object containing trial-specific data such as starts, ends, and cross-correlation.
resampling_freq (float, optional) – Value of the new sampling frequency if there is a difference between the initialized HMP object and the generating_events. Default is None.
data (np.ndarray, optional) – Alternative data to use instead of cross-correlation contained in trial_data.crosscorr. Default is None.
- Return type:
tuple[ndarray,list,ndarray,ndarray]- Returns:
random_source_times (np.ndarray) – Index of the true events found in the test estimation.
true_time_pars (list) – List of true distribution parameters (2D array: stages * parameters).
true_channel_pars (np.ndarray) – 2D ndarray (n_events * components), true electrode contribution to each event.
true_activities (np.ndarray) – Actual values at simulated event times.