<commit_before># -*- coding: utf-8 -*-
# Authors: <NAME> <<EMAIL>>
#          <NAME> <<EMAIL>>
#          <NAME> <<EMAIL>>


# License: BSD (3-clause)

from math import factorial
from os import path as op

import numpy as np
from scipy import linalg

from .. import __version__
from ..bem import _check_origin
from ..chpi import quat_to_rot, rot_to_quat
from ..transforms import (_str_to_frame, _get_trans, Transform, apply_trans,
                          _find_vector_rotation)
from ..forward import _concatenate_coils, _prep_meg_channels
from ..surface import _normalize_vectors
from ..io.constants import FIFF
from ..io.proc_history import _read_ctc
from ..io.write import _generate_meas_id, _date_now
from ..io import _loc_to_coil_trans, _BaseRaw
from ..io.pick import pick_types, pick_info, pick_channels
from ..utils import verbose, logger, _clean_names, warn
from ..fixes import _get_args, partial
from ..externals.six import string_types
from ..channels.channels import _get_T1T2_mag_inds


# Note: Elekta uses single precision and some algorithms might use
# truncated versions of constants (e.g., μ0), which could lead to small
# differences between algorithms


@verbose
def maxwell_filter(raw, origin='auto', int_order=8, ext_order=3,
                   calibration=None, cross_talk=None, st_duration=None,
                   st_correlation=0.98, coord_frame='head', destination=None,
                   regularize='in', ignore_ref=False, bad_condition='error',
                   head_pos=None, st_fixed=True, st_only=False, verbose=None):
    """Apply Maxwell filter to data using multipole moments

    .. warning:: Automatic bad channel detection is not currently implemented.
                 It is critical to mark bad channels before running Maxwell
                 filtering, so data should be inspected and marked accordingly
                 prior to running this algorithm.

    .. warning:: Not all features of Elekta MaxFilter™ are currently
                 implemented (see Notes). Maxwell filtering in mne-python
                 is not designed for clinical use.

    Parameters
    ----------
    raw : instance of mne.io.Raw
        Data to be filtered
    origin : array-like, shape (3,) | str
        Origin of internal and external multipolar moment space in meters.
        The default is ``'auto'``, which means ``(0., 0., 0.)`` for
        ``coord_frame='meg'``, and a head-digitization-based origin fit
        for ``coord_frame='head'``.
    int_order : int
        Order of internal component of spherical expansion.
    ext_order : int
        Order of external component of spherical expansion.
    calibration : str | None
        Path to the ``'.dat'`` file with fine calibration coefficients.
        File can have 1D or 3D gradiometer imbalance correction.
        This file is machine/site-specific.
    cross_talk : str | None
        Path to the FIF file with cross-talk correction information.
    st_duration : float | None
        If not None, apply spatiotemporal SSS with specified buffer duration
        (in seconds). Elekta's default is 10.0 seconds in MaxFilter™ v2.2.
        Spatiotemporal SSS acts as implicitly as a high-pass filter where the
        cut-off frequency is 1/st_dur Hz. For this (and other) reasons, longer
        buffers are generally better as long as your system can handle the
        higher memory usage. To ensure that each window is processed
        identically, choose a buffer length that divides evenly into your data.
        Any data at the trailing edge that doesn't fit evenly into a whole
        buffer window will be lumped into the previous buffer.
    st_correlation : float
        Correlation limit between inner and outer subspaces used to reject
        ovwrlapping intersecting inner/outer signals during spatiotemporal SSS.
    coord_frame : str
        The coordinate frame that the ``origin`` is specified in, either
        ``'meg'`` or ``'head'``. For empty-room recordings that do not have
        a head<->meg transform ``info['dev_head_t']``, the MEG coordinate
        frame should be used.
    destination : str | array-like, shape (3,) | None
        The destination location for the head. Can be ``None``, which
        will not change the head position, or a string path to a FIF file
        containing a MEG device<->head transformation, or a 3-element array
        giving the coordinates to translate to (with no rotations).
        For example, ``destination=(0, 0, 0.04)`` would translate the bases
        as ``--trans default`` would in MaxFilter™ (i.e., to the default
        head location).
    regularize : str | None
        Basis regularization type, must be "in" or None.
        "in" is the same algorithm as the "-regularize in" option in
        MaxFilter™.
    ignore_ref : bool
        If True, do not include reference channels in compensation. This
        option should be True for KIT files, since Maxwell filtering
        with reference channels is not currently supported.
    bad_condition : str
        How to deal with ill-conditioned SSS matrices. Can be "error"
        (default), "warning", or "ignore".
    head_pos : array | None
        If array, movement compensation will be performed.
        The array should be of shape (N, 10), holding the position
        parameters as returned by e.g. `read_head_pos`.

        .. versionadded:: 0.12

    st_fixed : bool
        If True (default), do tSSS using the median head position during the
        ``st_duration`` window. This is the default behavior of MaxFilter
        and has been most extensively tested.

        .. versionadded:: 0.12

    st_only : bool
        If True, only tSSS (temporal) projection of MEG data will be
        performed on the output data. The non-tSSS parameters (e.g.,
        ``int_order``, ``calibration``, ``head_pos``, etc.) will still be
        used to form the SSS bases used to calculate temporal projectors,
        but the ouptut MEG data will *only* have temporal projections
        performed. Noise reduction from SSS basis multiplication,
        cross-talk cancellation, movement compensation, and so forth
        will not be applied to the data.

        .. versionadded:: 0.12

    verbose : bool, str, int, or None<commit_msg>DOC: Clearer doc [ci skip]<commit_after># -*- coding: utf-8 -*-
# Authors: <NAME> <<EMAIL>>
#          <NAME> <<EMAIL>>
#          <NAME> <<EMAIL>>


# License: BSD (3-clause)

from math import factorial
from os import path as op

import numpy as np
from scipy import linalg

from .. import __version__
from ..bem import _check_origin
from ..chpi import quat_to_rot, rot_to_quat
from ..transforms import (_str_to_frame, _get_trans, Transform, apply_trans,
                          _find_vector_rotation)
from ..forward import _concatenate_coils, _prep_meg_channels
from ..surface import _normalize_vectors
from ..io.constants import FIFF
from ..io.proc_history import _read_ctc
from ..io.write import _generate_meas_id, _date_now
from ..io import _loc_to_coil_trans, _BaseRaw
from ..io.pick import pick_types, pick_info, pick_channels
from ..utils import verbose, logger, _clean_names, warn
from ..fixes import _get_args, partial
from ..externals.six import string_types
from ..channels.channels import _get_T1T2_mag_inds


# Note: Elekta uses single precision and some algorithms might use
# truncated versions of constants (e.g., μ0), which could lead to small
# differences between algorithms


@verbose
def maxwell_filter(raw, origin='auto', int_order=8, ext_order=3,
                   calibration=None, cross_talk=None, st_duration=None,
                   st_correlation=0.98, coord_frame='head', destination=None,
                   regularize='in', ignore_ref=False, bad_condition='error',
                   head_pos=None, st_fixed=True, st_only=False, verbose=None):
    """Apply Maxwell filter to data using multipole moments

    .. warning:: Automatic bad channel detection is not currently implemented.
                 It is critical to mark bad channels before running Maxwell
                 filtering, so data should be inspected and marked accordingly
                 prior to running this algorithm.

    .. warning:: Not all features of Elekta MaxFilter™ are currently
                 implemented (see Notes). Maxwell filtering in mne-python
                 is not designed for clinical use.

    Parameters
    ----------
    raw : instance of mne.io.Raw
        Data to be filtered
    origin : array-like, shape (3,) | str
        Origin of internal and external multipolar moment space in meters.
        The default is ``'auto'``, which means ``(0., 0., 0.)`` for
        ``coord_frame='meg'``, and a head-digitization-based origin fit
        for ``coord_frame='head'``.
    int_order : int
        Order of internal component of spherical expansion.
    ext_order : int
        Order of external component of spherical expansion.
    calibration : str | None
        Path to the ``'.dat'`` file with fine calibration coefficients.
        File can have 1D or 3D gradiometer imbalance correction.
        This file is machine/site-specific.
    cross_talk : str | None
        Path to the FIF file with cross-talk correction information.
    st_duration : float | None
        If not None, apply spatiotemporal SSS with specified buffer duration
        (in seconds). Elekta's default is 10.0 seconds in MaxFilter™ v2.2.
        Spatiotemporal SSS acts as implicitly as a high-pass filter where the
        cut-off frequency is 1/st_dur Hz. For this (and other) reasons, longer
        buffers are generally better as long as your system can handle the
        higher memory usage. To ensure that each window is processed
        identically, choose a buffer length that divides evenly into your data.
        Any data at the trailing edge that doesn't fit evenly into a whole
        buffer window will be lumped into the previous buffer.
    st_correlation : float
        Correlation limit between inner and outer subspaces used to reject
        ovwrlapping intersecting inner/outer signals during spatiotemporal SSS.
    coord_frame : str
        The coordinate frame that the ``origin`` is specified in, either
        ``'meg'`` or ``'head'``. For empty-room recordings that do not have
        a head<->meg transform ``info['dev_head_t']``, the MEG coordinate
        frame should be used.
    destination : str | array-like, shape (3,) | None
        The destination location for the head. Can be ``None``, which
        will not change the head position, or a string path to a FIF file
        containing a MEG device<->head transformation, or a 3-element array
        giving the coordinates to translate to (with no rotations).
        For example, ``destination=(0, 0, 0.04)`` would translate the bases
        as ``--trans default`` would in MaxFilter™ (i.e., to the default
        head location).
    regularize : str | None
        Basis regularization type, must be "in" or None.
        "in" is the same algorithm as the "-regularize in" option in
        MaxFilter™.
    ignore_ref : bool
        If True, do not include reference channels in compensation. This
        option should be True for KIT files, since Maxwell filtering
        with reference channels is not currently supported.
    bad_condition : str
        How to deal with ill-conditioned SSS matrices. Can be "error"
        (default), "warning", or "ignore".
    head_pos : array | None
        If array, movement compensation will be performed.
        The array should be of shape (N, 10), holding the position
        parameters as returned by e.g. `read_head_pos`.

        .. versionadded:: 0.12

    st_fixed : bool
        If True (default), do tSSS using the median head position during the
        ``st_duration`` window. This is the default behavior of MaxFilter
        and has been most extensively tested.

        .. versionadded:: 0.12

    st_only : bool
        If True, only tSSS (temporal) projection of MEG data will be
        performed on the output data. The non-tSSS parameters (e.g.,
        ``int_order``, ``calibration``, ``head_pos``, etc.) will still be
        used to form the SSS bases used to calculate temporal projectors,
        but the ouptut MEG data will *only* have temporal projections
        performed. Noise reduction from SSS basis multiplication,
        cross-talk cancellation, movement compensation, and so forth
        will not be applied to the data. This is useful, for example, when
        evoked movement compensation will be performed with
        :func:`mne.epochs.average_movements`.

        .. versionadded:: 0.12

    verbose : bool, str, int, or None
{'fraction_non_alphanumeric': 0.07345654738497837, 'fraction_numerical': 0.006291781360597719, 'mean_word_length': 2.713785046728972, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1755064', 'n_tokens_mistral': 3440, 'n_tokens_neox': 3270, 'n_words': 1487}