meganorm.src package

Submodules

meganorm.src.featureExtraction module

class meganorm.src.featureExtraction.FOOOFDecomposer(fooof_model, mode, ch_num)[source]

Bases: SpectralDecomposer

Spectral decomposer wrapping a FOOOF model for a single channel.

Methods

get_aperiodic_params()

Return the aperiodic parameters for the channel's FOOOF fit.

get_peak_params(fmin, fmax)

Extract the dominant peak and all peaks within a frequency band from the FOOOF model's peak parameters.

get_periodic_spectrum(original_psds)

Compute the periodic component by subtracting the fitted aperiodic component (in log space) from the original PSD.

get_r_squared()

Return the R-squared value of the FOOOF model fit.

get_aperiodic_params()[source]

Return the aperiodic parameters for the channel’s FOOOF fit.

Returns:

[offset, exponent], with exponent taken from the correct index depending on mode.

Return type:

list

Raises:

ValueError – If mode is not ‘knee’ or ‘fixed’.

get_peak_params(fmin, fmax)[source]

Extract the dominant peak and all peaks within a frequency band from the FOOOF model’s peak parameters.

Parameters:
  • fmin (float) – Lower bound of the frequency band.

  • fmax (float) – Upper bound of the frequency band.

Returns:

  • dominant_peak (tuple or None) – (center frequency, power, width) of the peak with maximum power within the band, or None if no valid peak is found.

  • band_peaks (list of tuple or None) – All non-NaN peaks within the frequency band, or None if none are found.

get_periodic_spectrum(original_psds)[source]

Compute the periodic component by subtracting the fitted aperiodic component (in log space) from the original PSD.

Parameters:

original_psds (np.ndarray) – Original power spectral density values, shape (n_channels, n_freqs).

Returns:

Periodic power spectrum for the channel, shape (n_freqs,).

Return type:

np.ndarray

get_r_squared()[source]

Return the R-squared value of the FOOOF model fit.

Returns:

R-squared value.

Return type:

float

class meganorm.src.featureExtraction.PYRASADecomposer(model, mode, ch_name, ch_num, aperiodic)[source]

Bases: SpectralDecomposer

Spectral decomposer wrapping a PYRASA (IRASA) model for a single channel.

Methods

get_aperiodic_params()

Return the aperiodic parameters for the channel from the fitted aperiodic model.

get_peak_params(fmin, fmax)

Placeholder for peak parameter extraction (not implemented for PYRASA models).

get_periodic_spectrum([original_psds])

Return the periodic component of the spectrum for the channel as computed by PYRASA.

get_r_squared()

Return the R-squared value of the aperiodic fit for the channel.

get_aperiodic_params()[source]

Return the aperiodic parameters for the channel from the fitted aperiodic model.

Returns:

[offset, exponent_1, exponent_2] for the channel.

Return type:

list

get_peak_params(fmin, fmax)[source]

Placeholder for peak parameter extraction (not implemented for PYRASA models).

Parameters:
  • fmin (float) – Lower bound of the frequency band.

  • fmax (float) – Upper bound of the frequency band.

Return type:

None, None

get_periodic_spectrum(original_psds=None)[source]

Return the periodic component of the spectrum for the channel as computed by PYRASA.

Parameters:

original_psds (np.ndarray, optional) – Unused; present for interface compatibility.

Returns:

Periodic power spectrum for the channel, shape (n_freqs,).

Return type:

np.ndarray

get_r_squared()[source]

Return the R-squared value of the aperiodic fit for the channel.

Returns:

R-squared value.

Return type:

float

class meganorm.src.featureExtraction.SpectralDecomposer[source]

Bases: ABC

Abstract base class for spectral decomposition methods.

Methods

get_aperiodic_params()

Return the fitted aperiodic parameters.

get_peak_params(fmin, fmax)

Return peak parameters within a given frequency range.

get_periodic_spectrum(original_psds)

Isolate the periodic component of the power spectrum by removing the fitted aperiodic component.

get_r_squared()

Return the goodness-of-fit metric for the spectral model.

abstractmethod get_aperiodic_params()[source]

Return the fitted aperiodic parameters.

Returns:

Aperiodic parameters in the order [offset, exponent] for ‘fixed’ mode, or [offset, exponent_1, exponent_2] for ‘knee’ mode.

Return type:

list

abstractmethod get_peak_params(fmin, fmax)[source]

Return peak parameters within a given frequency range.

Parameters:
  • fmin (float) – Lower bound of the frequency range.

  • fmax (float) – Upper bound of the frequency range.

Returns:

  • dominant_peak (tuple or None) – Parameters (center frequency, power, width) of the dominant peak in the range, or None if no peak is found.

  • band_peaks (list of tuple or None) – All peaks found within the frequency range, or None if none are found.

abstractmethod get_periodic_spectrum(original_psds)[source]

Isolate the periodic component of the power spectrum by removing the fitted aperiodic component.

Parameters:

original_psds (np.ndarray) – Original power spectral density values, shape (n_channels, n_freqs).

Returns:

Periodic (flattened) power spectrum for the current channel, shape (n_freqs,).

Return type:

np.ndarray

abstractmethod get_r_squared()[source]

Return the goodness-of-fit metric for the spectral model.

Returns:

R-squared value of the model fit.

Return type:

float

meganorm.src.featureExtraction.abs_canonical_power(psd, freqs, fmin, fmax)[source]

Calculates absolute canonical power of a frequency band from a power spectrum density (PSD).

Parameters:
  • psd (np.ndarray) – Power spectral density values (in linear scale).

  • freqs (np.ndarray) – A 1D array of frequency values that were used to compute the PSD.

  • fmin (Union[int, float]) – Lower bound of the frequency band

  • fmax (Union[int, float]) – Upper bound of the frequency band.

Returns:

Log-transformed absolute power in the specified frequency band.

Return type:

float

Notes

‘psd’ can be both original PSD or periodic PSD.

meganorm.src.featureExtraction.abs_individual_power(psd, freqs, band_peaks, individualized_band_ranges, band_name)[source]

Calculates absolute power in an individualized frequency band centered around the dominant peak.

Parameters:
  • psd (np.ndarray) – Power spectral density values (in linear scale).

  • freqs (np.ndarray) – A 1D array of frequency values that were used to compute the PSD.

  • band_peaks (list) – List of peak tuples (frequency, power, width).

  • individualized_band_ranges (dict) – Dictionary mapping band names to (lower_offset, upper_offset) in Hz.

  • band_name (str) – Name of the frequency band to compute power for.

Returns:

Log-transformed absolute power in the individualized frequency band. Returns np.nan if no peaks are found.

Return type:

float

Notes

‘psd’ can be both original PSD or periodic PSD.

meganorm.src.featureExtraction.add_feature(feature_container, feature_arr, feature_name, channel_name, band_name)[source]

Add a feature value to the feature container for a specific channel and frequency band.

This function appends a feature to a DataFrame by assigning a value (e.g., from an array) to a row labeled with the combined feature and band name, and a column labeled with the channel name.

Parameters:
  • feature_container (pd.DataFrame) – DataFrame used to store features, where rows represent feature names and columns represent channels.

  • feature_arr (np.ndarray) – Array containing the feature value(s) to add.

  • feature_name (str) – Name of the feature (e.g., ‘RelativePower_’).

  • channel_name (str) – Name of the channel (e.g., ‘MEG0121’) to which the feature value should be assigned.

  • band_name (str) – Frequency band to append to the feature name (e.g., ‘Alpha’).

Returns:

Updated DataFrame with the new feature added.

Return type:

pd.DataFrame

meganorm.src.featureExtraction.band_power_ratio(psd, freqs, fmin_num, fmax_num, fmin_den, fmax_den)[source]

Calculates the log ratio of power between two frequency bands.

Parameters:
  • psd (np.ndarray) – Power spectral density values (linear scale).

  • freqs (np.ndarray) – Frequency values corresponding to the PSD.

  • fmin_num (float) – Frequency bounds for the numerator band.

  • fmax_num (float) – Frequency bounds for the numerator band.

  • fmin_den (float) – Frequency bounds for the denominator band.

  • fmax_den (float) – Frequency bounds for the denominator band.

Returns:

log10(power_numerator / power_denominator), or np.nan if denominator is zero.

Return type:

float

meganorm.src.featureExtraction.compute_hemispheric_asymmetry(final_df, base_features=None)[source]

Computes hemispheric asymmetry indices between left and right hemisphere channels.

For each base feature, finds matching left/right hemisphere column pairs (identified by ‘_lh_’ and ‘_rh_’ in column names) and computes their difference as an asymmetry index.

Parameters:
  • final_df (pd.DataFrame) – Flattened feature DataFrame with columns named in the format ‘{feature}__{band}__{channel}’.

  • base_features (List[str], optional) – List of feature name prefixes to compute asymmetry for. Defaults to [“Adjusted_Canonical_Absolute_Power”, “OriginalPSD_Canonical_Absolute_Power”].

Returns:

Input DataFrame with additional asymmetry columns appended. New columns are named with ‘Hemispheric_Asymmetry__{base_feat}’ and ‘_lh_vs_rh_’.

Return type:

pd.DataFrame

meganorm.src.featureExtraction.create_feature_container(feature_categories, freq_bands, channel_names, BAND_RATIOS=None)[source]

Creates a DataFrame to store features for each channel, with feature names corresponding to the specified categories and frequency bands.

Parameters:
  • feature_categories (dict) – Dictionary with feature names as keys and booleans indicating whether the feature should be calculated.

  • freq_bands (dict) – Dictionary of frequency bands (e.g., {‘Theta’: (4, 8), ‘Alpha’: (8, 12)}).

  • channel_names (list) – List of channel names (e.g., [‘ch1’, ‘ch2’, ‘ch3’]).

Returns:

A DataFrame with feature names as rows and channels as columns.

Return type:

pd.DataFrame

meganorm.src.featureExtraction.feature_extract(subject_id, spectral_models, psds, feature_categories, freqs, freq_bands, channel_names, individualized_band_ranges, device, which_layout, which_sensor, aperiodic_mode, min_r_squared, power_band_ratios_list)[source]

Extract features from FOOOF models for each channel and frequency band.

This function computes various features from FOOOF models for each channel, based on specified frequency bands. Features such as offset, exponent, peak characteristics, and canonical power are calculated and stored in a DataFrame.

Parameters:
  • subject_id (str) – The unique identifier for the subject whose data is being processed.

  • spectral_models – Group of FOOOF models or PYRASA models, where each model corresponds to a channel and its power spectral data.

  • psds (np.ndarray) – Original power spectral density values, with shape (n_channels, n_freqs).

  • feature_categories (Dict[str, bool]) – A dictionary where keys are feature names (e.g., ‘Offset’, ‘Exponent’) and values are booleans indicating whether to compute the feature.

  • freqs (np.ndarray) – Frequency values corresponding to the power values in the psds array.

  • freq_bands (Dict[str, tuple]) – Dictionary mapping frequency band names (e.g., ‘Alpha’, ‘Beta’) to their corresponding frequency ranges (min_freq, max_freq).

  • channel_names (List[str]) – List of channel names corresponding to the rows of the psds array.

  • individualized_band_ranges (Dict[str, tuple]) – A dictionary mapping band names to individualized frequency ranges, which may differ across subjects or datasets.

  • device (str) – The device of the subject’s recording (e.g., ‘FIF’, ‘DS’). Used to read the appropriate layout file from the layout directory.

  • which_layout (str) – Specifies the sensor layout for feature averaging, either ‘all’ for global averaging or ‘lobe’ for averaging within lobes.

  • which_sensor (Dict[str, bool]) – A dictionary indicating which modalities (e.g., ‘meg’, ‘eeg’) should be included in the feature extraction.

  • aperiodic_mode (str) – Defines the aperiodic component fitting mode for FOOOF. Options are ‘knee’ or ‘fixed’.

  • min_r_squared (float) – Minimum acceptable R-squared value for FOOOF model fitting. Channels with R-squared values below this threshold are excluded.

  • power_band_ratios_list (List[tuple]) – List of ratio specifications (each exposing numerator and denominator band names) for which band-power ratio features should be computed.

Returns:

A DataFrame with features extracted for each channel and frequency band. The DataFrame has features as rows and channels (and frequency bands) as columns.

Return type:

pd.DataFrame

Raises:
  • ValueError – If aperiodic_mode is not ‘knee’ or ‘fixed’.

  • TypeError – If spectral_models is not an instance of f.FOOOF or pyrasa.irasa_mne.mne_objs.IrasaEpoched.

meganorm.src.featureExtraction.rel_canonical_power(psd, freqs, fmin, fmax)[source]

Calculates relative canonical power of a frequency band from a power spectrum density.

Parameters:
  • psd (np.ndarray) – Power spectral density values (in linear scale).

  • freqs (np.ndarray) – A 1D array of frequency values that were used to compute the PSD.

  • fmin (Union[int, float]) – Lower bound of the frequency band.

  • fmax (Union[int, float]) – Upper bound of the frequency band.

Returns:

Relative power in the specified frequency band. Returns np.nan if total power is zero.

Return type:

float

Notes

‘psd’ can be both original PSD or periodic PSD.

meganorm.src.featureExtraction.rel_individual_power(psd, freqs, band_peaks, individualized_band_ranges, band_name)[source]

Calculates relative power in an individualized frequency band centered around the dominant peak.

Parameters:
  • psd (np.ndarray) – Power spectral density values (in linear scale).

  • freqs (list) – List of peak tuples (frequency, power, width)

  • band_peaks (list) – List of peak tuples (frequency, power, width)

  • individualized_band_ranges (dict) – Dictionary mapping band names to (lower_offset, upper_offset) in Hz.

  • band_name (str) – Name of the frequency band to compute power for.

Returns:

Relative power in the individualized frequency band. Returns np.nan if total power is zero or input is invalid.

Return type:

float

Notes

‘psd’ can be both original PSD or periodic PSD.

meganorm.src.featureExtraction.summarizeFeatures(df, device, which_layout, which_sensor)[source]

Summarizes a feature DataFrame by averaging channels based on a specified sensor layout.

Since sensor positions may differ across datasets recorded with different MEG hardware systems, this function enables consistent feature extraction by averaging signals across the whole brain or predefined brain regions (e.g., lobes).

The function computes the mean of selected channels (e.g., MEG, EEG) according to a layout specified in a JSON file. The layout file is selected based on the recording device (e.g., ‘FIF’, ‘DS’) and contains channel groupings for either whole-brain or regional (lobe-level) parcellation.

Example layout for regional parcellation:
“FIF_MEG_LOBE”: {

“MAG_frontal_left”: [“MEG0121”, “MEG0341”, “MEG0311”, “MEG0321”, …], “MAG_frontal_right”: [“MEG1411”, “MEG1221”, “MEG1211”, “MEG1231”, …]

}

Example layout for whole-brain averaging:
“FIF_MAG_ALL”: {

“MAG_ALL”: [“MEG0121”, “MEG0341”, “MEG0311”, …]

}

Layout files must be stored in a dedicated layout directory and named based on the recording device (e.g., ‘FIF.json’). The appropriate key in the JSON (e.g., ‘FIF_MEG_LOBE’) is constructed using device, which_layout, and which_sensor.

Parameters:
  • df (pd.DataFrame) – A DataFrame where each column represents a channel and each row a sample (subject or epoch).

  • device (str) – The recording file type (e.g., ‘FIF’, ‘DS’). Used to locate the correct layout file.

  • which_layout (str) – Layout type to use: ‘all’ for global averaging or ‘lobe’ for region-based averaging.

  • which_sensor (dict) – Dictionary indicating which sensor modalities to include (e.g., {‘meg’: True, ‘eeg’: False}).

Returns:

A new DataFrame where columns represent averaged parcels and rows represent samples.

Return type:

pd.DataFrame

meganorm.src.mainParallel module

meganorm.src.mainParallel.main(args)[source]

Run the full spectral feature extraction pipeline for one subject.

Loads raw MEG/EEG/OPM data and processes it end-to-end: channel cleanup, filtering, ICA/GEDAI and environmental noise correction, head-movement correction, segmentation with optional Autoreject bad-segment removal, optional source localization, PSD computation with FOOOF/IRASA spectral parametrization, and band-power feature extraction. Extracted features are saved to a per-subject CSV.

Parameters:

args (list of str) – Raw command-line arguments (typically sys.argv[1:]), parsed via main_argparser. See that function for full argument details.

Return type:

None

Notes

  • Device is inferred from the file path/extension (BTI/4D, CTF, or MEGIN/fif); only one matched session is used even if the glob pattern resolves multiple recordings.

  • Line frequency comes from recording metadata, then –line_freq, defaulting to 60 Hz.

meganorm.src.mainParallel.main_argparser(args=None)[source]

Build and parse command-line arguments for the feature extraction script.

Defines the positional and optional arguments needed to run a single subject through the preprocessing, source localization, and spectral feature extraction pipeline, and parses them into a namespace.

Parameters:

args (list of str or None, optional) – List of argument strings to parse. If None, arguments are read from sys.argv (default behavior for command-line invocation).

Returns:

Namespace containing the parsed arguments:

dirstr

Path to the subject’s raw data. May contain a glob pattern (using “*” as a separator) when multiple recordings/sessions are present; the session used is selected via configs.which_meg_session.

save_dirstr

Directory where extracted features (and, depending on config, logs, PSDs, and source-localized epochs) will be saved.

subjectstr

Subject/participant identifier, used for file naming, logging, and locating subject-specific FreeSurfer data.

configsstr

Path to a JSON file (loadable via Config.load) specifying preprocessing, segmentation, source localization, PSD, and feature extraction parameters.

line_freqint or str, default=60

Power line frequency (Hz) used for notch filtering if it cannot be auto-detected from the recording. Pass the string “None” to disable an explicit override.

surfaces_dirstr or None, default=None

Path to the FreeSurfer subjects directory, required when apply_source_localization is enabled in the config (unless an MRI template is used).

empty_room_recording_pathstr or None, default=None

Path to the subject’s empty-room recording, used for noise pre-whitening. May contain a glob pattern. Particularly relevant when source localization is applied to recordings with both magnetometers and gradiometers.

event_recordstr or None, default=None

Path to the event file for this subject, resolved via glob if a pattern is provided. Used together with event_of_interest to extract epochs around specific events.

event_of_intereststr or None, default=None

Event ID to extract epochs around (e.g. “16”). Only used if event_record is also provided.

Return type:

argparse.Namespace

Notes

Several optional arguments accept the literal string “None” as a way to explicitly disable a default from the command line; main converts these strings to Python None after parsing.

meganorm.src.mainParallel.set_logger(args, pakcages_to_silent)[source]

Configure a per-subject file logger and silence noisy dependencies.

Removes any existing root logging handlers, then configures logging to write INFO-level (and above) messages to a subject-specific log file, while restricting specified third-party packages to WARNING level to reduce log verbosity from dependencies like MNE.

Parameters:
  • args (argparse.Namespace) –

    Parsed arguments (as returned by main_argparser), of which this function uses:

    save_dirstr

    Base output directory. The log file is written to <parent of save_dir>/Saved_outputs/log_summary/.

    subjectstr

    Subject identifier, used to name the log file as subject_<subject>_report.log.

  • pakcages_to_silent (list of str) – Names of logging namespaces (typically third-party package names, e.g. “mne”, “numexpr”, “dipy”) whose log level should be raised to WARNING so their INFO/DEBUG messages are suppressed.

Returns:

A logger for the current module (__name__), writing to the configured subject-specific log file in write mode (overwriting any prior log for the same subject).

Return type:

logging.Logger

Notes

The log directory is created if it does not already exist. Because root handlers are cleared before reconfiguration, calling this function more than once per process will reset logging for the whole run, not just for this module.

meganorm.src.preprocess module

meganorm.src.preprocess.AutoIca_with_IcaLabel(data, physiological_noise_type, n_components=30, ica_max_iter=1000, IcaMethod='infomax', iclabel_thr=0.8)[source]
meganorm.src.preprocess.annotate_noisy_raw(raw, reject=None, flat=None, window=1.0, step=0.5)[source]

Annotate noisy or flat segments of raw data using a sliding-window peak-to-peak amplitude criterion.

Slides a fixed-length window across the recording and flags windows where any channel’s peak-to-peak amplitude exceeds a rejection threshold (‘BAD_peak’) or falls below a flatness threshold (‘BAD_flat’), separately for each specified channel type.

Parameters:
  • raw (mne.io.Raw) – Raw MEG/EEG data to scan for artifacts.

  • reject (dict or None, optional) – Peak-to-peak amplitude rejection thresholds per channel type (e.g., {‘mag’: 5000e-15, ‘eeg’: 40e-6}). If None, peak rejection is skipped.

  • flat (dict or None, optional) – Peak-to-peak amplitude flatness thresholds per channel type. If None, flatness rejection is skipped.

  • window (float, optional) – Window length in seconds used to evaluate each segment. Default is 1.0.

  • step (float, optional) – Step size in seconds between successive windows. Default is 0.5.

Returns:

Annotations marking ‘BAD_peak’ and ‘BAD_flat’ segments. Empty if both reject and flat are None.

Return type:

mne.Annotations

meganorm.src.preprocess.apply_auto_ica_pipeline(data, channel_types, which_sensor, n_component, ica_max_iter, IcaMethod, auto_ica_corr_thr)[source]

Apply ICA automatically depending on available physiological channels and sensor types (MEG / EEG).

Parameters:
  • data (mne.raw) – mne.raw data.

  • channel_types (list of str) – List of channel type names present in the data (e.g., ["eeg", "ecg", "eog"]).

  • which_sensor (dict) – Dictionary specifying available sensor modalities.

  • n_component (int) – Number of ICA components to compute.

  • ica_max_iter (int) – Maximum number of iterations for ICA convergence.

  • IcaMethod (str) – ICA algorithm to use (e.g., "fastica", "picard").

  • auto_ica_corr_thr (float) – Threshold used for correlation-based artifact detection or ICLabel classification.

Returns:

  • data (object) – The input data after automatic ICA artifact removal.

  • number_of_reduced_ic (int) – Total number of ICA components identified and removed.

meganorm.src.preprocess.apply_chpi(meg_data, movement_limit, head_pos_save_path, device)[source]

Estimate and save continuous head position from cHPI coils.

Computes cHPI coil amplitudes and locations (using the appropriate method for MEGIN vs. CTF systems), derives head position over time, annotates excessive movement relative to movement_limit, and writes the head position estimates to disk.

Parameters:
  • meg_data (mne.io.Raw) – Raw MEG data containing cHPI coil information.

  • movement_limit (float) – Mean distance limit (in meters) used to annotate periods of excessive head movement.

  • head_pos_save_path (str) – Path where the computed head position data will be written.

  • device ({"fif", "ds"}) – Recording system type, used to select the appropriate cHPI location extraction method.

Return type:

None

meganorm.src.preprocess.apply_gradient_comp(ctf_meg_data, empty_room_recording=None, grade=3)[source]

Interpolate bad channels and apply gradient compensation to CTF MEG data.

This function first interpolates bad MEG channels using the minimum norm method to improve signal quality, then applies CTF-style gradient compensation at the specified grade level. Gradient compensation is specific to CTF MEG systems and helps remove interference from distant sources.

Parameters:
  • ctf_meg_data (mne.io.Raw) – The raw MEG data object (from a CTF system), loaded with preload=True. Must contain CTF-specific gradient compensation information.

  • grade (int, optional) – The gradient compensation level to apply. Valid values typically include: -1 (disable), 0 (raw data), 1, 2, 3 (increasing levels of compensation). Default is 3.

Returns:

ctf_meg_data – The same Raw object with interpolated bad channels and gradient compensation applied.

Return type:

mne.io.Raw

Notes

  • Only the minimum norm method (method={“meg”: “MNE”}) is used for interpolation, which is currently the only supported method for MEG in MNE.

  • Bad channels are not reset after interpolation (reset_bads=False) so that they remain marked in the data structure.

  • This function assumes that the input data is from a CTF MEG system.

See also

mne.io.Raw.interpolate_bads

Interpolate bad channels in MEG/EEG data.

mne.io.Raw.apply_gradient_compensation

Apply gradient compensation to CTF MEG data.

meganorm.src.preprocess.apply_tsss(data, cross_talk_path, calibration_path, head_pos_path=None, empty_room_record=None, st_duration=10.0, st_correlation=0.98)[source]

Apply temporal Signal Space Separation (tSSS) to MEG data with optional head position correction and empty-room noise processing.

This function uses MNE-Python’s Maxwell filtering implementation to suppress environmental noise and remove cross-talk between sensors. If a head position file is provided, movement compensation will be applied. Optionally, an empty-room recording can be processed with the same parameters for noise estimation.

Parameters:
  • data (mne.io.Raw) – Raw MEG data to be processed.

  • cross_talk_path (str or path-like) – Path to the cross-talk compensation file (CTF), typically provided by the MEG system.

  • calibration_path (str or path-like) – Path to the fine-calibration file (CAL), typically provided by the MEG system.

  • head_pos_path (str or path-like, optional) – Path to the head position file (.pos) obtained from cHPI processing. If provided, movement compensation will be applied.

  • empty_room_record (mne.io.Raw, optional) – Raw empty-room MEG recording to process for noise estimation. If provided, it will be Maxwell filtered with the same parameters as the main data.

  • st_duration (float, default=10.0) – Window duration in seconds for the temporal SSS (tSSS) projection. Shorter windows can better track non-stationary interference but may remove more brain signal.

  • st_correlation (float, default=0.98) – Correlation limit between SSS basis functions across time windows. Values closer to 1.0 remove less brain signal but may be less effective at removing artifacts.

Returns:

  • data_tsss (mne.io.Raw) – The Maxwell-filtered MEG data with optional movement compensation.

  • empty_room_record (mne.io.Raw or None) – The Maxwell-filtered empty-room recording if provided, else None.

Notes

  • Maxwell filtering is sensitive to accurate calibration and cross-talk compensation files; ensure the provided files match the MEG system used for the recording.

  • The st_duration and st_correlation parameters control the aggressiveness of the temporal projection; inappropriate values can either leave environmental noise in the data or attenuate brain signal.

  • If head_pos_path is provided, continuous head position data will be used to apply movement compensation during filtering.

References

[1]

Taulu, S., Simola, J. (2006). Spatiotemporal signal space separation method for rejecting nearby interference in MEG measurements. Physics in Medicine and Biology, 51(7), 1759.

meganorm.src.preprocess.auto_ica_with_corr(data, physiological_sensor, n_components=30, ica_max_iter=1000, IcaMethod='fastica', which_sensor={'eeg': True, 'meg': True}, auto_ica_corr_thr=0.9)[source]

Performs automated ICA for artifact removal by identifying components that correlate highly with physiological signals (ECG or EOG) which is determined by ‘auto_ica_corr_thr’.

Parameters:
  • data (mne.io.Raw) – Raw MEG/EEG data.

  • physiological_sensor (str) – Name of the physiological sensor (‘ecg’ or ‘eog’).

  • n_components (int or float) – Number of ICA components to retain.

  • ica_max_iter (int) – Maximum number of iterations for the ICA algorithm.

  • IcaMethod (str) – ICA algorithm to use (e.g., ‘fastica’, ‘picard’, ‘infomax’).

  • which_sensor (dict) – Dictionary indicating sensor types to include (e.g., {‘meg’: True, ‘eeg’: True}).

  • auto_ica_corr_thr (float) – Threshold for accepting independent component as noisy based on correlation with the corresponding physiological recording (ECG or EOG).

Returns:

  • data (mne.io.Raw) – Raw data with bad ICA components removed (in-place modification).

  • ICA_flag (bool) – True if no bad components were found, False otherwise.

meganorm.src.preprocess.auto_ica_with_mean(data, n_components=30, ica_max_iter=1000, IcaMethod='fastica', which_sensor={'eeg': True, 'meg': True}, auto_ica_corr_thr=0.9)[source]

Performs ICA-based artifact rejection using MNE’s built-in ECG correlation method. This function creates a synthetic ECG signal (by avergaing across magnetometers or Gradiometers) and use it to find and remove the noisy independent component.

Parameters:
  • data (mne.io.Raw) – Raw MEG/EEG data.

  • n_components (int, optional) – Number of ICA components to retain, by default 30.

  • ica_max_iter (int, optional) – Maximum number of iterations for the ICA algorithm, by default 1000.

  • IcaMethod (str, optional) – ICA algorithm to use (e.g., ‘fastica’, ‘picard’, ‘infomax’), by default “fastica”.

  • which_sensor (dict, optional) – Dictionary specifying sensor types to include (e.g., {“meg”: True, “eeg”: True}), by default {“meg”: True, “eeg”: True}.

  • auto_ica_corr_thr (float, optional) – Correlation threshold for detecting ECG-related components, by default 0.9.

Returns:

Raw data with ECG-related ICA components removed.

Return type:

mne.io.Raw

meganorm.src.preprocess.auto_reject_segmentation(raw, sampling_rate, tmin=20, tmax=-20, segments_length=10, overlap=0, ica_if_reject_by_annotation=True, n_interpolates=array([1, 4, 8, 16, 32]), consensus_percs=array([0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.]), cv='auto', thresh_method='bayesian_optimization', random_state=42, segment_events=None)[source]

Segment continuous data into fixed-length epochs and clean them using AutoReject.

Crops the raw data (or uses precomputed segment events), builds fixed-length epochs, and fits AutoReject to automatically interpolate or reject noisy epochs.

Parameters:
  • raw (mne.io.Raw) – Continuous MEG/EEG recording.

  • sampling_rate (float) – Sampling rate of the data in Hz.

  • tmin (float, optional) – Start time (in seconds) for cropping the raw data when segment_events is None. Default is 20.

  • tmax (float, optional) – End time offset (in seconds, must be negative) from the end of the recording, used for cropping when segment_events is None. Default is -20.

  • segments_length (float, optional) – Length of each epoch in seconds. Default is 10.

  • overlap (float, optional) – Overlap between successive fixed-length events in seconds. Default is 0.

  • ica_if_reject_by_annotation (bool, optional) – Whether to reject data by annotation when building epochs. Default is True.

  • n_interpolates (ndarray, optional) – Candidate numbers of channels to interpolate, passed to AutoReject. Default is [1, 4, 8, 16, 32].

  • consensus_percs (ndarray, optional) – Candidate consensus percentages, passed to AutoReject. Default is np.linspace(0, 1.0, 11).

  • cv (int or "auto", optional) – Number of cross-validation folds for AutoReject. If “auto”, set based on the number of epochs (clamped between 2 and 10). Default is “auto”.

  • thresh_method (str, optional) – Threshold optimization method used by AutoReject. Default is “bayesian_optimization”.

  • random_state (int, optional) – Random seed for AutoReject. Default is 42.

  • segment_events (ndarray or None, optional) – Precomputed MNE-style events array defining epoch onsets. If provided, tmin/tmax cropping is skipped.

Returns:

  • epochs_clean (mne.Epochs) – Epochs after AutoReject interpolation/rejection.

  • reject_log (autoreject.RejectLog) – Log describing which epochs/channels were interpolated or dropped.

Raises:

ValueError – If tmax is not negative, if no epochs could be created, or if fewer than 3 epochs are available for AutoReject.

meganorm.src.preprocess.drop_mag_or_grad(data, empty_room_recording, which_sensor)[source]

Drop either magnetometer or gradiometer channels, keeping only one MEG channel type.

If which_sensor[‘grad’] is True, magnetometer channels are dropped; if which_sensor[‘mag’] is True, gradiometer channels are dropped. Applied to both data and, if provided, empty_room_recording.

Parameters:
  • data (mne.io.Raw) – Raw MEG data containing both magnetometer and gradiometer channels.

  • empty_room_recording (mne.io.Raw or None) – Corresponding empty-room recording, or None.

  • which_sensor (dict) – Dictionary indicating which single MEG channel type to retain via keys ‘mag’ and ‘grad’.

Returns:

  • data (mne.io.Raw) – Data with the unwanted MEG channel type removed.

  • empty_room_recording (mne.io.Raw or None) – Empty-room recording with the same channels removed, or None if not provided.

meganorm.src.preprocess.drop_noisy_meg_channels(data, subID, args, device, which_sensor, empty_room_recording=None)[source]

Identifies and removes noisy or flat MEG/EEG channels using Maxwell filtering, and logs the number of dropped channels for each subject.

Parameters:
  • data (instance of mne.io.Raw) – The MEG/EEG recording to process.

  • subID (str) – Identifier for the subject, used in naming the log file.

  • args (argparse.Namespace or similar) – Object containing runtime arguments, including ‘saveDir’.

  • which_sensor (dict) –

    Configuration dictionary containing:
    • ’which_sensor’: one of {“meg”, “mag”, “grad”, “eeg”, “opm”}

  • empty_room_recording (instance of mne.io.Raw) – Empty room recording.

  • device (str)

Returns:

data_cleaned – The cleaned data with noisy/flat channels removed.

Return type:

instance of mne.io.Raw

Notes

If Maxwell filtering has already been applied (e.g., SSS step), the function will skip bad channel detection and proceed to drop previously marked bad channels.

The number of dropped channels is saved to a JSON log file in a directory derived from args.saveDir, replacing ‘temp’ with ‘log_droped_channels’.

meganorm.src.preprocess.drop_noisy_segments(segments, z_thr)[source]

Drop noisy data segments based on the z-scored standard deviation across time.

This function computes the standard deviation of each segment across the time axis, converts these values to z-scores, and removes segments whose z-score exceeds a given threshold. This is useful for discarding artifacts or unusually high-variance data before further processing.

Parameters:
  • segments (mne.Epochs or mne.Epochs-like) – The segmented MEG/EEG data object. Must have an attribute _data of shape (n_segments, n_channels, n_times) and a drop(indices) method to remove segments.

  • z_thr (float) – The z-score threshold. Segments with a standard deviation z-score greater than this value will be dropped.

Returns:

segments – The input object with noisy segments removed.

Return type:

mne.Epochs or mne.Epochs-like

Notes

  • This method assumes that noise manifests as abnormally high variance in one or more channels of a segment.

  • Z-scores are computed per channel across all segments, so segments may be flagged for removal if any channel exceeds the threshold.

  • The function logs the number of dropped segments and the remaining count.

meganorm.src.preprocess.extract_rs_blocks(raw, events, rs_id, sampling_rate, segments_length, overlap, seg_event_id=1)[source]

Extract and concatenate resting-state blocks from continuous data and generate fixed-length segment events within them.

Identifies contiguous blocks bounded by events matching rs_id, discards blocks shorter than segments_length, concatenates the retained blocks, and generates a new fixed-length events array (with overlap) within each retained block.

Parameters:
  • raw (mne.io.Raw) – Continuous MEG/EEG recording.

  • events (ndarray, shape (n_events, 3)) – MNE-style events array marking block boundaries.

  • rs_id (int) – Event ID marking the start of a resting-state block of interest.

  • sampling_rate (float) – Sampling rate of the data in Hz.

  • segments_length (float) – Desired length of each output segment, in seconds. Blocks shorter than this are discarded.

  • overlap (float) – Overlap between successive segments within a block, in seconds.

  • seg_event_id (int, optional) – Event ID to assign to the generated segment events. Default is 1.

Returns:

  • rs_raw (mne.io.Raw) – Concatenated raw data containing only the retained resting-state blocks.

  • seg_events (ndarray, shape (n_segments, 3)) – MNE-style events array marking fixed-length segment onsets within rs_raw.

meganorm.src.preprocess.find_ica_component(ica, data, physiological_signal, auto_ica_corr_thr)[source]

Identifies independent components that their correlation with physiological signals (ECG or EOG) is higher than a threshold.

Parameters:
  • ica (object) – The fitted ICA object using MNE.

  • data (mne.io.Raw) – The raw MEG/EEG data used to extract independent components.

  • physiological_signal (np.ndarray) – The physiological signal (ECG or EOG) to compare with independent componentss.

  • auto_ica_corr_thr (float) – Pearson correlation threshold (between 0 and 1) for accepting a component as noise.

Returns:

Index of the component with the highest correlation if it exceeds the threshold. Returns an empty list if no component meets the criterion.

Return type:

list

meganorm.src.preprocess.find_ref_meg_artifact(data, environmental_noise_ica_with_ref_meg_thr, ica_if_reject_by_annotation=True, environmental_noise_ica_with_ref_meg_method='together', environmental_noise_ica_with_ref_meg_measure='zscore')[source]

Identify and remove environmental-noise ICA components using reference MEG channels.

Fits ICA jointly on MEG and reference-MEG channels (or separately, depending on environmental_noise_ica_with_ref_meg_method) and uses ICA.find_bads_ref to detect components correlated with reference-channel activity.

Parameters:
  • data (mne.io.Raw) – Raw MEG data containing reference MEG channels.

  • environmental_noise_ica_with_ref_meg_thr (float) – Threshold passed to find_bads_ref for flagging bad components.

  • ica_if_reject_by_annotation (bool, optional) – Whether to reject data by annotation during ICA fitting. Default is True.

  • environmental_noise_ica_with_ref_meg_method ({"together", "separate"}, optional) – If “together”, ICA is fit jointly on MEG and reference channels. If “separate”, a separate ICA is fit on reference channels and its sources are added to the data before artifact detection. Default is “together”.

  • environmental_noise_ica_with_ref_meg_measure (str, optional) – Scoring measure used by find_bads_ref. Default is “zscore”.

Returns:

  • data (mne.io.Raw) – Data with identified environmental-noise components removed.

  • bad_comps (list of int) – Indices of ICA components excluded as environmental noise.

  • scores (ndarray) – Scores computed by find_bads_ref for each component.

meganorm.src.preprocess.gedai_preprocess(data, subject, freesurfer_dir, which_sensor_dict, gedai_method='both', sensai_method='optimize', conductivity=(0.3,), source_space='volumetric', gedai_duration=None, gedai_overlap=0.5, gedai_preliminary_broadband_noise_multiplier=6.0, gedai_noise_multiplier=3.0, gedai_wavelet_type='haar', gedai_wavelet_level='auto', gedai_wavelet_low_cutoff=None, gedai_epoch_size_in_cycles=12, gedai_highpass_cutoff=0.1, source_space_spacing='ico4', source_space_spacing_number=4, plot=False)[source]

Preprocess MEG/EEG data using GEDAI artifact removal.

Performs coregistration, computes a forward solution, and applies GEDAI artifact suppression separately for each sensor type (magnetometers, gradiometers, EEG). Non-MEG/EEG channels are preserved and recombined in the output.

Parameters:
  • data (mne.io.Raw) – Raw MEG/EEG recording to be cleaned.

  • subject (str) – Subject identifier, must match the corresponding FreeSurfer subject directory name.

  • freesurfer_dir (str or path-like) – Path to the FreeSurfer subjects directory. If None, a template will be used.

  • which_sensor_dict (dict) – Dictionary specifying which sensor types to include in the forward solution.

  • gedai_method ({"both", "broadband", "spectral"}, optional) – GEDAI artifact removal strategy. “broadband” applies suppression across the full frequency range (requires wavelet_level=0 and gedai_duration). “spectral” applies suppression per frequency band (requires wavelet_level > 0). “both” runs a preliminary broadband pass followed by spectral suppression. Default is “both”.

  • sensai_method (str, optional) – Method used by SensAI for noise estimation. Options are: “optimize” and “gridsearch”. Default is “optimize”.

  • conductivity (tuple of float, optional) – Conductivity values (in S/m) for the BEM layers. Use a 1-tuple for a single-shell model (MEG only) or a 3-tuple for a three-layer model (MEG+EEG). Default is (0.3,).

  • source_space ({"volumetric", "surface"}, optional) – Type of source space to use for the forward solution. Default is “volumetric”.

  • gedai_duration (float or None, optional) – Duration (in seconds) of each data segment used during fitting. Required when gedai_method is “broadband”. Default is None.

  • gedai_overlap (float, optional) – Fractional overlap between consecutive segments, between 0 and 1. Default is 0.5.

  • gedai_preliminary_broadband_noise_multiplier (float, optional) – Noise multiplier for the preliminary broadband suppression pass when gedai_method is “both”. Default is 6.0.

  • gedai_noise_multiplier (float, optional) – Noise multiplier threshold for the main GEDAI suppression step. Default is 3.0.

  • gedai_wavelet_type (str, optional) – Wavelet family to use for the spectral decomposition. Default is “haar”.

  • gedai_wavelet_level (int or "auto", optional) – Number of wavelet decomposition levels. Set to 0 for broadband mode, or “auto” to determine the level automatically. Default is “auto”.

  • gedai_wavelet_low_cutoff (float or None, optional) – Lower cutoff frequency (in Hz) for the wavelet decomposition. Should match the highpass filter cutoff. Default is None.

  • gedai_epoch_size_in_cycles (int, optional) – Minimum number of cycles per frequency band used to determine epoch length. Default is 12.

  • gedai_highpass_cutoff (float, optional) – Highpass filter cutoff frequency (in Hz) applied before GEDAI fitting. Default is 0.1.

  • source_space_spacing (str, optional) – Spacing parameter for surface source spaces (e.g. “ico4”). Default is “ico4”.

  • source_space_spacing_number (int, optional) – Numeric spacing value corresponding to source_space_spacing. Default is 4.

  • plot (bool, optional) – If True, displays GEDAI fit diagnostics and an interactive overlay of the cleaned vs. original signal for each sensor type. Default is False.

Returns:

Cleaned raw recording with MEG/EEG channels replaced by their GEDAI-suppressed counterparts. All other channels are unchanged.

Return type:

mne.io.Raw

meganorm.src.preprocess.head_motion_correction(data, empty_room_recording, device, Head_movement_limit_from_mean=0.0015)[source]

Perform head-motion–correction.

Parameters:
  • data (mne.io.Raw) – Raw MEG recording from a subject. Must contain cHPI channels if head-movement estimation is desired.

  • empty_room_recording (mne.io.Raw | None) – Empty-room MEG recording corresponding to the subject data. If provided, it will be prepared and Maxwell-filtered using the sensor geometry of the subject data.

  • device (str) – File extension identifying the MEG vendor.

  • Head_position_limit_from_mean (float, default=0.0015) – Threshold (in meters) for annotating excessive head movement. Time segments where the head position deviates from the mean position by more than this value will be annotated.

Returns:

  • data (mne.io.Raw) – The processed subject MEG data. If cHPI data are present, the output includes movement annotations and an updated dev_head_t based on the average head position.

  • empty_room_recording (mne.io.Raw | None) – The processed empty-room recording, filtered using the same Maxwell filtering parameters as the subject data but without movement compensation. Returned unchanged if None was provided.

meganorm.src.preprocess.pca_elbow_locator(raw, which_sensor)[source]

Estimate the number of ICA/PCA components to retain using the explained-variance elbow of a PCA decomposition.

Selects MEG and/or EEG channels per which_sensor, fits a PCA on the resulting data, and locates the “elbow” of the explained variance ratio curve using the Kneedle algorithm.

Parameters:
  • raw (mne.io.Raw) – Raw MEG/EEG data.

  • which_sensor (dict) – Dictionary indicating which sensor types to include (e.g., {‘meg’: True, ‘mag’: True, ‘grad’: True, ‘eeg’: False}).

Returns:

The estimated number of components at the elbow of the explained variance curve, with a minimum enforced value of 30.

Return type:

int

meganorm.src.preprocess.prepare_eeg_data(data, path)[source]

Prepare EEG data by setting channel types and electrode montage when they are not in the data yet

Parameters:
  • data (mne.io.Raw) – The raw EEG data.

  • path (str) – Path to the EEG recording file.

Returns:

The EEG data with updated channel types and montage (if available).

Return type:

mne.io.Raw

meganorm.src.preprocess.preprocess(data, device, subject, freesurfer_dir, which_sensor, empty_room_recording=None, resampling_rate=1000, digital_filter=True, rereference_method='average', n_component=30, ica_max_iter=800, IcaMethod='fastica', cutoffFreqLow=1, cutoffFreqHigh=45, apply_ica=True, power_line_freq=60, auto_ica_corr_thr=0.9, muscle_activity_thr=4.0, muscle_activity_min_length_good=0.1, muscle_activity_filter_freq=(110, 140), apply_ica_elbow_detection=False, apply_oversampled_temporal_projection=True, apply_Head_movement_correction=True, Head_movement_limit_from_mean=0.0015, apply_chpi_filter=False, apply_environmental_noise_correction=True, ctf_gradient_comp_level=3, apply_environmental_noise_ssp_with_eroom=False, apply_environmental_noise_ica_with_ref_meg=False, environmental_noise_ica_with_ref_meg_thr=2.5, ica_if_reject_by_annotation=True, environmental_noise_ica_with_ref_meg_method='together', environmental_noise_ica_with_ref_meg_measure='zscore', apply_gedai=True, gedai_method='both', sensai_method='optimize', conductivity=(0.3,), source_space='volumetric', gedai_duration=None, gedai_overlap=0.5, gedai_preliminary_broadband_noise_multiplier=6.0, same_environmental_noise_removal=False, gedai_noise_multiplier=3.0, gedai_wavelet_type='haar', gedai_wavelet_level='auto', gedai_wavelet_low_cutoff=None, gedai_epoch_size_in_cycles=12, gedai_highpass_cutoff=0.1, source_space_spacing='ico4', source_space_spacing_number=4, event_record=None, event_of_interest=None, segments_length=10, overlap=5)[source]

Applies a preprocessing pipeline on MEG/EEG data.

Parameters:
  • data (mne.io.Raw) – Raw MEG/EEG data.

  • device (str) – The extension of the subject’s recording (e.g., ‘FIF’, ‘DS’). Used to read the appropriate layout file from the layout directory.

  • which_sensor (dict) – Dictionary specifying which sensor types to include (e.g., {‘meg’: True, ‘eeg’: True}).

  • empty_room_recording (mne.io.Raw, optional) – Empty room recording.

  • resampling_rate (int, optional) – Target sampling rate for resampling. If None, resampling is skipped; by default 1000.

  • digital_filter (bool, optional) – Whether to apply a bandpass FIR filter to the data; by default True.

  • rereference_method (str, optional) – EEG re-referencing method. Supported: “average”, “REST”; by default “average”.

  • n_component (int, optional) – Number of independent component to retain in ICA; by default 30.

  • ica_max_iter (int, optional) – Maximum number of iterations for ICA; by default 800.

  • IcaMethod (str, optional) – ICA algorithm to use. Supported: ‘fastica’, ‘picard’, ‘infomax’; by default “fastica”.

  • cutoffFreqLow (int, optional) – Low cutoff frequency for bandpass filtering; by default 1.

  • cutoffFreqHigh (int, optional) – High cutoff frequency for bandpass filtering; by default 45.

  • apply_ica (bool, optional) – Whether to apply ICA to remove artifacts; by default True.

  • power_line_freq (int, optional) – Power line frequency (for notch filtering); by default 60.

  • auto_ica_corr_thr (float, optional) – Correlation threshold for automatic ICA artifact rejection; by default 0.9. That is, the correlation between identified independent components and physiological signals (ECG and EOG) must be higher than ‘auto_ica_corr_thr’

  • ctf_gradient_comp_level (int, optional) – The gradient compensation level to apply. Valid values typically include: -1 (disable), 0 (raw data), 1, 2, 3 (increasing levels of compensation). Default is 3.

  • muscle_activity_thr (float, optional) – The threshold for a segment to be considered as artifact (z-scores)

  • muscle_activity_min_length_good (float, optional) – The minimum required duration (in seconds) of valid data between consecutive annotations.

  • muscle_activity_filter_freq (tuple, optional) – Cutoff frequencies for the band-pass filter used in muscle activity detection. Muscle activity is typically more prominent in higher frequency ranges (e.g., 110–140 Hz).

  • apply_ica_elbow_detection (bool: False)

Returns:

Preprocessed MEG/EEG data.

Return type:

mne.io.Raw

meganorm.src.preprocess.remove_environmental_noise(data, device, empty_room_recording=None, ctf_gradient_comp_level=3, apply_environmental_noise_ssp_with_eroom=False, apply_environmental_noise_ica_with_ref_meg=False, environmental_noise_ica_with_ref_meg_thr=2.5, ica_if_reject_by_annotation=True, environmental_noise_ica_with_ref_meg_method='together', environmental_noise_ica_with_ref_meg_measure='zscore', same_environmental_noise_removal=False)[source]

Suppress environmental (external) noise using a device-appropriate strategy.

For CTF data, applies gradient compensation. For MEGIN data, relies on tSSS if already applied. Otherwise, environmental noise can be suppressed via SSP projectors computed from an empty-room recording, or via reference-MEG-based ICA.

Parameters:
  • data (mne.io.Raw) – Raw MEG/EEG data to clean.

  • device ({"CTF", "MEGIN", ...}) – Recording system type, determining the default noise-removal strategy.

  • empty_room_recording (mne.io.Raw, optional) – Empty-room recording used for gradient compensation or SSP projector estimation.

  • ctf_gradient_comp_level (int, optional) – Gradient compensation grade to apply for CTF data. Default is 3.

  • apply_environmental_noise_ssp_with_eroom (bool, optional) – Whether to compute and apply SSP projectors from the empty-room recording. Default is False.

  • apply_environmental_noise_ica_with_ref_meg (bool, optional) – Whether to use reference-MEG-based ICA to remove environmental noise. Default is False.

  • environmental_noise_ica_with_ref_meg_thr (float, optional) – Threshold used by find_bads_ref for identifying bad components. Default is 2.5.

  • ica_if_reject_by_annotation (bool, optional) – Whether to reject data by annotation when fitting the reference-MEG ICA. Default is True.

  • environmental_noise_ica_with_ref_meg_method ({"together", "separate"}, optional) – Strategy for combining reference-MEG and data channels during ICA-based artifact detection. Default is “together”.

  • environmental_noise_ica_with_ref_meg_measure (str, optional) – Scoring measure used by find_bads_ref. Default is “zscore”.

Returns:

  • data (mne.io.Raw) – Data with environmental noise suppressed.

  • empty_room_recording (mne.io.Raw or None) – Empty-room recording, updated if gradient compensation was applied.

meganorm.src.preprocess.segment_epoch(data, which_sensor, sampling_rate, tmin=20, tmax=-20, segments_length=10, overlap=0, ica_if_reject_by_annotation=True, bad_segment_removal_method='fixed_thr', mag_var_threshold=5e-12, grad_var_threshold=5e-10, eeg_var_threshold=4e-05, mag_flat_threshold=1e-14, grad_flat_threshold=1e-12, eeg_flat_threshold=4e-05, segment_events=None)[source]

Segment continuous MEG/EEG data into fixed-length overlapping epochs.

This function crops the input raw data to a specified time window, removes edge portions to avoid artifacts, and then segments the data into fixed-length epochs using MNE-Python. Automatic rejection and flat-channel criteria can be applied separately for MEG magnetometers, gradiometers, and EEG channels.

Parameters:
  • data (mne.io.Raw) – Continuous MEG/EEG recording.

  • tmin (float) – Start time (in seconds) for cropping the raw data.

  • tmax (float) – End time (in seconds) for cropping the raw data. Must be a negative value, indicating the offset (in seconds) from the end of the recording.

  • sampling_rate (float) – Sampling rate of the data in Hz.

  • segments_length (float, optional) – Length of each epoch in seconds. Default is 10.

  • overlap (float, optional) – Overlap between successive epochs in seconds. Default is 0.

  • ica_if_reject_by_annotation (bool, optional) – Whether to reject epochs based on annotations (e.g., ICA-identified artifacts). Passed to reject_by_annotation in mne.Epochs. Default is True.

  • remove_bad_segments (bool, optional) – Whether to apply amplitude and flatness thresholds to reject bad epochs. Default is True.

  • mag_var_threshold (float, optional) – Peak-to-peak amplitude threshold for rejecting epochs containing artifacts in magnetometer channels (in Tesla). Default is 5000e-15.

  • grad_var_threshold (float, optional) – Peak-to-peak amplitude threshold for rejecting epochs containing artifacts in gradiometer channels (in Tesla/m). Default is 5000e-13.

  • eeg_var_threshold (float, optional) – Peak-to-peak amplitude threshold for rejecting epochs containing artifacts in EEG channels (in Volts). Default is 40e-6.

  • mag_flat_threshold (float, optional) – Flatness threshold for magnetometer channels (in Tesla). Epochs with signals below this threshold are rejected. Default is 10e-15.

  • grad_flat_threshold (float, optional) – Flatness threshold for gradiometer channels (in Tesla/m). Default is 10e-13.

  • eeg_flat_threshold (float, optional) – Flatness threshold for EEG channels (in Volts). Default is 40e-6.

  • which_sensor (dict)

Returns:

  • segments (mne.Epochs) – An Epochs object containing fixed-length segments extracted from the continuous data.

  • rejection_summary (dict) – A dictionary summarising epoch retention and rejection, with keys:

    • total_epochs : int, total epochs before rejection.

    • retained_epochs : int, number of epochs kept.

    • discarded_epochs : int, number of epochs removed.

    • pct_discarded : float, percentage of epochs discarded.

    • signal_retained_s : float, seconds of signal retained.

    • signal_total_s : float, total seconds before rejection.

    • drop_reasons : Counter, counts per channel name or annotation label that caused rejection. Channel names indicate threshold-based rejection; annotation labels (e.g. 'IGNORED') indicate annotation-based rejection.

Raises:
  • ValueError – If tmax is not a negative number.

  • Exception – If all epochs are rejected, with a summary of drop reasons included in the message.

meganorm.src.psdParameterize module

meganorm.src.psdParameterize.computePsd(segments, freq_range_low=3, freq_range_high=40, sampling_rate=1000, psd_method='welch', psd_n_overlap=1, psd_n_fft=2, n_per_seg=2)[source]

Compute the Power Spectral Density (PSD) of EEG/MEG data segments.

Parameters:
  • segments (mne.Epochs) – Segmented data for which PSD will be computed.

  • freq_range_low (int) – Lower frequency bound for PSD calculation (Hz).

  • freq_range_high (int) – Upper frequency bound for PSD calculation (Hz).

  • sampling_rate (int) – Sampling rate of the data (Hz).

  • psd_method (str) – Method for computing the PSD. Default is “welch”.

  • psd_n_overlap (int) – Overlap between segments (in seconds) for PSD calculation.

  • psd_n_fft (int) – Number of FFT points used for the PSD calculation.

  • n_per_seg (int) – Number of samples per segment used for computing PSD.

Returns:

  • psds (np.ndarray) – Array of power spectral density values.

  • freqs (np.ndarray) – Array of frequency values corresponding to the PSD.

meganorm.src.psdParameterize.fooof(psds, freqs, freq_range_low=3, freq_range_high=40, min_peak_height=0, peak_threshold=2, peak_width_limits=[1, 12.0], aperiodic_mode='fixed')[source]

Fit a FOOOF model to power spectral density (PSD) data to separate periodic (oscillatory) and aperiodic (background) components.

Parameters:
  • psds (np.ndarray) – Power spectral density values.

  • freqs (np.ndarray) – Frequency values corresponding to the PSD.

  • freq_range_low (int) – Lower frequency bound for the FOOOF model (Hz).

  • freq_range_high (int) – Upper frequency bound for the FOOOF model (Hz).

  • min_peak_height (float) – Minimum height of peaks to be considered in the FOOOF model.

  • peak_threshold (float) – Threshold for peak detection in the FOOOF model.

  • peak_width_limits (list) – Limits on the width of peaks (in Hz).

  • aperiodic_mode (str) – Mode for modeling the aperiodic component. Options are “fixed”, “knee”, or “none”.

Returns:

  • fooofModels (FOOOFGroup) – Fitted FOOOF group model containing periodic and aperiodic components.

  • psds (np.ndarray) – Original power spectral density values.

  • freqs (np.ndarray) – Frequency values corresponding to the PSD.

meganorm.src.psdParameterize.irasa_epochs(data, band=(1.0, 100.0), hset_info=(1.05, 2.0, 0.05))[source]

Separate aperiodic from periodic power spectra using the IRASA algorithm for Epochs data.

This function applies the Irregular Resampling Auto-Spectral Analysis (IRASA) algorithm as described by Wen & Liu (2016) to decompose the power spectrum of neurophysiological signals into aperiodic (fractal) and periodic (oscillatory) components. It is specifically designed for time-series data in mne.Epochs format, making it suitable for event-related EEG/MEG analyses.

Parameters:
  • data (mne.Epochs) – The time-series data used to extract aperiodic and periodic power spectra. This should be an instance of mne.Epochs.

  • band (tuple of (float, float), optional, default: (1.0, 100.0)) – A tuple specifying the lower and upper bounds of the frequency range (in Hz) used for extracting the aperiodic and periodic spectra.

  • hset_info (tuple of (float, float, float), optional, default: (1.05, 2.0, 0.05)) – Contains the range of up/downsampling factors used in the IRASA algorithm. This should be a tuple specifying the (min, max, step) values for the resampling.

Returns:

  • psd_list_original (np.array) – Original power spectrum.

  • aperiodic (AperiodicEpochsSpectrum) – The aperiodic component of the data as an AperiodicEpochsSpectrum object.

  • periodic (PeriodicEpochsSpectrum) – The periodic component of the data as a PeriodicEpochsSpectrum object.

Return type:

IrasaEpoched

meganorm.src.psdParameterize.parameterize_psds(segments, parametrization_method, freq_range_low=3, freq_range_high=40, min_peak_height=0, peak_threshold=2, sampling_rate=1000, psd_method='welch', psd_n_overlap=1, psd_n_fft=2, n_per_seg=2, peak_width_limits=[1, 12.0], aperiodic_mode='knee', irasa_hset=(1.05, 2.0, 0.05))[source]

Runs the complete pipeline for spectral parameterization using FOOOF. This includes computing the PSD and fitting FOOOF models for each channel.

Parameters:
  • segments (mne.Epochs) – Epoched MNE object containing segmented data.

  • freq_range_low (float) – Lower bound of frequency range for PSD and FOOOF (Hz).

  • freq_range_high (float) – Upper bound of frequency range for PSD and FOOOF (Hz).

  • min_peak_height (float) – Minimum height of peaks to be detected by FOOOF.

  • peak_threshold (float) – Threshold for peak detection relative to the aperiodic fit.

  • sampling_rate (int) – Sampling frequency of the signal (Hz).

  • psd_method (str) – Method used to compute PSD. Options: “welch”, “multitaper”.

  • psd_n_overlap (int) – Overlap (in seconds) between segments in PSD computation.

  • psd_n_fft (int) – Number of FFT points (in seconds) used in PSD.

  • n_per_seg (int) – Length (in seconds) of each segment used in PSD.

  • peak_width_limits (list of float, optional) – Lower and upper bounds on peak width (Hz). Default is [1, 12.0].

  • aperiodic_mode (str) – Mode of aperiodic fit. Options: “fixed” or “knee”.

Returns:

  • spectral_models (FOOOFGroup | pyrasa.irasa_mne.mne_objs.IrasaEpoched) – Fitted spectral models for each channel.

  • psds (np.ndarray) – Power spectral densities.

  • freqs (np.ndarray) – Corresponding frequency values.

Raises:
  • ValueError – If psd_method is not ‘welch’ or ‘multitaper’.

  • ValueError – If aperiodic_mode is not ‘fixed’ or ‘knee’.

meganorm.src.psdParameterize.sqc_parameterize_psds(segments, parametrization_method, freq_range_low=3, freq_range_high=40, min_peak_height=0, peak_threshold=2, sampling_rate=1000, psd_method='welch', psd_n_overlap=1, psd_n_fft=2, n_per_seg=2, peak_width_limits=[1, 12.0], aperiodic_mode='knee', irasa_hset=(1.05, 2.0, 0.05))[source]

Runs the complete pipeline for spectral parameterization using FOOOF. This includes computing the PSD and fitting FOOOF models for each channel.

Parameters:
  • segments (mne.Epochs) – Epoched MNE object containing segmented data.

  • freq_range_low (float) – Lower bound of frequency range for PSD and FOOOF (Hz).

  • freq_range_high (float) – Upper bound of frequency range for PSD and FOOOF (Hz).

  • min_peak_height (float) – Minimum height of peaks to be detected by FOOOF.

  • peak_threshold (float) – Threshold for peak detection relative to the aperiodic fit.

  • sampling_rate (int) – Sampling frequency of the signal (Hz).

  • psd_method (str) – Method used to compute PSD. Options: “welch”, “multitaper”.

  • psd_n_overlap (int) – Overlap (in seconds) between segments in PSD computation.

  • psd_n_fft (int) – Number of FFT points (in seconds) used in PSD.

  • n_per_seg (int) – Length (in seconds) of each segment used in PSD.

  • peak_width_limits (list of float, optional) – Lower and upper bounds on peak width (Hz). Default is [1, 12.0].

  • aperiodic_mode (str) – Mode of aperiodic fit. Options: “fixed” or “knee”.

Returns:

  • spectral_models (FOOOFGroup | pyrasa.irasa_mne.mne_objs.IrasaEpoched) – Fitted spectral models for each channel.

  • psds (np.ndarray) – Power spectral densities.

  • freqs (np.ndarray) – Corresponding frequency values.

Raises:
  • ValueError – If psd_method is not ‘welch’ or ‘multitaper’.

  • ValueError – If aperiodic_mode is not ‘fixed’ or ‘knee’.

Module contents