ant.tools package#
Submodules#
ant.tools.orica module#
- class ant.tools.orica.ORICA(n_channels, learning_rate=0.1, block_size=256, online_whitening=True, calibrate_pca=False, forgetfac=1.0, nonlinearity='tanh', random_state=None)#
Bases:
object
Online Recursive ICA (ORICA) for EEG data.
- Parameters:
n_channels (int) – Number of input EEG channels.
learning_rate (float) – Learning rate for ICA updates.
block_size (int) – Size of blocks for online updates.
online_whitening (bool) – If True, perform online whitening. If False, assumes input is already whitened.
calibrate_pca (bool) – If True, estimate whitening matrix from initial block and fix it. If False, update recursively.
forgetfac (float) – Forgetting factor for online covariance (0 < forgetfac <= 1). Values < 1 allow adaptation to nonstationary signals.
nonlinearity (str) – Nonlinearity function: ‘tanh’, ‘pow3’, or ‘gauss’.
random_state (int | None) – Seed for reproducibility.
Methods
find_blink_ic
(template_map[, threshold])Identify independent components corresponding to blinks.
Fit ORICA to the data block X and return the estimated sources.
Reconstruct EEG data from the estimated sources.
partial_fit
(X)Update the unmixing matrix with a new block of EEG data using online ICA.
transform
(X)Apply the learned unmixing matrix to new data without updating it.
- find_blink_ic(template_map, threshold=0.7)#
Identify independent components corresponding to blinks.
Correlates each column of the mixing matrix A with a blink template map to detect blink-related components.
- Parameters:
template_map (ndarray, shape (n_channels,)) – Template topography of a blink (e.g., from frontal electrodes).
threshold (float, default=0.7) – Correlation threshold above which a component is considered blink-related.
- Returns:
blink_idx (list of int) – Indices of independent components likely corresponding to blinks.
corrs (ndarray, shape (n_components,)) – Correlation values between each component and the blink template.
- Raises:
RuntimeError – If the ORICA model has not been fitted yet.
- fit_transform(X)#
Fit ORICA to the data block X and return the estimated sources.
This is equivalent to calling partial_fit(X) followed by transform(X).
- Parameters:
X (ndarray, shape (n_channels, n_samples)) – EEG data block.
- Returns:
S – The estimated source signals.
- Return type:
ndarray, shape (n_channels, n_samples)
- inverse_transform(X)#
Reconstruct EEG data from the estimated sources.
This uses the pseudo-inverse of the unmixing matrix W to project source signals back to the sensor space. The channel mean is added back if available.
- Parameters:
S (ndarray, shape (n_channels, n_samples)) – Source signals to reconstruct.
- Returns:
X_rec – Reconstructed EEG data in sensor space.
- Return type:
ndarray, shape (n_channels, n_samples)
- Raises:
RuntimeError – If the ORICA model has not been fitted yet.
- partial_fit(X)#
Update the unmixing matrix with a new block of EEG data using online ICA.
This method performs one iteration of the ORICA algorithm, updating the unmixing matrix W incrementally with the provided data block X. It handles online whitening if enabled and maintains stability via QR decomposition.
- Parameters:
X (ndarray, shape (n_channels, n_samples)) – A block of EEG data. Each row corresponds to one channel.
- Returns:
self – The updated ORICA instance with the new unmixing matrix.
- Return type:
instance of ORICA
- Raises:
ValueError – If X does not have the expected number of channels.
- transform(X)#
Apply the learned unmixing matrix to new data without updating it.
This projects EEG data onto the source space using the current W. Online whitening is applied if enabled. No adaptation of W occurs.
- Parameters:
X (ndarray, shape (n_channels, n_samples)) – EEG data to transform.
- Returns:
S – The estimated source signals.
- Return type:
ndarray, shape (n_channels, n_samples)
ant.tools.simulation module#
- ant.tools.simulation.simulate_eeg_raw(brain_label, frequency, amplitude, duration, gap_duration, n_repetition, start, iir_filter=[0.2, -0.2, 0.04], fname_save=None, verbose=None)#
Simulate EEG data with a sinusoidal source in a given brain label.
A forward solution is created for
fsaverage
and a sinusoidal source is injected into the specified brain label. The simulated signal is then projected to sensor space, optionally repeated with gaps, and saved as an MNE Raw object.- Parameters:
brain_label (str) – Name (regexp) of the cortical label in which to simulate the source.
frequency (float) – Frequency of the simulated sine wave (Hz).
amplitude (float) – Amplitude scaling factor of the simulated signal.
duration (float) – Duration of each simulated signal epoch in seconds.
gap_duration (float) – Interval (in seconds) between consecutive signal epochs.
n_repetition (int) – Number of signal epochs to simulate.
start (float) – Start time of the first simulated signal, in seconds.
iir_filter (array_like) – IIR filter coefficients (denominator) used when adding noise.
verbose (bool | str | int | None) – Control verbosity of the logging output.
- Returns:
raw – The simulated raw EEG object.
- Return type:
instance of mne.io.Raw
Notes
The simulated raw file is also written to disk in the
data/simulated
subdirectory, with a filename that includes the brain label, frequency, and amplitude.Examples
>>> raw = simulate_eeg_raw('bankssts-lh', frequency=10, amplitude=1e-9, ... duration=2., gap_duration=1., n_repetition=5, ... start=0.) >>> raw.plot()
ant.tools.tools module#
- ant.tools.tools.butter_bandpass(l_freq, h_freq, sfreq, order)#
Design a Butterworth band-pass filter.
- Parameters:
- Returns:
sos – Second-order sections representation of the band-pass filter, suitable for use with
scipy.signal.sosfiltfilt()
.- Return type:
ndarray
- ant.tools.tools.compute_bandpower(data, sfreq, band, method='fft', relative=True, window='hann', n_fft=None, **kwargs)#
Compute the bandpower of EEG/MEG channels using various PSD estimation methods.
- Parameters:
data (ndarray, shape (n_channels, n_samples)) – Input time series data.
sfreq (float) – Sampling frequency in Hz.
band (tuple of float) – Frequency band of interest (low, high) in Hz.
method ({'fft', 'periodogram', 'welch', 'multitaper'}, default='fft') – PSD estimation method.
relative (bool, default=True) – Normalize by total power if True.
window (str, default='hann') – Window type (used only for ‘fft’).
n_fft (int | None) – Number of FFT points (used only for ‘fft’).
**kwargs (additional keyword arguments) – Passed to the respective PSD functions.
- Returns:
bandpower – Bandpower of each channel in the requested frequency band.
- Return type:
ndarray, shape (n_channels,)
- ant.tools.tools.compute_fft(sfreq, winsize, freq_range, freq_res=1)#
Compute FFT-related quantities for spectral analysis.
- Parameters:
- Returns:
fft_window (ndarray, shape (n_times,)) – Hanning window of length
winsize * sfreq
in samples.freq_band (ndarray, shape (n_freqs,)) – Array of frequencies within the specified range.
freq_band_idxs (ndarray, shape (n_freqs,)) – Indices of
frequencies
corresponding tofreq_band
.frequencies (ndarray, shape (n_freqs_total,)) – Array of frequencies from the FFT across the full spectrum.
- ant.tools.tools.create_blink_template(raw, max_iter=800, method='infomax')#
Create a template for eye blink ICA component from raw EEG data.
- Parameters:
- Returns:
template_blink_comp – The spatial topography of the ICA component corresponding to the blink (shape: n_channels x 1). If no blink component is detected, returns None.
- Return type:
np.ndarray
- ant.tools.tools.estimate_aperiodic_component(raw_baseline, picks, method, freq_range=(1, 20), verbose=None)#
Estimate the aperiodic (1/f) component of a PSD using FOOOF.
- Parameters:
raw_baseline (mne.io.BaseRaw) – MNE Raw object containing baseline data.
picks (str | list) – Channels to include in PSD computation.
psd_params (dict) – Parameters passed to raw_baseline.compute_psd().
freq_range (tuple of float, optional (default=(1, 20))) – Frequency range in Hz for fitting the model.
verbose (bool, optional) – Whether to print FOOOF fitting progress.
- Returns:
aperiodic_params (ndarray) – Parameters of the aperiodic component (offset, slope, knee if used).
peak_params (ndarray) – Parameters of oscillatory peaks identified in the spectrum.
- ant.tools.tools.get_canonical_freqs(frange_name)#
Map a canonical frequency band name to its frequency range.
- Parameters:
frange_name (str) – Name of the frequency band. Supported values include: ‘delta’, ‘theta’, ‘alpha’, ‘lower_alpha’, ‘upper_alpha’, ‘smr’, ‘beta’, ‘lower_beta’, ‘upper_beta’, ‘gamma’, ‘lower_gamma’, ‘upper_gamma’.
- Returns:
Two-element list containing [low_freq, high_freq] in Hz.
- Return type:
List[float]
- Raises:
ValueError – If the provided frequency band name is not defined.
- ant.tools.tools.get_params(config_file, modality, modality_params)#
Load and update parameters for a given neurofeedback (NF) modality.
- Parameters:
config_file (str | path-like) – Path to the YAML configuration file containing modality parameters.
modality (str) – Name of the neurofeedback modality. Must be present in the
NF_modality
section of the config file.modality_params (dict | None) – Optional dictionary with parameter overrides. The keys should be method names (e.g., “fft”, “welch”), and the values should be dictionaries with parameter key-value pairs to update.
- Returns:
params – Dictionary containing updated parameters for the specified modality.
- Return type:
- Raises:
ValueError – If the modality is not found in the config file.
ValueError – If a provided method in
modality_params
is not available for the given modality.
Notes
This function first loads default parameters for the requested modality from the YAML file. If
modality_params
is provided, the defaults are updated with the user-specified overrides.
- ant.tools.tools.log_degree_barrier(signals, dist_type, alpha, beta, step=0.5, max_iter=10000, rtol=1e-16, w0=None)#
Graph learning with a log-barrier degree constraint.
Builds a weighted graph from smooth signals by solving a convex optimization problem with: - distance fitting, - log-barrier enforcing non-degenerate node degrees, - quadratic regularization on edge weights.
- Parameters:
signals (array of shape (n_nodes, n_samples)) – Input data (node-wise signals).
dist_type (str) – Distance metric to use (passed to
scipy.spatial.distance.pdist
).alpha (float) – Weight of the log-barrier degree penalty.
beta (float) – Weight of the L2 regularization term.
step (float) – Initial step size for the optimization.
w0 (array or None) – Initial edge weights. If None, initialized to zeros.
max_iter (int) – Maximum number of iterations for the solver.
rtol (float) – Relative tolerance for convergence.
- Returns:
graph_matrix – Learned adjacency matrix of the graph.
- Return type:
ndarray of shape (n_nodes, n_nodes)
Notes
Uses MLF-BF primal-dual solver (external solvers package).
Relies on functions.func objects with custom eval/prox/grad.
The optimization problem solved is of the form:
min_w 2 <w, z> - α Σ log(k(w)) + β ||w||²
where z are normalized pairwise distances and k(w) maps edge weights to node degrees.
- ant.tools.tools.plot_glass_brain(bl1, bl2=None)#
Plot one or two brain labels on an fsaverage glass brain.
- Parameters:
- Returns:
fig_brain – Figure containing the glass brain plots with highlighted labels.
- Return type:
matplotlib.figure.Figure
Notes
This function uses the
fsaverage
subject and theaparc
parcellation from FreeSurfer. The labels are displayed on a cortical surface rendering using four different views (frontal, dorsal, frontal, lateral).
- ant.tools.tools.remove_blinks_lms(data, ref_ch_idx=0, n_taps=5, mu=0.01)#
Remove blink artifacts from EEG using adaptive regression (LMS).
- Parameters:
- Returns:
cleaned – Shape (n_channels, n_times), cleaned EEG.
- Return type:
np.ndarray
- ant.tools.tools.setup_plotter(mesh, clim=[0, 0.6], camera_position='yz', azimuth=45)#
Initialize PyVista plotter, add mesh, and set camera.
- ant.tools.tools.setup_surface(subjects_dir, hemi_distance=100.0)#
Fetch fsaverage surfaces and prepare PyVista mesh for both hemispheres.
- ant.tools.tools.timed(func)#
Decorator to measure execution time of a function.
- Parameters:
func (callable) – Function to be timed.
- Returns:
wrapper – Wrapped function that returns both the function’s output and its execution time in seconds.
- Return type:
callable
Notes
The decorated function returns a tuple
(value, elapsed_time)
, wherevalue
is the original return value of the function, andelapsed_time
is the runtime measured withtime.perf_counter()
.
- ant.tools.tools.weight_to_degree_map(n_nodes)#
Construct linear mappings between edge weights and node degrees.
Given a graph with n_nodes, this function builds a sparse matrix that maps edge weights to node degrees and its transpose. The resulting linear operators are useful in graph optimization problems.
- Parameters:
n_nodes (int) – Number of nodes in the graph.
- Returns:
k (callable) – Function mapping edge weights (1D array of length n_edges) to node degrees (1D array of length n_nodes).
kt (callable) – Function mapping node degrees back to edge weights.
Notes
The number of edges is
n_edges = n_nodes * (n_nodes - 1) / 2
.Internally, constructs a sparse COO matrix of shape
(n_nodes, n_edges)
.