Preprocessing API
Preprocessing processors for preparing EEG data before correction.
Filtering
Filter
- class facet.preprocessing.Filter(l_freq: float | None = None, h_freq: float | None = None, picks: str | list[str] | None = None, filter_length: str = 'auto', method: str = 'fir', phase: str = 'zero', fir_window: str = 'hamming', verbose: bool = False)[source]
Bases:
ProcessorApply MNE’s generic band/high/low-pass filter to EEG data.
Wraps
mne.io.Raw.filter()with configurable FIR/IIR parameters. If a noise estimate is present in the context, the same filter is applied to the noise so that downstream evaluation steps remain consistent.- Parameters:
l_freq (
float, optional) – Low cutoff frequency in Hz (Nonefor no highpass).h_freq (
float, optional) – High cutoff frequency in Hz (Nonefor no lowpass).picks (
strorlistofstr, optional) – Channels to filter.Nonefilters all channels.filter_length (
str, optional) – Length of the FIR filter (default:'auto').method (
str, optional) – Filter method,'fir'or'iir'(default:'fir').phase (
str, optional) – Phase of the filter (default:'zero').fir_window (
str, optional) – Window function for FIR filter (default:'hamming').verbose (
bool, optional) – MNE verbosity flag passed toraw.filter()(default:False).
- __init__(l_freq: float | None = None, h_freq: float | None = None, picks: str | list[str] | None = None, filter_length: str = 'auto', method: str = 'fir', phase: str = 'zero', fir_window: str = 'hamming', verbose: bool = False)[source]
Initialize processor.
- 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).
HighPassFilter
- class facet.preprocessing.HighPassFilter(freq: float, picks: str | list[str] | None = None, filter_length: str = 'auto', method: str = 'fir', phase: str = 'zero', fir_window: str = 'hamming')[source]
Bases:
FilterApply a highpass filter to EEG data.
Convenience subclass of
Filterthat exposes a singlefreqparameter instead of separatel_freq/h_freq.- Parameters:
freq (
float) – Highpass cutoff frequency in Hz.picks (
strorlistofstr, optional) – Channels to filter.Nonefilters all channels.filter_length (
str, optional) – Length of the FIR filter (default:'auto').method (
str, optional) – Filter method,'fir'or'iir'(default:'fir').phase (
str, optional) – Phase of the filter (default:'zero').fir_window (
str, optional) – Window function for FIR filter (default:'hamming').
LowPassFilter
- class facet.preprocessing.LowPassFilter(freq: float, picks: str | list[str] | None = None, filter_length: str = 'auto', method: str = 'fir', phase: str = 'zero', fir_window: str = 'hamming')[source]
Bases:
FilterApply a lowpass filter to EEG data.
Convenience subclass of
Filterthat exposes a singlefreqparameter instead of separatel_freq/h_freq.- Parameters:
freq (
float) – Lowpass cutoff frequency in Hz.picks (
strorlistofstr, optional) – Channels to filter.Nonefilters all channels.filter_length (
str, optional) – Length of the FIR filter (default:'auto').method (
str, optional) – Filter method,'fir'or'iir'(default:'fir').phase (
str, optional) – Phase of the filter (default:'zero').fir_window (
str, optional) – Window function for FIR filter (default:'hamming').
BandPassFilter
- class facet.preprocessing.BandPassFilter(l_freq: float, h_freq: float, picks: str | list[str] | None = None, filter_length: str = 'auto', method: str = 'fir', phase: str = 'zero', fir_window: str = 'hamming')[source]
Bases:
FilterApply a bandpass filter to EEG data.
Convenience subclass of
Filterthat requires bothl_freqandh_freqto be specified.- Parameters:
l_freq (
float) – Low cutoff frequency in Hz.h_freq (
float) – High cutoff frequency in Hz.picks (
strorlistofstr, optional) – Channels to filter.Nonefilters all channels.filter_length (
str, optional) – Length of the FIR filter (default:'auto').method (
str, optional) – Filter method,'fir'or'iir'(default:'fir').phase (
str, optional) – Phase of the filter (default:'zero').fir_window (
str, optional) – Window function for FIR filter (default:'hamming').
NotchFilter
- class facet.preprocessing.NotchFilter(freqs: float | list[float], picks: str | list[str] | None = None, filter_length: str = 'auto', notch_widths: float | list[float] | None = None, method: str = 'fir', phase: str = 'zero', fir_window: str = 'hamming')[source]
Bases:
ProcessorApply a notch filter to remove line noise from EEG data.
Wraps
mne.io.Raw.notch_filter()with configurable FIR/IIR parameters. Typical use is to remove 50 Hz or 60 Hz mains interference and their harmonics. If a noise estimate is present in the context, the same filter is applied to keep evaluation results consistent.- Parameters:
freqs (
floatorlistoffloat) – Frequencies to notch out in Hz (e.g.,[50, 100]).picks (
strorlistofstr, optional) – Channels to filter.Nonefilters all channels.filter_length (
str, optional) – Length of the FIR filter (default:'auto').notch_widths (
floatorlistoffloat, optional) – Width of each notch filter.Noneuses MNE defaults.method (
str, optional) – Filter method,'fir'or'iir'(default:'fir').phase (
str, optional) – Phase of the filter (default:'zero').fir_window (
str, optional) – Window function for FIR filter (default:'hamming').
- __init__(freqs: float | list[float], picks: str | list[str] | None = None, filter_length: str = 'auto', notch_widths: float | list[float] | None = None, method: str = 'fir', phase: str = 'zero', fir_window: str = 'hamming')[source]
Initialize processor.
- 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).
MATLABPreFilter
- class facet.preprocessing.MATLABPreFilter(lp_frequency: float | Sequence[float] | None = None, hp_frequency: float | Sequence[float] | None = None, transfer_frequencies: np.ndarray | Sequence[np.ndarray] | None = None, transfer_amplitudes: np.ndarray | Sequence[np.ndarray] | None = None, gauss_hp_frequency: float | Sequence[float] | None = None, picks: str | Sequence[str] = 'eeg', pad_acquisition: bool = True)[source]
Bases:
ProcessorApply MATLAB FACET-style FFT prefiltering before artifact correction.
Supports: - Piecewise-linear transfer-function filtering in frequency domain. - Gaussian high-pass filtering (DC-safe) in frequency domain. - Optional padded filtering inside the acquisition window.
- Parameters:
lp_frequency (
floatorcollections.abc.Sequenceoffloat, optional) – Low-pass cutoff in Hz (scalar or per-channel values).Nonemeans no LP from generated transfer functions.hp_frequency (
floatorcollections.abc.Sequenceoffloat, optional) – High-pass cutoff in Hz (scalar or per-channel values).Nonemeans no HP from generated transfer functions.transfer_frequencies (
numpy.ndarrayorcollections.abc.Sequenceofnumpy.ndarray, optional) – Custom normalized frequency points in[0, 1]for transfer-function filtering. If set, overrides LP/HP synthesis.transfer_amplitudes (
numpy.ndarrayorcollections.abc.Sequenceofnumpy.ndarray, optional) – Amplitude points corresponding totransfer_frequencies.gauss_hp_frequency (
floatorcollections.abc.Sequenceoffloat, optional) – Gaussian high-pass cutoff in Hz (scalar or per-channel values).picks (
strorcollections.abc.Sequenceofstr) – Channels to filter (default:"eeg").pad_acquisition (
bool) – Use acquisition-window padding during filtering (default: True).
- __init__(lp_frequency: float | Sequence[float] | None = None, hp_frequency: float | Sequence[float] | None = None, transfer_frequencies: np.ndarray | Sequence[np.ndarray] | None = None, transfer_amplitudes: np.ndarray | Sequence[np.ndarray] | None = None, gauss_hp_frequency: float | Sequence[float] | None = None, picks: str | Sequence[str] = 'eeg', pad_acquisition: bool = True) 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).
Resampling
Resample
- class facet.preprocessing.Resample(sfreq: float, npad: str = 'auto', window: str = 'boxcar', n_jobs: int = 1, verbose: bool = False)[source]
Bases:
ProcessorResample EEG data to a fixed target sampling frequency.
Wraps
mne.io.Raw.resample(). Trigger positions are scaled proportionally after resampling. If a noise estimate is present in the context, it is resampled with identical parameters so that downstream evaluation steps remain consistent.- Parameters:
sfreq (
float) – Target sampling frequency in Hz.npad (
str, optional) – Amount to pad the start and end of the data (default:'auto').window (
str, optional) – Window to use for resampling (default:'boxcar').n_jobs (
int, optional) – Number of parallel jobs for resampling (default:1).verbose (
bool, optional) – MNE verbosity flag passed toraw.resample()(default:False).
- __init__(sfreq: float, npad: str = 'auto', window: str = 'boxcar', n_jobs: int = 1, verbose: bool = False)[source]
Initialize processor.
- 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).
UpSample
- class facet.preprocessing.UpSample(factor: int = 10, npad: str = 'auto', window: str = 'boxcar', n_jobs: int = 1, verbose: bool = False)[source]
Bases:
ResampleUpsample EEG data by a fixed integer factor.
Increases the sampling frequency by multiplying it by factor. Trigger positions and any noise estimate are scaled accordingly.
- Parameters:
factor (
int, optional) – Upsampling factor, e.g.10increases the sampling frequency ten-fold (default:10).npad (
str, optional) – Amount to pad the start and end of the data (default:'auto').window (
str, optional) – Window to use for resampling (default:'boxcar').n_jobs (
int, optional) – Number of parallel jobs for resampling (default:1).verbose (
bool, optional) – MNE verbosity flag passed toraw.resample()(default:False).
- __init__(factor: int = 10, npad: str = 'auto', window: str = 'boxcar', n_jobs: int = 1, verbose: bool = False)[source]
Initialize processor.
- 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).
DownSample
- class facet.preprocessing.DownSample(factor: int = 10, npad: str = 'auto', window: str = 'boxcar', n_jobs: int = 1, verbose: bool = False)[source]
Bases:
ResampleDownsample EEG data by a fixed integer factor.
Decreases the sampling frequency by dividing it by factor. Trigger positions and any noise estimate are scaled accordingly.
- Parameters:
factor (
int, optional) – Downsampling factor, e.g.10reduces the sampling frequency ten-fold (default:10).npad (
str, optional) – Amount to pad the start and end of the data (default:'auto').window (
str, optional) – Window to use for resampling (default:'boxcar').n_jobs (
int, optional) – Number of parallel jobs for resampling (default:1).verbose (
bool, optional) – MNE verbosity flag passed toraw.resample()(default:False).
- __init__(factor: int = 10, npad: str = 'auto', window: str = 'boxcar', n_jobs: int = 1, verbose: bool = False)[source]
Initialize processor.
- validate(context: ProcessingContext) None[source]
Check that the resulting sampling frequency is at least 1 Hz.
- 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).
Trigger Detection
TriggerDetector
- class facet.preprocessing.TriggerDetector(regex: str, save_to_annotations: bool = False)[source]
Bases:
ProcessorDetect triggers from annotations or stim channels using a regex pattern.
Searches the raw data for events whose description (annotation) or integer value (stim channel) matches the supplied regular expression. Detected trigger sample positions are stored in
context.metadata.triggers.The artifact length is estimated from the median inter-trigger interval; volume-level gaps in slice-triggered acquisitions are detected automatically.
- Parameters:
- 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).
QRSTriggerDetector
- class facet.preprocessing.QRSTriggerDetector(save_to_annotations: bool = False)[source]
Bases:
ProcessorDetect QRS complexes (heartbeats) for BCG artifact correction.
Uses the FMRIB QRS detector from
facet.helpers.bcg_detector, which requires theneurokit2package (available viapip install facetpy[all]).The artifact length is set to half the median RR interval, centred on each detected R-peak.
- Parameters:
save_to_annotations (
bool, optional) – IfTrue, write detected QRS peaks back to the raw annotations (default: False).
- 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).
MissingTriggerDetector
- class facet.preprocessing.MissingTriggerDetector(add_to_context: bool = True, correlation_threshold: float = 0.9, search_window_factor: float = 0.1, ref_channel: int = 0)[source]
Bases:
ProcessorDetect and insert missing triggers by template matching.
Scans the trigger sequence for gaps larger than 1.9× the artifact length and attempts to locate missing artifact epochs by cross-correlating a reference template against the signal. Optionally extends the search one step before the first trigger and one step after the last.
- Parameters:
add_to_context (
bool, optional) – IfTrue, insert found triggers into metadata and annotations (default: True).correlation_threshold (
float, optional) – Minimum absolute Pearson correlation to accept a candidate trigger (default: 0.9).search_window_factor (
float, optional) – Search window as a fraction of artifact length (default: 0.1).ref_channel (
int, optional) – Reference channel index for template matching (default: 0).
- __init__(add_to_context: bool = True, correlation_threshold: float = 0.9, search_window_factor: float = 0.1, ref_channel: int = 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).
MissingTriggerCompleter
- class facet.preprocessing.MissingTriggerCompleter(volumes: int, slices: int, add_to_context: bool = True, add_annotations: bool = True, strict: bool = True)[source]
Bases:
ProcessorDeterministically complete missing triggers using volume/slice counts.
MATLAB FACET parity processor for
FindMissingTriggers(volumes, slices)based on theCompleteTriggersreconstruction heuristic.- Parameters:
volumes (
int) – Total number of fMRI volumes expected.slices (
int) – Number of slices per volume.add_to_context (
bool, optional) – IfTrue, replacemetadata.triggerswith the completed list (default: True).add_annotations (
bool, optional) – IfTrueand raw is available, add annotations for inserted triggers (default: True).strict (
bool, optional) – IfTrue, mismatches raiseProcessorValidationError. IfFalse, best-effort completion is used (default: True).
- __init__(volumes: int, slices: int, add_to_context: bool = True, add_annotations: bool = True, strict: bool = True) 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).
SliceTriggerGenerator
- class facet.preprocessing.SliceTriggerGenerator(slices: int, duration_samples: float | None = None, relative_position: float = 0.03, add_annotations: bool = False)[source]
Bases:
ProcessorGenerate slice triggers from volume triggers.
MATLAB FACET parity processor for
GenerateSliceTriggers.- Parameters:
slices (
int) – Number of slices per volume.duration_samples (
float, optional) – Slice duration in samples. IfNone, derived from trigger spacing.relative_position (
float) – Relative position of first slice trigger with respect to the volume trigger (default: 0.03).add_annotations (
bool, optional) – IfTrueand raw is available, generated triggers are added as annotations (default: False).
- __init__(slices: int, duration_samples: float | None = None, relative_position: float = 0.03, add_annotations: 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).
TriggerExplorer
- class facet.preprocessing.TriggerExplorer(mode: str = 'gui', auto_select: str | None = None, save_to_annotations: bool = False)[source]
Bases:
ProcessorInteractively explore and select trigger events from annotations or STIM channels.
Scans the loaded data for all available event sources (MNE annotations and STIM channels) and lets the user pick the correct trigger source. Three interaction modes are supported:
"gui"(default)Opens a matplotlib window with a downsampled preview of the first EEG channel. Radio buttons list every discovered event type; selecting one highlights the corresponding trigger positions on the waveform. A Confirm button finalises the choice. Falls back to
"terminal"automatically when no GUI backend is available."terminal"Prints a Rich table and prompts for a selection number in the terminal.
"auto"Alias for
"gui"— kept for backward compatibility.
When
auto_selectis provided, all interactive prompts are skipped and the first event matching the regex is chosen automatically — useful for scripted / non-interactive pipelines.- Parameters:
mode (
str, optional) – Interaction mode:"gui"(default),"terminal", or"auto".auto_select (
strorNone, optional) – If given, automatically select the event whose description matches this regex, bypassing any interactive prompt (default: None).save_to_annotations (
bool, optional) – IfTrue, write detected triggers back to the raw annotations (default: False).
- __init__(mode: str = 'gui', auto_select: str | None = None, save_to_annotations: 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).
InteractiveTriggerExplorer
- facet.preprocessing.InteractiveTriggerExplorer
alias of
TriggerExplorer
Alignment
TriggerAligner
- class facet.preprocessing.TriggerAligner(ref_trigger_index: int = 0, ref_channel: int | None = None, search_window: int | None = None, save_to_annotations: bool = False, upsample_for_alignment: bool = True)[source]
Bases:
ProcessorAlign triggers to artifact positions using cross-correlation.
Refines trigger positions by finding the lag that maximises cross- correlation with a reference artifact epoch. The search can optionally operate on temporarily upsampled data for sub-sample precision.
- Parameters:
ref_trigger_index (
int, optional) – Index of the reference trigger to use as template (default: 0).ref_channel (
int, optional) – Reference channel index. Uses the first EEG channel whenNone(default: None).search_window (
int, optional) – Search window in samples. Derived from the upsampling factor whenNone(default: None).save_to_annotations (
bool, optional) – IfTrue, save aligned triggers as raw annotations (default: False).upsample_for_alignment (
bool, optional) – Temporarily upsample data before alignment for sub-sample accuracy (default: True).
- __init__(ref_trigger_index: int = 0, ref_channel: int | None = None, search_window: int | None = None, save_to_annotations: bool = False, upsample_for_alignment: bool = True) 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).
SliceAligner
- class facet.preprocessing.SliceAligner(ref_trigger_index: int = 0, ref_channel: int | None = None, search_window: int | None = None, save_to_annotations: bool = False)[source]
Bases:
TriggerAlignerAlign slice triggers on already-upsampled data.
Identical to
TriggerAlignerbut skips the internal temporary upsampling step, assuming the data has already been upsampled upstream.- Parameters:
ref_trigger_index (
int, optional) – Index of the reference trigger (default: 0).ref_channel (
int, optional) – Reference channel index (default: None).search_window (
int, optional) – Search window in samples (default: None).save_to_annotations (
bool, optional) – Save aligned triggers as annotations (default: False).
SubsampleAligner
- class facet.preprocessing.SubsampleAligner(ref_trigger_index: int = 0, ref_channel: int | None = None, search_window: int | None = None, apply_to_raw: bool = False)[source]
Bases:
ProcessorRefine trigger positions at subsample precision after upsampling.
Mirrors the intent of the MATLAB RAAlignSubSample step. For each trigger a search segment is extracted, cross-correlated against a reference epoch, and the trigger is shifted by the lag that maximises the correlation.
When
apply_to_raw=Truethe corresponding raw data segments are also rolled by the computed shifts; otherwise only the trigger positions in metadata are updated.- Parameters:
ref_trigger_index (
int, optional) – Index of the reference trigger used as the alignment template (default: 0).ref_channel (
int, optional) – Reference channel index. Uses the first EEG channel whenNone(default: None).search_window (
int, optional) – Search radius in samples. Defaults to twice the upsampling factor.apply_to_raw (
bool, optional) – IfTrue, roll raw data segments by the computed shifts (default: False).
- __init__(ref_trigger_index: int = 0, ref_channel: int | None = None, search_window: int | None = None, apply_to_raw: 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).
Transforms
CutAcquisitionWindow
- class facet.preprocessing.CutAcquisitionWindow(pre_padding_samples: int | None = None, post_padding_samples: int | None = None)[source]
Bases:
ProcessorDerive acquisition window bounds similarly to MATLAB’s RACut step.
Records the acquisition start/end sample indices and the per-trigger pre/post sample counts in metadata so that downstream processors can operate on consistent artifact windows without accessing raw signal data directly.
- Parameters:
- __init__(pre_padding_samples: int | None = None, post_padding_samples: int | 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).
PasteAcquisitionWindow
- class facet.preprocessing.PasteAcquisitionWindow[source]
Bases:
ProcessorFinalize acquisition metadata and clear cached window segments.
FACETpy keeps the full-length raw data throughout the pipeline, so this processor ensures acquisition metadata is present and clears any cached segments set by
CutAcquisitionWindow.- 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).
Crop
- class facet.preprocessing.Crop(tmin: float | None = None, tmax: float | None = None)[source]
Bases:
ProcessorCrop the Raw recording to a time interval.
A concise alternative to
LambdaProcessorfor the common pattern of restricting the recording to a specific window before processing.- Parameters:
Examples
Crop(tmin=0, tmax=162) Crop() # open interactive selector
- 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).
MagicErasor
- class facet.preprocessing.MagicErasor(picks: str | list[str] = 'eeg', channel: str | int | None = None, default_mode: str = 'zero', random_seed: int | None = None)[source]
Bases:
ProcessorInteractively erase selected signal segments with configurable modes.
Opens an interactive matplotlib editor for one preview channel and lets the user select time segments repeatedly. Each selected segment can be replaced using one of four modes:
zero: set samples to zero.mean: set samples to the channel mean.interpolate: linearly interpolate between segment boundaries.generated_eeg: replace with synthetic EEG generated throughEEGGenerator, then adapt channel-wise mean and amplitude to the local surrounding signal.
The editor stays open until the user clicks Done, enabling multiple edits in a single session.
- Parameters:
picks (
strorlist[str], optional) – Channels to edit (default:"eeg").channel (
strorint, optional) – Channel used for preview in the interactive window. WhenNone, the first edited EEG channel is used.default_mode (
str, optional) – Initially selected editing mode (default:"zero").random_seed (
int, optional) – Optional seed used whengenerated_eegmode is applied.
- __init__(picks: str | list[str] = 'eeg', channel: str | int | None = None, default_mode: str = 'zero', random_seed: int | 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).
RawTransform
- class facet.preprocessing.RawTransform(name: str, func: Callable)[source]
Bases:
ProcessorApply an arbitrary callable to the Raw object.
A lighter-weight alternative to
LambdaProcessorwhen only the Raw object needs to be modified. The callable receives the current Raw object and must return a new (or modified copy of a) Raw object.- Parameters:
name (
str) – Human-readable label shown in pipeline logs and progress.func (
collections.abc.Callable) –Callable[[mne.io.Raw], mne.io.Raw]— receives the current Raw object, must return a (possibly new) Raw object.
Examples
# Drop bad channels inline RawTransform("drop_bad", lambda raw: raw.copy().pick_channels( [ch for ch in raw.ch_names if ch not in ["EKG", "EMG"]] )) # Set average reference RawTransform("set_eeg_ref", lambda raw: raw.copy().set_eeg_reference("average"))
- 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).
PickChannels
- class facet.preprocessing.PickChannels(picks: str | list[str], on_missing: str = 'ignore')[source]
Bases:
ProcessorKeep only the specified channels or channel types.
A named, reusable alternative to the common
lambda ctx: ctx.with_raw( ctx.get_raw().copy().pick(...))pattern.- Parameters:
picks (
strorlistofstr) – Channel type ("eeg","stim", …) or list of channel names / types accepted bymne.io.Raw.pick().on_missing (
str, optional) – Passed to MNE."ignore"(default) silently skips channels that are absent from the recording.
Examples
# Keep only EEG and stimulus channels PickChannels(picks=["eeg", "stim"]) # Keep specific channels by name PickChannels(picks=["Fp1", "Fp2", "Fz"])
- 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).
DropChannels
- class facet.preprocessing.DropChannels(channels: list[str], on_missing: str = 'ignore')[source]
Bases:
ProcessorRemove named channels from the recording.
A named, reusable alternative to the
lambda ctx: ...drop_channels(...)pattern commonly seen in inline pipeline steps.- Parameters:
Examples
# Drop typical non-EEG channels that may be present in EDF files DropChannels(channels=["EKG", "EMG", "EOG", "ECG"])
- 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).
ChannelStandardizer
- class facet.preprocessing.ChannelStandardizer(standard: str | list[str], on_missing: str = 'ignore', keep_auxiliary: bool = True, rename_aliases: bool = True)[source]
Bases:
ProcessorConvert EEG channel layouts to predefined standards or custom subsets.
Keeps EEG channels that match the requested standard in a deterministic order, optionally preserving non-EEG channels (e.g., trigger/stim channels). Legacy aliases such as
T3 -> T7andT5 -> P7are resolved automatically. When alias channels are used, they can be renamed to the target standard labels.- Parameters:
standard (
strorlist[str]) – Target standard identifier or explicit ordered channel list. Supported built-in identifiers: -"10-20"/"standard_1020_19"-"32"/"standard_1020_32"For other strings, the processor tries to load an MNE standard montage viamne.channels.make_standard_montage()and uses its channel list.on_missing (
str, optional) – Missing-channel behavior:"ignore"(default) keeps available matches only,"raise"fails when any requested channel is missing.keep_auxiliary (
bool, optional) – IfTrue(default), append non-EEG channels after the selected EEG subset.rename_aliases (
bool, optional) – IfTrue(default), rename selected alias channels to the requested target labels when possible (e.g.,T3becomesT7).
- __init__(standard: str | list[str], on_missing: str = 'ignore', keep_auxiliary: bool = True, rename_aliases: bool = True) 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).
PrintMetric
- class facet.preprocessing.PrintMetric(*metric_names: str, label: str | None = None)[source]
Bases:
ProcessorPrint one or more evaluation metric values — useful for debugging pipelines.
Inserts a transparent logging step that reads from the shared metrics dict populated by evaluation processors (e.g.
SNRCalculator). The context is returned unchanged.- Parameters:
Examples
pipeline = Pipeline([ ..., SNRCalculator(), PrintMetric("snr"), # → " snr=12.345" PCACorrection(...), SNRCalculator(), PrintMetric("snr", label="after PCA"), # → " [after PCA] snr=14.201" ])
- 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).
Diagnostics
AnalyzeDataReport
- class facet.preprocessing.AnalyzeDataReport[source]
Bases:
ProcessorGenerate a FACETpy-style data analysis summary.
This mirrors the purpose of MATLAB FACET
AnalyzeDatawhile keeping output in FACETpy’s structured metadata + concise logger format.The generated report is stored in
metadata.custom["analyze_data_report"].- 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).
CheckDataReport
- class facet.preprocessing.CheckDataReport(require_triggers: bool = True, strict: bool = True)[source]
Bases:
ProcessorRun FACETpy-style data checks and emit a structured report.
This mirrors MATLAB FACET
CheckDataintent and stores results inmetadata.custom["check_data_report"].- Parameters:
- 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).