Correction API

Correction processors for removing fMRI artifacts from EEG data.

AAS Correction

AASCorrection

class facet.correction.AASCorrection(window_size: int = 30, rel_window_position: float = 0.0, correlation_threshold: float = 0.975, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, interpolate_volume_gaps: bool = False, apply_epoch_alpha_scaling: bool = False)[source]

Bases: Processor

Remove fMRI gradient artifacts using Averaged Artifact Subtraction.

For each trigger epoch, finds highly correlated epochs within a sliding window and computes a weighted average. The averaged template is then subtracted from the original epoch. The algorithm adapts to non-stationary artifacts through correlation-based epoch selection.

References

Allen et al., 2000. “A method for removing imaging artifact from continuous EEG recorded during functional MRI.” NeuroImage, 12(2), 230-239.

Parameters:
  • window_size (int) – Number of epochs to consider in the sliding window (default: 30).

  • rel_window_position (float) – Relative position of the window center between -1 and 1, where 0 is centered on the current epoch (default: 0.0).

  • correlation_threshold (float) – Minimum Pearson r required to include an epoch in the average (default: 0.975).

  • plot_artifacts (bool) – If True, plots a randomly selected averaged artifact after computation (default: False).

  • realign_after_averaging (bool) – If True, realigns trigger positions to the averaged artifact templates using cross-correlation (default: True).

  • search_window_factor (float) – Multiplier of the upsampling factor used as the cross-correlation search window (default: 3.0).

  • interpolate_volume_gaps (bool) – If True, linearly interpolate estimated artifact/noise values in gaps between consecutive artifact windows (default: False).

  • apply_epoch_alpha_scaling (bool) – If True, scale each epoch template by a least-squares alpha factor before subtraction, similar to MATLAB FACET CalcAvgArt (default: False).

name: str = 'aas_correction'
description: str = 'Averaged Artifact Subtraction for fMRI artifacts'
version: str = '1.0.0'
requires_triggers: bool = True
requires_raw: bool = True
modifies_raw: bool = True
parallel_safe: bool = True
channel_wise: bool = True
__init__(window_size: int = 30, rel_window_position: float = 0.0, correlation_threshold: float = 0.975, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, interpolate_volume_gaps: bool = False, apply_epoch_alpha_scaling: bool = False) None[source]

Initialize processor.

validate(context: ProcessingContext) None[source]

Validate that prerequisites are met.

Override this method to add custom validation logic.

Parameters:

context – Processing context

Raises:

ProcessorValidationError – If validation fails

process(context: ProcessingContext) ProcessingContext[source]

Process the context.

This is the main method to implement in subclasses.

Parameters:

context – Input processing context

Returns:

Output processing context. If None is returned, the input context is used (no-op behavior).

AveragedArtifactSubtraction (alias)

facet.correction.AveragedArtifactSubtraction

alias of AASCorrection

FARM Correction

FARMCorrection

class facet.correction.FARMCorrection(window_size: int = 30, correlation_threshold: float = 0.9, search_half_window: int | None = None, search_half_window_factor: float = 3.0, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, interpolate_volume_gaps: bool = False, apply_epoch_alpha_scaling: bool = False)[source]

Bases: AASCorrection

Remove fMRI artifacts using the MATLAB FACET FARM weighting strategy.

This processor reuses the AAS subtraction pipeline but replaces template selection with the FARM rule from MATLAB AvgArtWghtFARM:

  • Compute epoch-to-epoch correlations for one channel.

  • For each epoch, search within a wide neighborhood.

  • Keep up to window_size most correlated epochs above threshold.

  • Average the selected epochs with equal weights.

Parameters:
  • window_size (int) – Number of similar epochs to average (default: 30).

  • correlation_threshold (float) – Minimum absolute correlation for candidate selection (default: 0.9, matching MATLAB FARM).

  • search_half_window (int, optional) – Half-window in epochs used for candidate search. If None, derived from search_half_window_factor * window_size.

  • search_half_window_factor (float) – Multiplier used when search_half_window is not set (default: 3.0).

  • plot_artifacts (bool) – If True, plot one random averaged artifact (default: False).

  • realign_after_averaging (bool) – If True, realign triggers after template averaging (default: True).

  • search_window_factor (float) – Trigger-realignment search-window factor (default: 3.0).

  • interpolate_volume_gaps (bool) – If True, interpolate estimated artifact/noise in inter-epoch gaps (default: False).

  • apply_epoch_alpha_scaling (bool) – If True, apply MATLAB-like per-epoch least-squares alpha scaling before subtraction (default: False).

name: str = 'farm_correction'
description: str = 'AAS with MATLAB FACET FARM template weighting'
version: str = '1.0.0'
__init__(window_size: int = 30, correlation_threshold: float = 0.9, search_half_window: int | None = None, search_half_window_factor: float = 3.0, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, interpolate_volume_gaps: bool = False, apply_epoch_alpha_scaling: bool = False) None[source]

Initialize processor.

validate(context: ProcessingContext) None[source]

Validate that prerequisites are met.

Override this method to add custom validation logic.

Parameters:

context – Processing context

Raises:

ProcessorValidationError – If validation fails

Volume Artifact Correction

VolumeArtifactCorrection

class facet.correction.VolumeArtifactCorrection(template_count: int = 5, weighting_position: float = 0.8, weighting_slope: float = 20.0)[source]

Bases: Processor

Correct volume-transition artifacts around slice-trigger gaps.

MATLAB FACET’s RARemoveVolumeArtifact subtracts a transition artifact from the slice before and after each detected volume gap, then linearly interpolates the gap itself. This processor ports that behavior.

Parameters:
  • template_count (int) – Number of neighboring slices used to form pre/post templates (default: 5).

  • weighting_position (float) – Relative location of the logistic midpoint inside one artifact epoch (default: 0.8).

  • weighting_slope (float) – Logistic slope used for transition weighting (default: 20.0).

name: str = 'volume_artifact_correction'
description: str = 'Correct transition artifacts around volume gaps'
version: str = '1.0.0'
requires_triggers: bool = True
requires_raw: bool = True
modifies_raw: bool = True
parallel_safe: bool = True
channel_wise: bool = True
__init__(template_count: int = 5, weighting_position: float = 0.8, weighting_slope: float = 20.0) None[source]

Initialize processor.

validate(context: ProcessingContext) None[source]

Validate that prerequisites are met.

Override this method to add custom validation logic.

Parameters:

context – Processing context

Raises:

ProcessorValidationError – If validation fails

process(context: ProcessingContext) ProcessingContext[source]

Process the context.

This is the main method to implement in subclasses.

Parameters:

context – Input processing context

Returns:

Output processing context. If None is returned, the input context is used (no-op behavior).

RemoveVolumeArtifactCorrection

facet.correction.RemoveVolumeArtifactCorrection

alias of VolumeArtifactCorrection

AAS Weighting Variants

CorrespondingSliceCorrection

class facet.correction.CorrespondingSliceCorrection(slices_per_volume: int | None = None, window_size: int = 30, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, apply_epoch_alpha_scaling: bool = False)[source]

Bases: AASCorrection

AAS with corresponding-slice averaging across volumes.

This implements MATLAB FACET’s AvgArtWghtCorrespondingSlice rule: each slice epoch is averaged with the same slice position in neighboring volumes.

Parameters:
  • slices_per_volume (int, optional) – Number of slices per volume. If None, the value is taken from context.metadata.slices_per_volume.

  • window_size (int) – Half-window in volumes (default: 30).

  • plot_artifacts (bool) – If True, plot one random averaged artifact (default: False).

  • realign_after_averaging (bool) – If True, realign triggers after averaging (default: True).

  • search_window_factor (float) – Trigger realignment search-window factor (default: 3.0).

  • apply_epoch_alpha_scaling (bool) – If True, apply MATLAB-like per-epoch least-squares alpha scaling before subtraction (default: False).

name: str = 'corresponding_slice_correction'
description: str = 'AAS with corresponding-slice averaging across volumes'
version: str = '1.0.0'
__init__(slices_per_volume: int | None = None, window_size: int = 30, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, apply_epoch_alpha_scaling: bool = False) None[source]

Initialize processor.

validate(context: ProcessingContext) None[source]

Validate that prerequisites are met.

Override this method to add custom validation logic.

Parameters:

context – Processing context

Raises:

ProcessorValidationError – If validation fails

process(context: ProcessingContext) ProcessingContext[source]

Process the context.

This is the main method to implement in subclasses.

Parameters:

context – Input processing context

Returns:

Output processing context. If None is returned, the input context is used (no-op behavior).

VolumeTriggerCorrection

class facet.correction.VolumeTriggerCorrection(window_size: int = 30, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, apply_epoch_alpha_scaling: bool = False)[source]

Bases: AASCorrection

AAS with MATLAB FACET volume-trigger weighting.

Reproduces AvgArtWghtVolumeTrigger weighting for volume/section trigger workflows.

Parameters:
  • window_size (int) – Averaging window size in epochs (default: 30).

  • plot_artifacts (bool) – If True, plot one random averaged artifact (default: False).

  • realign_after_averaging (bool) – If True, realign triggers after averaging (default: True).

  • search_window_factor (float) – Trigger realignment search-window factor (default: 3.0).

  • apply_epoch_alpha_scaling (bool) – If True, apply MATLAB-like per-epoch least-squares alpha scaling before subtraction (default: False).

name: str = 'volume_trigger_correction'
description: str = 'AAS with MATLAB volume-trigger averaging weights'
version: str = '1.0.0'
__init__(window_size: int = 30, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, apply_epoch_alpha_scaling: bool = False) None[source]

Initialize processor.

SliceTriggerCorrection

class facet.correction.SliceTriggerCorrection(window_size: int = 30, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, apply_epoch_alpha_scaling: bool = False)[source]

Bases: AASCorrection

AAS with MATLAB FACET slice-trigger odd/even template weighting.

Reproduces AvgArtWghtSliceTrigger behavior by constructing one averaging set from every second epoch (even offsets) and another from the complementary epochs (odd offsets), then alternating between them.

Parameters:
  • window_size (int) – Half-window size in epochs (default: 30).

  • plot_artifacts (bool) – If True, plot one random averaged artifact (default: False).

  • realign_after_averaging (bool) – If True, realign triggers after averaging (default: True).

  • search_window_factor (float) – Trigger realignment search-window factor (default: 3.0).

  • apply_epoch_alpha_scaling (bool) – If True, apply MATLAB-like per-epoch least-squares alpha scaling before subtraction (default: False).

name: str = 'slice_trigger_correction'
description: str = 'AAS with MATLAB slice-trigger odd/even averaging weights'
version: str = '1.0.0'
__init__(window_size: int = 30, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, apply_epoch_alpha_scaling: bool = False) None[source]

Initialize processor.

MoosmannCorrection

class facet.correction.MoosmannCorrection(rp_file: str, window_size: int = 30, motion_threshold: float = 5.0, motion_window_size: int | None = None, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, apply_epoch_alpha_scaling: bool = False)[source]

Bases: AASCorrection

AAS with motion-informed Moosmann averaging weights.

Uses the realignment-parameter-informed weighting strategy from AvgArtWghtMoosmann.

Parameters:
  • rp_file (str) – Path to SPM-style realignment parameter text file.

  • window_size (int) – AAS base window size (default: 30).

  • motion_threshold (float) – Motion threshold passed to the weighting routine (default: 5.0).

  • motion_window_size (int, optional) – Number of neighboring epochs for motion weighting. If None, uses 2 * window_size.

  • plot_artifacts (bool) – If True, plot one random averaged artifact (default: False).

  • realign_after_averaging (bool) – If True, realign triggers after averaging (default: True).

  • search_window_factor (float) – Trigger realignment search-window factor (default: 3.0).

  • apply_epoch_alpha_scaling (bool) – If True, apply MATLAB-like per-epoch least-squares alpha scaling before subtraction (default: False).

name: str = 'moosmann_correction'
description: str = 'AAS with motion-informed Moosmann template weighting'
version: str = '1.0.0'
__init__(rp_file: str, window_size: int = 30, motion_threshold: float = 5.0, motion_window_size: int | None = None, plot_artifacts: bool = False, realign_after_averaging: bool = True, search_window_factor: float = 3.0, apply_epoch_alpha_scaling: bool = False) None[source]

Initialize processor.

validate(context: ProcessingContext) None[source]

Validate that prerequisites are met.

Override this method to add custom validation logic.

Parameters:

context – Processing context

Raises:

ProcessorValidationError – If validation fails

process(context: ProcessingContext) ProcessingContext[source]

Process the context.

This is the main method to implement in subclasses.

Parameters:

context – Input processing context

Returns:

Output processing context. If None is returned, the input context is used (no-op behavior).

ANC Correction

ANCCorrection

class facet.correction.ANCCorrection(filter_order: int | None = None, hp_freq: float | None = None, hp_filter_weights: ndarray | None = None, use_c_extension: bool = True, mu_factor: float = 0.05, max_gain: float = 50.0)[source]

Bases: Processor

Remove residual fMRI artifacts using Adaptive Noise Cancellation.

Uses the estimated noise from a prior correction step (e.g. AAS) as a reference signal. The LMS adaptive filter iteratively minimises the residual between the EEG and a scaled, filtered copy of the reference, yielding a per-channel filtered-noise estimate that is subtracted from the EEG.

The algorithm:

  1. High-pass filters EEG and reference to remove DC / low-frequency drift.

  2. Scales the reference to match EEG amplitude (Alpha factor).

  3. Adapts filter coefficients using the LMS algorithm.

  4. Subtracts the filtered noise from the EEG.

Parameters:
  • filter_order (int, optional) – Adaptive filter order. Defaults to artifact length derived from context.

  • hp_freq (float, optional) – High-pass cutoff frequency in Hz. Auto-derived from trigger rate when not specified.

  • hp_filter_weights (numpy.ndarray, optional) – Pre-computed FIR filter weights; overrides hp_freq when provided.

  • use_c_extension (bool) – Use the optional fastranc C extension for speed (default: True). Falls back to the pure-Python LMS implementation automatically.

  • mu_factor (float) – Learning-rate numerator; actual µ = mu_factor / (N × var(ref)) (default: 0.05).

  • max_gain (float) – Maximum allowed ratio of filtered-noise amplitude to EEG amplitude. Corrections exceeding this are discarded (default: 50.0).

name: str = 'anc_correction'
description: str = 'Adaptive Noise Cancellation for residual artifacts'
version: str = '1.0.0'
requires_triggers: bool = True
requires_raw: bool = True
modifies_raw: bool = True
parallel_safe: bool = False
channel_wise: bool = True
__init__(filter_order: int | None = None, hp_freq: float | None = None, hp_filter_weights: ndarray | None = None, use_c_extension: bool = True, mu_factor: float = 0.05, max_gain: float = 50.0) None[source]

Initialize processor.

validate(context: ProcessingContext) None[source]

Validate that prerequisites are met.

Override this method to add custom validation logic.

Parameters:

context – Processing context

Raises:

ProcessorValidationError – If validation fails

process(context: ProcessingContext) ProcessingContext[source]

Process the context.

This is the main method to implement in subclasses.

Parameters:

context – Input processing context

Returns:

Output processing context. If None is returned, the input context is used (no-op behavior).

AdaptiveNoiseCancellation (alias)

facet.correction.AdaptiveNoiseCancellation

alias of ANCCorrection

PCA Correction

PCACorrection

class facet.correction.PCACorrection(n_components: int | float | str = 0.95, hp_freq: float | None = None, hp_filter_weights: ndarray | None = None, exclude_channels: list | None = None)[source]

Bases: Processor

Remove fMRI artifacts from EEG data using Principal Component Analysis.

Splits the acquisition window into trigger-aligned epochs, applies PCA to each epoch, reconstructs the data using the retained components, and subtracts the reconstruction from the original signal. The subtracted portion is treated as the artifact estimate.

The number of retained components can be controlled precisely:

  • An integer keeps exactly that many components.

  • A float in (0, 1) retains enough components to explain that fraction of the total variance (e.g. 0.95 → 95 %).

  • "auto" uses MATLAB FACET OBS heuristics.

  • 0 skips PCA for all channels.

Parameters:
  • n_components (int or float or str) – Number of PCA components to retain (int) or variance fraction to retain (float in (0, 1)). Use "auto" for MATLAB-like OBS auto selection. Default: 0.95.

  • hp_freq (float, optional) – High-pass cutoff frequency in Hz applied before PCA. None skips filtering (default: None).

  • hp_filter_weights (numpy.ndarray, optional) – Pre-computed filter weights; overrides hp_freq when provided.

  • exclude_channels (list, optional) – Channel indices to skip during PCA (default: empty list).

name: str = 'pca_correction'
description: str = 'PCA-based artifact removal'
version: str = '1.0.0'
requires_triggers: bool = True
requires_raw: bool = True
modifies_raw: bool = True
parallel_safe: bool = True
channel_wise: bool = True
TH_SLOPE = 2.0
TH_CUMVAR = 80.0
TH_VAREXP = 5.0
__init__(n_components: int | float | str = 0.95, hp_freq: float | None = None, hp_filter_weights: ndarray | None = None, exclude_channels: list | None = None) None[source]

Initialize processor.

validate(context: ProcessingContext) None[source]

Validate that prerequisites are met.

Override this method to add custom validation logic.

Parameters:

context – Processing context

Raises:

ProcessorValidationError – If validation fails

process(context: ProcessingContext) ProcessingContext[source]

Process the context.

This is the main method to implement in subclasses.

Parameters:

context – Input processing context

Returns:

Output processing context. If None is returned, the input context is used (no-op behavior).

Legacy Weighting Aliases

AvgArtWghtCorrespondingSliceCorrection

facet.correction.AvgArtWghtCorrespondingSliceCorrection

alias of CorrespondingSliceCorrection

AvgArtWghtVolumeTriggerCorrection

facet.correction.AvgArtWghtVolumeTriggerCorrection

alias of VolumeTriggerCorrection

AvgArtWghtSliceTriggerCorrection

facet.correction.AvgArtWghtSliceTriggerCorrection

alias of SliceTriggerCorrection

AvgArtWghtMoosmannCorrection

facet.correction.AvgArtWghtMoosmannCorrection

alias of MoosmannCorrection