API#

Technical reference for all functions, classes, and modules in HMP.

Models#

Basedata module#

Builds the base data object to be used in HMP, including preprocessing and projections.

BaseData is typically initialized through the function ‘from_io’.

Option 1, first build an object with from_io(io_data), then apply operations in the following order:

hmp_data = hmp.basedata.from_io(io_data) hmp_data.crop_reject_epochs(duration_id=’response_time’) hmp_data.project(hmp.projectors.PCA(n_comp=10)) hmp_data.apply_variance_ops()

Option 2: use the default pipeline with:

hmp_data = hmp.basedata.default(io_data,duration_id=’response_time’,n_comp=10)

Includes methods to:
  1. Reject durations whose interval exceeds lower and upper interval limits (min_duration and max_duration).

    Reject epochs whose amplitude exceeds a threshold on any electrode. For valid epochs crop the data up to duration Center the data using samples from baseline up to duration.

  2. Project channels to new virtual channel, either based on PCA,

    an arbitrary linear combination of channels, or the identity of the channels.

  3. Whiten the components, standardize the components for each recording (False by Default)

    and standardize each trial’s variance (common_variance).

class hmp.basedata.BaseData(data)#

Bases: object

BaseData class containing all data necessary for estimating HMP models.

data#

Data with dimensions [sample, component, trial], coordinates that describe the dataset including recording, subject, epoch, and a trial MultiIndex, and attributes sfreq and offset. Typically obtained through class method ‘from_io(..)’.

Type:

xr.DataArray

apply_variance_ops(whiten=True, common_variance=False, standardize_recording=False)#

Apply three variance operators, typically after projection.

whitenbool, optional

Return the components with unit-variance Default = True

common_variancebool, optional

Standardize variance across trials. Default = False

standardize_recording: bool, optional

Divide each component for each recording by its standard deviation Default = False

crop_reject_epochs(duration_id='response_time', offsets=(0, 0), center=True, min_duration=0, max_duration=None, reject_amplitude=inf, verbose=True)#

Crop and reject epochs, typically before projection.

duration_id: str, optional

Name of the variable that contains the trial intervals in the epoch_data used for cropping and rejection. Default = None

offsetstuple, optional

Seconds of recording to keep before and after end of each epoch duration. First value refers to the times taken before epoch center and second value to the time kept after end. Should be positive. Used for padding the data before crosscorrelation. Adding template width / 2 is recommended. If float apply the offsets symmetrically. Default = 0

centerbool

Whether to use the median to center over all trials and electrodes using the samples from start of the epoch (baseline) to duration of the trial.

min_durationfloat, optional

Minimum duration threshold for keeping epochs. Default = 0

max_durationfloat, optional

Maximum duration threshold for keeping epochs. Default = Inf

reject_amplitudefloat, optional

Amplitude threshold for rejecting noisy epochs. Default = Inf

data: DataArray#
pca_and_variance(n_comp=None, method_pca='svd', whiten=True, common_variance=False, standardize_recording=False, verbose=True)#

Apply PCA and variance operations.

project(projector)#

Project data from channels to components.

projector: Projector

Module from the projectors class

select_coord(value, variable, method=<ufunc 'equal'>, copy=True)#

Select a subset from basedata using the specified coordinate(s).

The function selects trials where method(data[variable], value) is True. You can either use functions returning booleans or a custom function using lambda, e.g. method=lambda x, v: ~x.isin(v)

Parameters:
  • value (str | num) – Value to test with method().

  • variable (str) – coordinate present in data that is used for condition selection

  • method (callable) – You can use callable resulting in a boolean, e.g. ‘np.equal’, np.greater or lambda s, v: s.str.contains(v) Method also allows for ‘contains’ that selects trial in which value appears in variable (e.g. ‘comp’ in ‘incompatible’ and ‘compatible’)

  • copy (bool) – Whether to return a copy (True, Default) or overwrite the current object (False)

Returns:

data – Subset of the provided BaseData object.

Return type:

BaseData

hmp.basedata.default(epoch_data, duration_id='response_time', offsets=(0, 0), center=True, min_duration=0, max_duration=None, reject_amplitude=inf, n_comp=None, whiten=True, common_variance=False, standardize_recording=False, verbose=True)#

Create a BaseData instance from data from io.

Includes:
  • epoch cropping and rejection

  • PCA

  • variance operations.

Parameters:
  • epoch_data (xr.DataArray) – Data with dimensions [sample, component, trial], coordinates that describe the dataset including recording, subject, epoch, and a trial MultiIndex, and attributes sfreq and offset. Typically obtained through class method ‘from_io(..)’.

  • duration_id (str, optional) – Name of the variable that contains the trial intervals in the epoch_data used for cropping. Default = ‘response_time’.

  • offsets (tuple, float, optional) – Seconds of recording to keep before and after end of each epoch duration. First value refers to the times taken before epoch center and second value to the time kept after end. Should be positive. Used for padding the data before crosscorrelation. Adding template width / 2 is recommended. If float apply the offsets symmetrically. Default = 0

  • center (bool) – Median center the data after cropping including baseline default = False

  • min_duration (float, optional) – Minimum duration threshold for keeping epochs. Default = 0

  • max_duration (float, optional) – Maximum duration threshold for keeping epochs. Default = Inf

  • reject_amplitude (float, optional) – Amplitude threshold for rejecting noisy epochs. Default = None

  • n_comp (int, optional) – Nr of components retained if > 1, otherwise (0 < n_comp < 1) nr of components explaining at least n_comp% variance are retained. If None, user input requested. Default = None

  • whiten (bool, optional) – Return the components with unit-variance Default = True

  • common_variance (bool, optional) – Standardize variance across trials. Default = False

  • standardize_recording (bool, optional) – Divide each component for each recording by its standard deviation Default = False

  • verbose (bool) – Provide feedback on the different operations

Returns:

An instance of BaseData using default preprocessing routine

Return type:

BaseData

hmp.basedata.from_io(epoch_data)#

Create a BaseData instance from data from io.

Parameters:

epoch_data (xr.Dataset) – Input EEG data with dimensions [recording, epoch, sample, channel], from io module

Returns:

An instance of BaseData

Return type:

BaseData

Projections module#

Input/output module#

Distributions module#

Classes for several probability distributions (Gamma, Lognormal, Wald, Weibull).

class hmp.distributions.Gamma(shape=2)#

Bases: object

Define 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: object

Define 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: object

Define 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: object

Define 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.

Main class Pattern and including a half-sine wave template (HalfSine)

Classes#

Pattern - Main class
HalfSine

Generates a normalized half-sine wave template for use in signal processing or event detection.

class hmp.patterns.HalfSine(width=50)#

Bases: Pattern

Create a HalfSine instance with the expected parameters.

Parameters:

width (float, optional) – Width of the half-sine wave in milliseconds, by default 50 ms (1000Hz). 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)

static create_template(width)#

Create a HalfSine template with the expected parameters.

class hmp.patterns.Pattern(template, width=None)#

Bases: ABC

General class to be passed to models.

Parameters:
  • template (np.ndarray) – The pattern template.

  • width (int, optional) – Length of the pattern in ms (= samples at 1000Hz).

PatternData module#

Builds the data to be used in HMP model estimation.

class hmp.patterndata.PatternData(durations, starts, ends, sfreq, pattern, template, cross_corr)#

Bases: object

A 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

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_basedata(base_data, pattern=None, dtype=None)#

Create a TrialData instance from preprocessed data and a given pattern.

Parameters:
  • base_data (BaseData or xr.DataArray) – BaseData object or xarray DataArray containing the preprocessed data.

  • pattern (Pattern) – The pattern to use for cross-correlation computation. Default is half sine with 50 ms width.

  • dtype (np.DTypeLike) – Precision, use np.float32 or np.int64. By default inherits from data.

Returns:

An instance of PatternData with computed durations, cross-correlation, and metadata.

Return type:

PatternData

pattern: Pattern#
sfreq: float#
starts: ndarray#
template: ndarray#
hmp.patterndata.cross_correlation(data, template, offset_start, offset_end)#

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. It uses the “same” mode of the scipy.signal.correlate function which is OK if baseline + offset end, if not it’s not the worst strategy assuming centered signal

Parameters:
  • data (np.ndarray) – 2D ndarray with shape (n_samples, n_components).

  • template (np.ndarray) – 1D array representing the pattern to correlate with.

  • offset_start (int) – Samples before duration start in the data, used to pad before crosscorrelation

  • offset_end (int) – Samples after duration end in the data, used to pad before crosscorrelation

Returns:

crossc – A 2D ndarray with shape (n_samples * n_trials, n_components) where each cell contains the correlation value of the component time serie 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 ‘recording’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, 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_model(epoch_data, estimates, channel_position, *args, **kwargs)#

Plot model results.

Plot the event topographies at the average time of the onset of the next stage. Either from an EventModel or Eliminative model, based on the number of dimensions of the estimates.

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.

  • **kwargs (*args and) –

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=True, 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 (tuple | list, optional) – tuple 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(epoch_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:
  • epoch_data (xr.Dataset) – epoch_data from hmp.io

  • 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 event

  • baseline (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 = 0

  • event_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.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, 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

  • 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.select_coord(data, value, variable, method=<ufunc 'equal'>, copy=True)#

Select a subset from the data or estimates using the specified coordinate(s).

The function selects trials where method(data[variable], value) is True. You can either use functions returning booleans or a custom function using lambda, e.g. method=lambda x, v: ~x.isin(v)

Parameters:
  • data (xr.Dataset | xr.DataArray) – Data from io or estimates from hmp

  • value (str | num) – Value to test with method().

  • variable (str) – coordinate present in data that is used for condition selection

  • method (callable) – You can use callable resulting in a boolean, e.g. ‘np.equal’, np.greater or lambda s, v: s.str.contains(v) Method also allows for ‘contains’ that selects trial in which value appears in variable (e.g. ‘comp’ in ‘incompatible’ and ‘compatible’)

  • copy (bool) – Whether to return a copy (True, Default) or overwrite the current object (False)

Returns:

data – Subset of 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, pattern_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.

  • pattern_data (PatternData) – 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 pattern_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.