From 1ac5fca5354d423acb3f66191523a9953ab45b71 Mon Sep 17 00:00:00 2001 From: Daria Agafonova Date: Fri, 24 Jul 2026 19:32:01 +0200 Subject: [PATCH 1/3] DOC Remove defaults from parameter type descriptions --- doc/changes/dev/14095.other.rst | 1 + mne/_fiff/pick.py | 4 +- mne/bem.py | 2 +- mne/cov.py | 78 ++++++++++++------------- mne/decoding/_fixes.py | 8 +-- mne/decoding/base.py | 4 +- mne/decoding/csp.py | 22 +++---- mne/decoding/ems.py | 4 +- mne/decoding/ssd.py | 14 ++--- mne/decoding/time_frequency.py | 14 ++--- mne/decoding/transformer.py | 20 +++---- mne/decoding/xdawn.py | 4 +- mne/evoked.py | 6 +- mne/export/_egimff.py | 2 +- mne/fixes.py | 4 +- mne/forward/forward.py | 18 +++--- mne/io/artemis123/artemis123.py | 2 +- mne/io/base.py | 8 +-- mne/io/ctf/ctf.py | 4 +- mne/io/eeglab/eeglab.py | 2 +- mne/io/egi/egimff.py | 2 +- mne/io/eyelink/_utils.py | 6 +- mne/io/fiff/raw.py | 4 +- mne/io/fil/fil.py | 4 +- mne/minimum_norm/time_frequency.py | 4 +- mne/preprocessing/artifact_detection.py | 2 +- mne/preprocessing/tests/test_infomax.py | 2 +- mne/preprocessing/xdawn.py | 18 +++--- mne/rank.py | 2 +- mne/source_space/_source_space.py | 4 +- mne/stats/permutations.py | 2 +- mne/tests/test_docstring_parameters.py | 38 +++++++++--- mne/time_frequency/multitaper.py | 4 +- mne/time_frequency/tfr.py | 44 +++++++------- mne/utils/config.py | 2 +- mne/utils/docs.py | 16 ++--- mne/viz/_brain/_brain.py | 2 +- mne/viz/ica.py | 6 +- mne/viz/topomap.py | 2 +- 39 files changed, 205 insertions(+), 180 deletions(-) create mode 100644 doc/changes/dev/14095.other.rst diff --git a/doc/changes/dev/14095.other.rst b/doc/changes/dev/14095.other.rst new file mode 100644 index 00000000000..cc38e3e7562 --- /dev/null +++ b/doc/changes/dev/14095.other.rst @@ -0,0 +1 @@ +Move default values out of parameter type descriptions and remove ``optional`` from docstrings, by `Daria Agafonova`_. diff --git a/mne/_fiff/pick.py b/mne/_fiff/pick.py index fa2a8d94a2e..7f62644c254 100644 --- a/mne/_fiff/pick.py +++ b/mne/_fiff/pick.py @@ -944,9 +944,9 @@ def pick_channels_cov( ---------- orig : Covariance A covariance. - include : list of str, (optional) + include : list of str List of channels to include (if empty, include all available). - exclude : list of str, (optional) | 'bads' + exclude : list of str | 'bads' Channels to exclude (if empty, do not exclude any). Defaults to 'bads'. %(ordered)s copy : bool diff --git a/mne/bem.py b/mne/bem.py index 8718dd9ced3..8d3b606dc62 100644 --- a/mne/bem.py +++ b/mne/bem.py @@ -1443,7 +1443,7 @@ def read_bem_surfaces( ---------- fname : path-like The name of the file containing the surfaces. - patch_stats : bool, optional (default False) + patch_stats : bool Calculate and add cortical patch statistics to the surfaces. s_id : int | None If int, only read and return the surface with the given ``s_id``. diff --git a/mne/cov.py b/mne/cov.py index baf5a053786..d54c952a6b0 100644 --- a/mne/cov.py +++ b/mne/cov.py @@ -606,15 +606,15 @@ def compute_raw_covariance( Raw data. tmin : float Beginning of time interval in seconds. Defaults to 0. - tmax : float | None (default None) + tmax : float | None End of time interval in seconds. If None (default), use the end of the recording. - tstep : float (default 0.2) + tstep : float Length of data chunks for artifact rejection in seconds. Can also be None to use a single epoch of (tmax - tmin) duration. This can use a lot of memory for large ``Raw`` instances. - reject : dict | None (default None) + reject : dict | None Rejection parameters based on peak-to-peak amplitude. Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg'. If reject is None then no rejection is done. Example:: @@ -625,7 +625,7 @@ def compute_raw_covariance( eog=250e-6 # V (EOG channels) ) - flat : dict | None (default None) + flat : dict | None Rejection parameters based on flatness of signal. Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg', and values are floats that set the minimum acceptable peak-to-peak amplitude. @@ -637,23 +637,23 @@ def compute_raw_covariance( covariance or rank estimates. .. versionadded:: 1.11 - method : str | list | None (default 'empirical') + method : str | list | None The method used for covariance estimation. See :func:`mne.compute_covariance`. .. versionadded:: 0.12 - method_params : dict | None (default None) + method_params : dict | None Additional parameters to the estimation procedure. See :func:`mne.compute_covariance`. .. versionadded:: 0.12 - cv : int | sklearn.model_selection object (default 3) + cv : int | sklearn.model_selection object The cross validation method. Defaults to 3, which will internally trigger by default :class:`sklearn.model_selection.KFold` with 3 splits. .. versionadded:: 0.12 - scalings : dict | None (default None) + scalings : dict | None Defaults to ``dict(mag=1e15, grad=1e13, eeg=1e6)``. These defaults will scale magnetometers and gradiometers at the same unit. @@ -662,7 +662,7 @@ def compute_raw_covariance( %(n_jobs)s .. versionadded:: 0.12 - return_estimators : bool (default False) + return_estimators : bool Whether to return all estimators or the best. Only considered if method equals 'auto' or is a list of str. Defaults to False. @@ -911,17 +911,17 @@ def compute_covariance( ---------- epochs : instance of Epochs, or list of Epochs The epochs. - keep_sample_mean : bool (default True) + keep_sample_mean : bool If False, the average response over epochs is computed for each event type and subtracted during the covariance computation. This is useful if the evoked response from a previous stimulus extends into the baseline period of the next. Note. This option is only implemented for method='empirical'. - tmin : float | None (default None) + tmin : float | None Start time for baseline. If None start at first sample. - tmax : float | None (default None) + tmax : float | None End time for baseline. If None end at last sample. - projs : list of Projection | None (default None) + projs : list of Projection | None List of projectors to use in covariance calculation, or None to indicate that the projectors from the epochs should be inherited. If None, then projectors from all epochs must match. @@ -931,7 +931,7 @@ def compute_covariance( covariance or rank estimates. .. versionadded:: 1.11 - method : str | list | None (default 'empirical') + method : str | list | None The method used for covariance estimation. If 'empirical' (default), the sample covariance will be computed. A list can be passed to perform estimates using multiple methods. @@ -949,7 +949,7 @@ def compute_covariance( segments of data, since computation can take a long time. .. versionadded:: 0.9.0 - method_params : dict | None (default None) + method_params : dict | None Additional parameters to the estimation procedure. Only considered if method is not None. Keys must correspond to the value(s) of ``method``. If None (default), expands to the following (with the addition of @@ -962,16 +962,16 @@ def compute_covariance( 'pca': {'iter_n_components': None}, 'factor_analysis': {'iter_n_components': None}} - cv : int | sklearn.model_selection object (default 3) + cv : int | sklearn.model_selection object The cross validation method. Defaults to 3, which will internally trigger by default :class:`sklearn.model_selection.KFold` with 3 splits. - scalings : dict | None (default None) + scalings : dict | None Defaults to ``dict(mag=1e15, grad=1e13, eeg=1e6)``. These defaults will scale data to roughly the same order of magnitude. %(n_jobs)s - return_estimators : bool (default False) + return_estimators : bool Whether to return all estimators or the best. Only considered if method equals 'auto' or is a list of str. Defaults to False. on_mismatch : str @@ -1986,45 +1986,45 @@ def regularize( cov : Covariance The noise covariance matrix. %(info_not_none)s (Used to get channel types and bad channels). - mag : float (default 0.1) + mag : float Regularization factor for MEG magnetometers. - grad : float (default 0.1) + grad : float Regularization factor for MEG gradiometers. Must be the same as ``mag`` if data have been processed with SSS. - eeg : float (default 0.1) + eeg : float Regularization factor for EEG. - exclude : list | 'bads' (default 'bads') + exclude : list | 'bads' List of channels to mark as bad. If 'bads', bads channels are extracted from both info['bads'] and cov['bads']. - proj : bool (default True) + proj : bool Apply projections to keep rank of data. - seeg : float (default 0.1) + seeg : float Regularization factor for sEEG signals. - ecog : float (default 0.1) + ecog : float Regularization factor for ECoG signals. - hbo : float (default 0.1) + hbo : float Regularization factor for HBO signals. - hbr : float (default 0.1) + hbr : float Regularization factor for HBR signals. - fnirs_cw_amplitude : float (default 0.1) + fnirs_cw_amplitude : float Regularization factor for fNIRS CW raw signals. - fnirs_fd_ac_amplitude : float (default 0.1) + fnirs_fd_ac_amplitude : float Regularization factor for fNIRS FD AC raw signals. - fnirs_fd_phase : float (default 0.1) + fnirs_fd_phase : float Regularization factor for fNIRS raw phase signals. - fnirs_od : float (default 0.1) + fnirs_od : float Regularization factor for fNIRS optical density signals. - fnirs_td_gated_amplitude : float (default 0.1) + fnirs_td_gated_amplitude : float Regularization factor for fNIRS time domain gated amplitude signals. - fnirs_td_moments_intensity : float (default 0.1) + fnirs_td_moments_intensity : float Regularization factor for fNIRS time domain moments amplitude signals. - fnirs_td_moments_mean : float (default 0.1) + fnirs_td_moments_mean : float Regularization factor for fNIRS time domain moments mean signals. - fnirs_td_moments_variance : float (default 0.1) + fnirs_td_moments_variance : float Regularization factor for fNIRS time domain moments variance signals. - csd : float (default 0.1) + csd : float Regularization factor for EEG-CSD signals. - dbs : float (default 0.1) + dbs : float Regularization factor for DBS signals. %(rank_none)s @@ -2375,13 +2375,13 @@ def whiten_evoked( noise_cov : instance of Covariance The noise covariance. %(picks_good_data)s - diag : bool (default False) + diag : bool If True, whiten using only the diagonal of the covariance. %(rank_none)s .. versionadded:: 0.18 Support for 'info' mode. - scalings : dict | None (default None) + scalings : dict | None To achieve reliable rank estimation on multiple sensors, sensors have to be rescaled. This parameter controls the rescaling. If dict, it will override the diff --git a/mne/decoding/_fixes.py b/mne/decoding/_fixes.py index 0a71721279e..813c74343a6 100644 --- a/mne/decoding/_fixes.py +++ b/mne/decoding/_fixes.py @@ -41,7 +41,7 @@ def validate_data( the only accepted `check_params` are `multi_output` and `y_numeric`. - y : array-like of shape (n_samples,), default='no_validation' + y : array-like of shape (n_samples,) The targets. - If `None`, :func:`~sklearn.utils.check_array` is called on `X`. If @@ -54,7 +54,7 @@ def validate_data( either :func:`~sklearn.utils.check_array` or :func:`~sklearn.utils.check_X_y` depending on `validate_separately`. - reset : bool, default=True + reset : bool Whether to reset the `n_features_in_` attribute. If False, the input will be checked for consistency with data provided when reset was last True. @@ -65,7 +65,7 @@ def validate_data( call to `partial_fit`. All other methods that validate `X` should set `reset=False`. - validate_separately : False or tuple of dicts, default=False + validate_separately : False or tuple of dicts Only used if `y` is not `None`. If `False`, call :func:`~sklearn.utils.check_X_y`. Else, it must be a tuple of kwargs to be used for calling :func:`~sklearn.utils.check_array` on `X` @@ -74,7 +74,7 @@ def validate_data( `estimator=self` is automatically added to these dicts to generate more informative error message in case of invalid input data. - skip_check_array : bool, default=False + skip_check_array : bool If `True`, `X` and `y` are unchanged and only `feature_names_in_` and `n_features_in_` are checked. Otherwise, :func:`~sklearn.utils.check_array` is called on `X` and `y`. diff --git a/mne/decoding/base.py b/mne/decoding/base.py index 75ec826b711..fe2707e1fd1 100644 --- a/mne/decoding/base.py +++ b/mne/decoding/base.py @@ -842,9 +842,9 @@ def cross_val_multiscore( other cases, :class:`sklearn.model_selection.KFold` is used. %(n_jobs)s %(verbose)s - fit_params : dict, optional + fit_params : dict Parameters to pass to the fit method of the estimator. - pre_dispatch : int, or str, optional + pre_dispatch : int, or str Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched diff --git a/mne/decoding/csp.py b/mne/decoding/csp.py index 18d8d5e0246..99c324fba31 100644 --- a/mne/decoding/csp.py +++ b/mne/decoding/csp.py @@ -34,28 +34,28 @@ class CSP(_GEDTransformer): Parameters ---------- - n_components : int (default 4) + n_components : int The number of components to decompose M/EEG signals. This number should be set by cross-validation. - reg : float | str | None (default None) + reg : float | str | None If not None (same as ``'empirical'``, default), allow regularization for covariance estimation. If float (between 0 and 1), shrinkage is used. For str values, ``reg`` will be passed as ``method`` to :func:`mne.compute_covariance`. - log : None | bool (default None) + log : None | bool If ``transform_into`` equals ``'average_power'`` and ``log`` is None or True, then apply a log transform to standardize features, else features are z-scored. If ``transform_into`` is ``'csp_space'``, ``log`` must be None. - cov_est : 'concat' | 'epoch' (default 'concat') + cov_est : 'concat' | 'epoch' If ``'concat'``, covariance matrices are estimated on concatenated epochs for each class. If ``'epoch'``, covariance matrices are estimated on each epoch separately and then averaged over each class. - transform_into : 'average_power' | 'csp_space' (default 'average_power') + transform_into : 'average_power' | 'csp_space' If 'average_power' then ``self.transform`` will return the average power of each spatial filter. If ``'csp_space'``, ``self.transform`` will return the data in CSP space. - norm_trace : bool (default False) + norm_trace : bool Normalize class covariance by its trace. Trace normalization is a step of the original CSP algorithm :footcite:`KolesEtAl1990` to eliminate magnitude variations in the EEG between individuals. It is not applied @@ -89,7 +89,7 @@ class CSP(_GEDTransformer): %(rank_none)s .. versionadded:: 0.17 - component_order : 'mutual_info' | 'alternate' (default 'mutual_info') + component_order : 'mutual_info' | 'alternate' If ``'mutual_info'`` order components by decreasing mutual information (in the two-class case this uses a simplification which orders components by decreasing absolute deviation of the eigenvalues from 0.5 @@ -611,9 +611,9 @@ def _ajd_pham(X, eps=1e-6, max_iter=15): ---------- X : ndarray, shape (n_epochs, n_channels, n_channels) A set of covariance matrices to diagonalize. - eps : float, default 1e-6 + eps : float The tolerance for stopping criterion. - max_iter : int, default 1000 + max_iter : int The maximum number of iteration to reach convergence. Returns @@ -705,13 +705,13 @@ class SPoC(CSP): ---------- n_components : int The number of components to decompose M/EEG signals. - reg : float | str | None (default None) + reg : float | str | None If not None (same as ``'empirical'``, default), allow regularization for covariance estimation. If float, shrinkage is used (0 <= shrinkage <= 1). For str options, ``reg`` will be passed to ``method`` to :func:`mne.compute_covariance`. - log : None | bool (default None) + log : None | bool If transform_into == 'average_power' and log is None or True, then applies a log transform to standardize the features, else the features are z-scored. If transform_into == 'csp_space', then log must be None. diff --git a/mne/decoding/ems.py b/mne/decoding/ems.py index 5c7557798ef..3f17bbee694 100644 --- a/mne/decoding/ems.py +++ b/mne/decoding/ems.py @@ -131,13 +131,13 @@ def compute_ems( ---------- epochs : instance of mne.Epochs The epochs. - conditions : list of str | None, default None + conditions : list of str | None If a list of strings, strings must match the epochs.event_id's key as well as the number of conditions supported by the objective_function. If None keys in epochs.event_id are used. %(picks_good_data)s %(n_jobs)s - cv : cross-validation object | str | None, default LeaveOneOut + cv : cross-validation object | str | None The cross-validation scheme. %(verbose)s diff --git a/mne/decoding/ssd.py b/mne/decoding/ssd.py index 30ea788a73c..d00a17ca626 100644 --- a/mne/decoding/ssd.py +++ b/mne/decoding/ssd.py @@ -41,31 +41,31 @@ class SSD(_GEDTransformer): Filtering for the frequencies of interest. filt_params_noise : dict Filtering for the frequencies of non-interest. - reg : float | str | None (default) + reg : float | str | None Which covariance estimator to use. If not None (same as 'empirical'), allow regularization for covariance estimation. If float, shrinkage is used (0 <= shrinkage <= 1). For str options, reg will be passed to method :func:`mne.compute_covariance`. - n_components : int | None (default None) + n_components : int | None The number of components to extract from the signal. If None, the number of components equal to the rank of the data are returned (see ``rank``). - picks : array of int | None (default None) + picks : array of int | None The indices of good channels. - sort_by_spectral_ratio : bool (default True) + sort_by_spectral_ratio : bool If set to True, the components are sorted according to the spectral ratio. See Eq. (24) in :footcite:`NikulinEtAl2011`. - return_filtered : bool (default False) + return_filtered : bool If return_filtered is True, data is bandpassed and projected onto the SSD components. - n_fft : int (default None) + n_fft : int If sort_by_spectral_ratio is set to True, then the SSD sources will be sorted according to their spectral ratio which is calculated based on :func:`mne.time_frequency.psd_array_welch`. The n_fft parameter sets the length of FFT used. The default (None) will use 1 second of data. See :func:`mne.time_frequency.psd_array_welch` for more information. - cov_method_params : dict | None (default None) + cov_method_params : dict | None As in :class:`mne.decoding.SPoC` The default is None. restr_type : "restricting" | "whitening" | None diff --git a/mne/decoding/time_frequency.py b/mne/decoding/time_frequency.py index 29232aaeb9f..bbfe57277ca 100644 --- a/mne/decoding/time_frequency.py +++ b/mne/decoding/time_frequency.py @@ -21,23 +21,23 @@ class TimeFrequency(MNETransformerMixin, BaseEstimator): ---------- freqs : array-like of float, shape (n_freqs,) The frequencies. - sfreq : float | int, default 1.0 + sfreq : float | int Sampling frequency of the data. - method : 'multitaper' | 'morlet', default 'morlet' + method : 'multitaper' | 'morlet' The time-frequency method. 'morlet' convolves a Morlet wavelet. 'multitaper' uses Morlet wavelets windowed with multiple DPSS multitapers. - n_cycles : float | array of float, default 7.0 + n_cycles : float | array of float Number of cycles in the Morlet wavelet. Fixed number or one per frequency. - time_bandwidth : float, default None + time_bandwidth : float If None and method=multitaper, will be set to 4.0 (3 tapers). Time x (Full) Bandwidth product. Only applies if method == 'multitaper'. The number of good tapers (low-bias) is chosen automatically based on this to equal floor(time_bandwidth - 1). - use_fft : bool, default True + use_fft : bool Use the FFT for convolutions or not. - decim : int | slice, default 1 + decim : int | slice To reduce memory usage, decimation factor after time-frequency decomposition. If `int`, returns tfr[..., ::decim]. @@ -46,7 +46,7 @@ class TimeFrequency(MNETransformerMixin, BaseEstimator): .. note:: Decimation may create aliasing artifacts, yet decimation is done after the convolutions. - output : str, default 'complex' + output : str * 'complex' : single trial complex. * 'power' : single trial power. * 'phase' : single trial phase. diff --git a/mne/decoding/transformer.py b/mne/decoding/transformer.py index 34cebe57bff..5ec026b0a39 100644 --- a/mne/decoding/transformer.py +++ b/mne/decoding/transformer.py @@ -138,7 +138,7 @@ class Scaler(MNETransformerMixin, BaseEstimator): Parameters ---------- %(info)s Only necessary if ``scalings`` is a dict or None. - scalings : dict, str, default None + scalings : dict, str Scaling method to be applied to data channel wise. * if scalings is None (default), scales mag by 1e15, grad by 1e13, @@ -152,10 +152,10 @@ class Scaler(MNETransformerMixin, BaseEstimator): :class:`sklearn.preprocessing.StandardScaler` is used. - with_mean : bool, default True + with_mean : bool If True, center the data using mean (or median) before scaling. Ignored for channel-type scaling. - with_std : bool, default True + with_std : bool If True, scale the data to unit variance (``scalings='mean'``), quantile range (``scalings='median``), or using channel type if ``scalings`` is a dict or None). @@ -654,7 +654,7 @@ class UnsupervisedSpatialFilter(MNETransformerMixin, BaseEstimator): ---------- estimator : instance of sklearn.base.BaseEstimator Estimator using some decomposition algorithm. - average : bool, default False + average : bool If True, the estimator is fitted on the average across samples (e.g. epochs). """ @@ -797,9 +797,9 @@ class TemporalFilter(MNETransformerMixin, BaseEstimator): h_freq : float | None High cut-off frequency in Hz. If None the data are only high-passed. - sfreq : float, default 1.0 + sfreq : float Sampling frequency in Hz. - filter_length : str | int, default 'auto' + filter_length : str | int Length of the FIR filter to use (if applicable): * int: specified length in samples. @@ -828,17 +828,17 @@ class TemporalFilter(MNETransformerMixin, BaseEstimator): min(max(h_freq * 0.25, 2.), info['sfreq'] / 2. - h_freq) Only used for ``method='fir'``. - n_jobs : int | str, default 1 + n_jobs : int | str Number of jobs to run in parallel. Can be 'cuda' if ``cupy`` is installed properly and method='fir'. - method : str, default 'fir' + method : str 'fir' will use overlap-add FIR filtering, 'iir' will use IIR forward-backward filtering (via filtfilt). - iir_params : dict | None, default None + iir_params : dict | None Dictionary of parameters to use for IIR filtering. See mne.filter.construct_iir_filter for details. If iir_params is None and method="iir", 4th order Butterworth will be used. - fir_window : str, default 'hamming' + fir_window : str The window to use in FIR design, can be "hamming", "hann", or "blackman". fir_design : str diff --git a/mne/decoding/xdawn.py b/mne/decoding/xdawn.py index ad0ad480679..0251cc6a1be 100644 --- a/mne/decoding/xdawn.py +++ b/mne/decoding/xdawn.py @@ -34,9 +34,9 @@ class XdawnTransformer(_GEDTransformer): Parameters ---------- - n_components : int (default 2) + n_components : int The number of components to decompose the signals. - reg : float | str | None (default None) + reg : float | str | None If not None (same as ``'empirical'``, default), allow regularization for covariance estimation. If float, shrinkage is used (0 <= shrinkage <= 1). diff --git a/mne/evoked.py b/mne/evoked.py index 2b30784f998..58c56314b29 100644 --- a/mne/evoked.py +++ b/mne/evoked.py @@ -131,12 +131,12 @@ class Evoked( condition : int | str | None Dataset ID number (int) or comment/name (str). Optional if there is only one data set in file. - proj : bool, optional + proj : bool Apply SSP projection vectors. kind : str Either ``'average'`` or ``'standard_error'``. The type of data to read. Only used if 'condition' is a str. - allow_maxshield : bool | str (default False) + allow_maxshield : bool | str If True, allow loading of data that has been recorded with internal active compensation (MaxShield). Data recorded with MaxShield should generally not be loaded directly, but should first be processed using @@ -1801,7 +1801,7 @@ def read_evokeds( Either ``'average'`` or ``'standard_error'``, the type of data to read. proj : bool If False, available projectors won't be applied to the data. - allow_maxshield : bool | str (default False) + allow_maxshield : bool | str If True, allow loading of data that has been recorded with internal active compensation (MaxShield). Data recorded with MaxShield should generally not be loaded directly, but should first be processed using diff --git a/mne/export/_egimff.py b/mne/export/_egimff.py index 185afb5f558..6e041dec0a7 100644 --- a/mne/export/_egimff.py +++ b/mne/export/_egimff.py @@ -27,7 +27,7 @@ def export_evokeds_mff(fname, evoked, history=None, *, overwrite=False, verbose= List of evoked datasets to export to one file. Note that the measurement info from the first evoked instance is used, so be sure that information matches. - history : None (default) | list of dict + history : None | list of dict Optional list of history entries (dictionaries) to be written to history.xml. This must adhere to the format described in mffpy.xml_files.History.content. If None, no history.xml will be diff --git a/mne/fixes.py b/mne/fixes.py index 70c6c8ffd61..3efe90a5031 100644 --- a/mne/fixes.py +++ b/mne/fixes.py @@ -221,7 +221,7 @@ def get_params(self, deep=True): Parameters ---------- - deep : bool, default=True + deep : bool If True, will return the parameters for this estimator and contained subobjects that are estimators. @@ -567,7 +567,7 @@ def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08): ---------- arr : array-like To be cumulatively summed as flat - axis : int, optional + axis : int Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array. rtol : float diff --git a/mne/forward/forward.py b/mne/forward/forward.py index e27422d9e05..08269704c08 100644 --- a/mne/forward/forward.py +++ b/mne/forward/forward.py @@ -524,10 +524,10 @@ def read_forward_solution(fname, include=(), exclude=(), *, ordered=True, verbos fname : path-like The file name, which should end with ``-fwd.fif``, ``-fwd.fif.gz``, ``_fwd.fif``, ``_fwd.fif.gz``, ``-fwd.h5``, or ``_fwd.h5``. - include : list, optional + include : list List of names of channels to include. If empty all channels are included. - exclude : list, optional + exclude : list List of names of channels to exclude. If empty include all channels. %(ordered)s %(verbose)s @@ -724,10 +724,10 @@ def convert_forward_solution( ---------- fwd : Forward The forward solution to modify. - surf_ori : bool, optional (default False) + surf_ori : bool Use surface-based source coordinate system? Note that force_fixed=True implies surf_ori=True. - force_fixed : bool, optional (default False) + force_fixed : bool If True, force fixed source orientation mode. copy : bool Whether to return a new instance or modify in place. @@ -1364,7 +1364,7 @@ def compute_depth_prior( The ``limit_depth_chs`` argument can take the following values: - * :data:`python:True` (default) + * : data:`python:True` Use only grad channels in depth weighting (equivalent to MNE C minimum-norm code). If grad channels aren't present, only mag channels will be used (if no mag, then eeg). This makes the depth @@ -1615,9 +1615,9 @@ def apply_forward( stc : SourceEstimate The source estimate from which the sensor space data is computed. %(info_not_none)s - start : int, optional + start : int Index of first time sample (index not time is seconds). - stop : int, optional + stop : int Index of first time sample not to include (index not time is seconds). %(use_cps)s @@ -1694,9 +1694,9 @@ def apply_forward_raw( stc : SourceEstimate The source estimate from which the sensor space data is computed. %(info_not_none)s - start : int, optional + start : int Index of first time sample (index not time is seconds). - stop : int, optional + stop : int Index of first time sample not to include (index not time is seconds). %(on_missing_fwd)s Default is "raise". diff --git a/mne/io/artemis123/artemis123.py b/mne/io/artemis123/artemis123.py index bf61fa6c481..b63313773ab 100644 --- a/mne/io/artemis123/artemis123.py +++ b/mne/io/artemis123/artemis123.py @@ -41,7 +41,7 @@ def read_raw_artemis123( %(verbose)s pos_fname : path-like | None If not None, load digitized head points from this file. - add_head_trans : bool (default True) + add_head_trans : bool If True attempt to perform initial head localization. Compute initial device to head coordinate transform using HPI coils. If no HPI coils are in info['dig'] hpi coils are assumed to be in canonical diff --git a/mne/io/base.py b/mne/io/base.py index bd50991690b..6064e067f7f 100644 --- a/mne/io/base.py +++ b/mne/io/base.py @@ -396,15 +396,15 @@ def _read_segment( Parameters ---------- - start : int, (optional) + start : int first sample to include (first is 0). If omitted, defaults to the first sample in data. - stop : int, (optional) + stop : int First sample to not include. If omitted, data is included to the end. - sel : array, optional + sel : array Indices of channels to select. - data_buffer : array or str, optional + data_buffer : array or str numpy array to fill with data read, must have the correct shape. If str, a np.memmap with the correct data type will be used to store the data. diff --git a/mne/io/ctf/ctf.py b/mne/io/ctf/ctf.py index 3c280dc0c24..2a394d2e0df 100644 --- a/mne/io/ctf/ctf.py +++ b/mne/io/ctf/ctf.py @@ -50,7 +50,7 @@ def read_raw_ctf( to ignore the system clock (e.g., if head positions are measured multiple times during a recording). %(preload)s - clean_names : bool, optional + clean_names : bool If True main channel names and compensation channel names will be cleaned from CTF suffixes. The default is False. %(verbose)s @@ -92,7 +92,7 @@ class RawCTF(BaseRaw): to ignore the system clock (e.g., if head positions are measured multiple times during a recording). %(preload)s - clean_names : bool, optional + clean_names : bool If True main channel names and compensation channel names will be cleaned from CTF suffixes. The default is False. %(verbose)s diff --git a/mne/io/eeglab/eeglab.py b/mne/io/eeglab/eeglab.py index d0b21a1e7d9..a1aab6aa2dc 100644 --- a/mne/io/eeglab/eeglab.py +++ b/mne/io/eeglab/eeglab.py @@ -575,7 +575,7 @@ class EpochsEEGLAB(BaseEpochs): EEGLAB (.set) file with each descriptions copied from ``eventtype``. tmin : float Start time before event. - baseline : None or tuple of length 2 (default (None, 0)) + baseline : None or tuple of length 2 The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". diff --git a/mne/io/egi/egimff.py b/mne/io/egi/egimff.py index f875d021308..56a68256a14 100644 --- a/mne/io/egi/egimff.py +++ b/mne/io/egi/egimff.py @@ -693,7 +693,7 @@ def read_evokeds_mff( channel_naming : str Channel naming convention for EEG channels. Defaults to 'E%%d' (resulting in channel names 'E1', 'E2', 'E3'...). - baseline : None (default) or tuple of length 2 + baseline : None or tuple of length 2 The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". If a is None the beginning of the data is used and if b is None then b diff --git a/mne/io/eyelink/_utils.py b/mne/io/eyelink/_utils.py index 6aa6d6441c8..6a9e8e62e07 100644 --- a/mne/io/eyelink/_utils.py +++ b/mne/io/eyelink/_utils.py @@ -688,7 +688,7 @@ def _adjust_times( sfreq : int | float: sampling frequency of the data - time_col : str (default 'time'): + time_col : str name of column with the timestamps (e.g. 9511881, 9511882, ...) Returns @@ -726,7 +726,7 @@ def _find_overlaps(df, max_time=0.05): ---------- df : pandas.DataFrame Pandas DataFrame with occular events (fixations, saccades, blinks) - max_time : float (default 0.05) + max_time : float Time in seconds. Defaults to .05 (50 ms) Returns @@ -793,7 +793,7 @@ def _href_to_radian(opposite, f=15_000): ---------- opposite : int The x or y coordinate in an HREF gaze sample. - f : int (default 15_000) + f : int distance of plane from the eye. Defaults to 15,000 units, which was taken from the Eyelink 1000 plus user manual. diff --git a/mne/io/fiff/raw.py b/mne/io/fiff/raw.py index 8e76d16b3d6..639f805d3f2 100644 --- a/mne/io/fiff/raw.py +++ b/mne/io/fiff/raw.py @@ -55,7 +55,7 @@ class Raw(BaseRaw): .. versionchanged:: 0.18 Support for file-like objects. - allow_maxshield : bool | str (default False) + allow_maxshield : bool | str If True, allow loading of data that has been recorded with internal active compensation (MaxShield). Data recorded with MaxShield should generally not be loaded directly, but should first be processed using @@ -521,7 +521,7 @@ def read_raw_fif( .. versionchanged:: 0.18 Support for file-like objects. - allow_maxshield : bool | str (default False) + allow_maxshield : bool | str If True, allow loading of data that has been recorded with internal active compensation (MaxShield). Data recorded with MaxShield should generally not be loaded directly, but should first be processed using diff --git a/mne/io/fil/fil.py b/mne/io/fil/fil.py index 0f5abace580..638656f3f77 100644 --- a/mne/io/fil/fil.py +++ b/mne/io/fil/fil.py @@ -38,7 +38,7 @@ def read_raw_fil( ---------- binfile : path-like Path to the MEG data binary (ending in ``'_meg.bin'``). - precision : str, optional + precision : str How is the data represented? ``'single'`` if 32-bit or ``'double'`` if 64-bit (default is single). %(preload)s @@ -65,7 +65,7 @@ class RawFIL(BaseRaw): ---------- binfile : path-like Path to the MEG data binary (ending in ``'_meg.bin'``). - precision : str, optional + precision : str How is the data represented? ``'single'`` if 32-bit or ``'double'`` if 64-bit (default is single). %(preload)s diff --git a/mne/minimum_norm/time_frequency.py b/mne/minimum_norm/time_frequency.py index 94634705539..30d92ca71c2 100644 --- a/mne/minimum_norm/time_frequency.py +++ b/mne/minimum_norm/time_frequency.py @@ -214,7 +214,7 @@ def source_band_induced_power( Do convolutions in time or frequency domain with FFT. decim : int Temporal decimation factor. - baseline : None (default) or tuple, shape (2,) + baseline : None or tuple, shape (2,) The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". If a is None the beginning of the data is used and if b is None then b @@ -640,7 +640,7 @@ def source_induced_power( If "normal", rather than pooling the orientations by taking the norm, only the radial component is kept. This is only implemented when working with loose orientations. - baseline : None (default) or tuple of length 2 + baseline : None or tuple of length 2 The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". diff --git a/mne/preprocessing/artifact_detection.py b/mne/preprocessing/artifact_detection.py index 8674d6e22b3..32758dec888 100644 --- a/mne/preprocessing/artifact_detection.py +++ b/mne/preprocessing/artifact_detection.py @@ -176,7 +176,7 @@ def annotate_movement( Head translation velocity limit in meters per second. mean_distance_limit : float Head position limit from mean recording in meters. - use_dev_head_trans : 'average' (default) | 'info' + use_dev_head_trans : 'average' | 'info' Identify the device to head transform used to define the fixed HPI locations for computing moving distances. If ``average`` the average device to head transform is diff --git a/mne/preprocessing/tests/test_infomax.py b/mne/preprocessing/tests/test_infomax.py index 36cc5663379..6ac98b85136 100644 --- a/mne/preprocessing/tests/test_infomax.py +++ b/mne/preprocessing/tests/test_infomax.py @@ -23,7 +23,7 @@ def center_and_norm(x, axis=-1): x: ndarray Array with an axis of observations (statistical units) measured on random variables. - axis: int, optional + axis : int Axis along which the mean and variance are calculated. """ x = np.rollaxis(x, axis) diff --git a/mne/preprocessing/xdawn.py b/mne/preprocessing/xdawn.py index fd061323a36..b0ebaa6c593 100644 --- a/mne/preprocessing/xdawn.py +++ b/mne/preprocessing/xdawn.py @@ -121,9 +121,9 @@ def _fit_xdawn( The epochs data. y : array, shape (n_epochs) The epochs class. - n_components : int (default 2) + n_components : int The number of components to decompose the signals signals. - reg : float | str | None (default None) + reg : float | str | None If not None (same as ``'empirical'``, default), allow regularization for covariance estimation. If float, shrinkage is used (0 <= shrinkage <= 1). @@ -224,16 +224,16 @@ class Xdawn(XdawnTransformer): Parameters ---------- - n_components : int, (default 2) + n_components : int The number of components to decompose the signals. signal_cov : None | Covariance | ndarray, shape (n_channels, n_channels) (default None). The signal covariance used for whitening of the data. if None, the covariance is estimated from the epochs signal. - correct_overlap : 'auto' or bool (default 'auto') + correct_overlap : 'auto' or bool Compute the independent evoked responses per condition, while correcting for event overlaps if any. If 'auto', then overlapp_correction = True if the events do overlap. - reg : float | str | None (default None) + reg : float | str | None If not None (same as ``'empirical'``, default), allow regularization for covariance estimation. If float, shrinkage is used (0 <= shrinkage <= 1). @@ -285,7 +285,7 @@ def fit(self, epochs, y=None): ---------- epochs : instance of Epochs An instance of Epoch on which Xdawn filters will be fitted. - y : ndarray | None (default None) + y : ndarray | None If None, used epochs.events[:, 2]. Returns @@ -399,14 +399,14 @@ def apply(self, inst, event_id=None, include=None, exclude=None): ---------- inst : instance of Raw | Epochs | Evoked The data to be processed. - event_id : dict | list of str | None (default None) + event_id : dict | list of str | None The kind of event to apply. if None, a dict of inst will be return one for each type of event xdawn has been fitted. - include : array_like of int | None (default None) + include : array_like of int | None The indices referring to columns in the ummixing matrix. The components to be kept. If None, the first n_components (as defined in the Xdawn constructor) will be kept. - exclude : array_like of int | None (default None) + exclude : array_like of int | None The indices referring to columns in the ummixing matrix. The components to be zeroed out. If None, all the components except the first n_components will be exclude. diff --git a/mne/rank.py b/mne/rank.py index 65833a5363f..c9076fc395c 100644 --- a/mne/rank.py +++ b/mne/rank.py @@ -382,7 +382,7 @@ def compute_rank( inst : instance of Raw, Epochs, or Covariance Raw measurements to compute the rank from or the covariance. %(rank_none)s - scalings : dict | None (default None) + scalings : dict | None Defaults to ``dict(mag=1e15, grad=1e13, eeg=1e6)``. These defaults will scale different channel types to comparable values. diff --git a/mne/source_space/_source_space.py b/mne/source_space/_source_space.py index e062ff69daa..c57b2895ac6 100644 --- a/mne/source_space/_source_space.py +++ b/mne/source_space/_source_space.py @@ -849,7 +849,7 @@ def _read_source_spaces_from_tree(fid, tree, patch_stats=False, verbose=None): An open file descriptor. tree : dict The FIF tree structure if source is a file id. - patch_stats : bool, optional (default False) + patch_stats : bool Calculate and add cortical patch statistics to the surfaces. %(verbose)s @@ -886,7 +886,7 @@ def read_source_spaces(fname, patch_stats=False, verbose=None): fname : path-like The name of the file, which should end with ``-src.fif`` or ``-src.fif.gz``. - patch_stats : bool, optional (default False) + patch_stats : bool Calculate and add cortical patch statistics to the surfaces. %(verbose)s diff --git a/mne/stats/permutations.py b/mne/stats/permutations.py index c9c5fe59b10..60f9ce40052 100644 --- a/mne/stats/permutations.py +++ b/mne/stats/permutations.py @@ -45,7 +45,7 @@ def permutation_t_test( permutations are tested. It's the exact test, that can be untractable when the number of samples is big (e.g. > 20). If n_permutations >= 2**n_samples then the exact test is performed. - tail : -1 or 0 or 1 (default = 0) + tail : -1 or 0 or 1 If tail is 1, the alternative hypothesis is that the mean of the data is greater than 0 (upper tailed test). If tail is 0, the alternative hypothesis is that the mean of the data is different diff --git a/mne/tests/test_docstring_parameters.py b/mne/tests/test_docstring_parameters.py index 4602112af6a..ac888f1b70b 100644 --- a/mne/tests/test_docstring_parameters.py +++ b/mne/tests/test_docstring_parameters.py @@ -102,6 +102,11 @@ def _func_name(func, cls=None): error_ignores_specific = { # specific instances to skip ("regress_artifact", "SS05"), # "Regress" is actually imperative } +bad_docstring_type = re.compile( + r"(?:\(\s*default\b|,\s*default(?=\s|=|:)|" + r"(?:^|,)\s*(?:optional|\(\s*optional\s*\))(?:$|\s*\())", + re.IGNORECASE, +) subclass_name_ignores = ( ( dict, @@ -124,8 +129,25 @@ def _func_name(func, cls=None): ) +@pytest.mark.parametrize( + ("type_description", "is_bad"), + [ + ("bool, optional", True), + ("bool, (optional)", True), + ("bool, default=True", True), + ("bool (default True)", True), + ('{"default", "pandas"}', False), + ("bool | None", False), + ], +) +def test_bad_docstring_type(type_description, is_bad): + """Test detection of defaults and optional in parameter types.""" + assert bool(bad_docstring_type.search(type_description)) == is_bad + + def check_parameters_match(func, *, cls=None, where): """Check docstring, return list of incorrect results.""" + from numpydoc.docscrape import FunctionDoc from numpydoc.validate import validate name = _func_name(func, cls) @@ -144,6 +166,15 @@ def check_parameters_match(func, *, cls=None, where): if err[0] not in error_ignores and (name.split(".")[-1], err[0]) not in error_ignores_specific ] + module = inspect.getmodule(func) + if module is not None and module.__name__.startswith("mne."): + for param in FunctionDoc(func)["Parameters"]: + if bad_docstring_type.search(param.type): + incorrect.append( + f"{where} : {name} : {param.name} : type description " + f"{param.type!r} includes a default or 'optional'; put defaults " + "in the parameter description instead" + ) # Add a check that all public functions and methods that have "verbose" # set the default verbose=None if cls is None: @@ -522,12 +553,6 @@ def _type_atoms(type_str): s = type_str.replace("``", "").replace("`", "") # drop reST inline literals s = re.sub(r":\w+:", "", s) # drop sphinx roles, e.g. :class: s = s.replace("~", "") # drop the sphinx "abbreviate" marker - # TODO: neither ``default X`` nor ``optional`` belongs in a numpydoc *type* -- - # MNE style puts the default in the parameter description prose instead. Drop - # these three normalizations to find (and then fix) the docstrings doing it. - s = re.sub(r"\s*\(\s*default[^)]*\)", "", s, flags=re.I) # (default X) - s = re.sub(r"\s*,\s*default[:=]?\s*[^,|]+", "", s, flags=re.I) # , default X - s = re.sub(r"\s*,?\s*optional\b", "", s, flags=re.I) # , optional s = re.sub(r"\binstance of\b", "", s) s = re.sub(r",?\s*(?:of )?shape\s*\(?[^)|]*\)?", "", s) # shape (n, m) suffixes s = re.sub(r"\btuple of length \d+\b", "tuple", s, flags=re.I) @@ -587,7 +612,6 @@ def _is_type_like(atom): "Evoked instance, or list of Evoked instances", "None | colormap | (colormap, bool) | 'interactive'", "Raw object", - "bool, str, or None (default None)", "instance of matplotlib Axes | None", "list of (int | str) | tuple of (int | str)", "list of (int | str) | tuple of (int | str) | ``'auto'``", diff --git a/mne/time_frequency/multitaper.py b/mne/time_frequency/multitaper.py index d917056b2ac..2f6a24bf339 100644 --- a/mne/time_frequency/multitaper.py +++ b/mne/time_frequency/multitaper.py @@ -502,7 +502,7 @@ def tfr_array_multitaper( use_fft : bool Use the FFT for convolutions or not. Defaults to True. %(decim_tfr)s - output : str, default 'complex' + output : str * ``'complex'`` : single trial per taper complex values. * ``'power'`` : single trial power. @@ -513,7 +513,7 @@ def tfr_array_multitaper( coherence across trials. %(n_jobs)s The parallelization is implemented across channels. - return_weights : bool, default False + return_weights : bool If True, return the taper weights. Only applies if ``output='complex'`` or ``'phase'``. diff --git a/mne/time_frequency/tfr.py b/mne/time_frequency/tfr.py index dace3a5b14b..61824c62f31 100644 --- a/mne/time_frequency/tfr.py +++ b/mne/time_frequency/tfr.py @@ -95,7 +95,7 @@ def morlet(sfreq, freqs, n_cycles=7.0, sigma=None, zero_mean=False): n_cycles : float | array-like, shape (n_freqs,) Number of cycles. Can be a fixed number (float) or one per frequency (array-like). - sigma : float, default None + sigma : float It controls the width of the wavelet ie its temporal resolution. If sigma is None the temporal resolution is adapted with the frequency like for all wavelet transform. @@ -103,7 +103,7 @@ def morlet(sfreq, freqs, n_cycles=7.0, sigma=None, zero_mean=False): If sigma is fixed the temporal resolution is fixed like for the short time Fourier transform and the number of oscillations increases with the frequency. - zero_mean : bool, default False + zero_mean : bool Make sure the wavelet has a mean of zero. Returns @@ -248,14 +248,14 @@ def _make_dpss( The sampling frequency. freqs : ndarray, shape (n_freqs,) The frequencies in Hz. - n_cycles : float | ndarray, shape (n_freqs,), default 7. + n_cycles : float | ndarray, shape (n_freqs,) The number of cycles globally or for each frequency. - time_bandwidth : float, default 4.0 + time_bandwidth : float Time x Bandwidth product. The number of good tapers (low-bias) is chosen automatically based on this to equal floor(time_bandwidth - 1). Default is 4.0, giving 3 good tapers. - zero_mean : bool | None, , default False + zero_mean : bool | None Make sure the wavelet has a mean of zero. return_weights : bool Whether to return the concentration weights. @@ -353,7 +353,7 @@ def _cwt_gen(X, Ws, *, fsize=0, mode="same", decim=1, use_fft=True): FFT length. mode : {'full', 'valid', 'same'} See numpy.convolve. - decim : int | slice, default 1 + decim : int | slice To reduce memory usage, decimation factor after time-frequency decomposition. If `int`, returns tfr[..., ::decim]. @@ -361,7 +361,7 @@ def _cwt_gen(X, Ws, *, fsize=0, mode="same", decim=1, use_fft=True): .. note:: Decimation may create aliasing artifacts. - use_fft : bool, default True + use_fft : bool Use the FFT for convolutions or not. Returns @@ -448,26 +448,26 @@ def _compute_tfr( The epochs.default ``'complex'`` freqs : array-like of floats, shape (n_freqs) The frequencies. - sfreq : float | int, default 1.0 + sfreq : float | int Sampling frequency of the data. - method : 'multitaper' | 'morlet', default 'morlet' + method : 'multitaper' | 'morlet' The time-frequency method. 'morlet' convolves a Morlet wavelet. 'multitaper' uses complex exponentials windowed with multiple DPSS tapers. - n_cycles : float | array of float, default 7.0 + n_cycles : float | array of float Number of cycles in the wavelet. Fixed number or one per frequency. - zero_mean : bool | None, default None + zero_mean : bool | None None means True for method='multitaper' and False for method='morlet'. If True, make sure the wavelets have a mean of zero. - time_bandwidth : float, default None + time_bandwidth : float If None and method=multitaper, will be set to 4.0 (3 tapers). Time x (Full) Bandwidth product. Only applies if method == 'multitaper'. The number of good tapers (low-bias) is chosen automatically based on this to equal floor(time_bandwidth - 1). - use_fft : bool, default True + use_fft : bool Use the FFT for convolutions or not. - decim : int | slice, default 1 + decim : int | slice To reduce memory usage, decimation factor after time-frequency decomposition. If `int`, returns tfr[..., ::decim]. @@ -486,7 +486,7 @@ def _compute_tfr( * 'itc' : inter-trial coherence. * 'avg_power_itc' : average of single trial power and inter-trial coherence across trials. - return_weights : bool, default False + return_weights : bool Whether to return the taper weights. Only applies if method='multitaper' and output='complex' or 'phase'. %(n_jobs)s @@ -878,17 +878,17 @@ def tfr_morlet( The epochs or evoked object. %(freqs_tfr_array)s %(n_cycles_tfr)s - use_fft : bool, default False + use_fft : bool The fft based convolution or not. - return_itc : bool, default True + return_itc : bool Return inter-trial coherence (ITC) as well as averaged power. Must be ``False`` for evoked data. %(decim_tfr)s %(n_jobs)s - picks : array-like of int | None, default None + picks : array-like of int | None The indices of the channels to decompose. If None, all available good data channels are decomposed. - zero_mean : bool, default True + zero_mean : bool Make sure the wavelet has a mean of zero. .. versionadded:: 0.13.0 @@ -978,7 +978,7 @@ def tfr_array_morlet( use_fft : bool Use the FFT for convolutions or not. default True. %(decim_tfr)s - output : str, default ``'complex'`` + output : str * ``'complex'`` : single trial complex. * ``'power'`` : single trial power. @@ -1070,9 +1070,9 @@ def tfr_multitaper( %(freqs_tfr_array)s %(n_cycles_tfr)s %(time_bandwidth_tfr)s - use_fft : bool, default True + use_fft : bool The fft based convolution or not. - return_itc : bool, default True + return_itc : bool Return inter-trial coherence (ITC) as well as averaged (or single-trial) power. %(decim_tfr)s diff --git a/mne/utils/config.py b/mne/utils/config.py index 34677ed4db4..be935e269bc 100644 --- a/mne/utils/config.py +++ b/mne/utils/config.py @@ -236,7 +236,7 @@ def _open_lock(path, *args, **kwargs): ---------- path : str The path to the file to be opened. - *args, **kwargs : optional + *args, **kwargs : arguments Additional arguments and keyword arguments to be passed to the `open` function. diff --git a/mne/utils/docs.py b/mne/utils/docs.py index 4723ad20019..3f3a8a7485e 100644 --- a/mne/utils/docs.py +++ b/mne/utils/docs.py @@ -358,7 +358,7 @@ def _reflow_param_docstring(docstring, has_first_line=True, width=75): """ docdict["average_tfr"] = """ -average : bool, default True +average : bool If ``False`` return an `EpochsTFR` containing separate TFRs for each epoch. If ``True`` return an `AverageTFR` containing the average of all TFRs across epochs. @@ -1646,14 +1646,14 @@ def _reflow_param_docstring(docstring, has_first_line=True, width=75): """ docdict["eyelink_apply_offsets"] = """ -apply_offsets : bool (default False) +apply_offsets : bool Adjusts the onset time of the :class:`~mne.Annotations` created from Eyelink experiment messages, if offset values exist in the ASCII file. If False, any offset-like values will be prepended to the annotation description. """ docdict["eyelink_create_annotations"] = """ -create_annotations : bool | list (default True) +create_annotations : bool | list Whether to create :class:`~mne.Annotations` from occular events (blinks, fixations, saccades) and experiment messages. If a list, must contain one or more of ``['fixations', 'saccades',' blinks', messages']``. @@ -1662,7 +1662,7 @@ def _reflow_param_docstring(docstring, has_first_line=True, width=75): """ docdict["eyelink_find_overlaps"] = """ -find_overlaps : bool (default False) +find_overlaps : bool Combine left and right eye :class:`mne.Annotations` (blinks, fixations, saccades) if their start times and their stop times are both not separated by more than overlap_threshold. @@ -1673,7 +1673,7 @@ def _reflow_param_docstring(docstring, has_first_line=True, width=75): Path to the eyelink file (``.asc``).""" docdict["eyelink_overlap_threshold"] = """ -overlap_threshold : float (default 0.05) +overlap_threshold : float Time in seconds. Threshold of allowable time-gap between both the start and stop times of the left and right eyes. If the gap is larger than the threshold, the :class:`mne.Annotations` will be kept separate (i.e. ``"blink_L"``, @@ -3687,7 +3687,7 @@ def _reflow_param_docstring(docstring, has_first_line=True, width=75): """ docdict["preload"] = """ -preload : bool or str (default False) +preload : bool or str Preload data into memory for data manipulation and faster indexing. If True, the data will be preloaded into memory (fast, requires large amount of memory). If preload is a string, preload is the @@ -3695,7 +3695,7 @@ def _reflow_param_docstring(docstring, has_first_line=True, width=75): on the hard drive (slower, requires less memory).""" docdict["preload_concatenate"] = """ -preload : bool, str, or None (default None) +preload : bool | str | None Preload data into memory for data manipulation and faster indexing. If True, the data will be preloaded into memory (fast, requires large amount of memory). If preload is a string, preload is the @@ -5779,7 +5779,7 @@ def _docformat(docstring, docdict=None, funcname=None): ---------- docstring : string docstring from function, possibly with dict formatting strings - docdict : dict, optional + docdict : dict dictionary with keys that match the dict formatting strings and values that are docstring fragments to be inserted. The indentation of the inserted docstrings is set to match the diff --git a/mne/viz/_brain/_brain.py b/mne/viz/_brain/_brain.py index 837f588846c..2a57f73d81a 100644 --- a/mne/viz/_brain/_brain.py +++ b/mne/viz/_brain/_brain.py @@ -1857,7 +1857,7 @@ def add_data( initial_time : float | None Time initially shown in the plot. ``None`` to use the first time sample (default). - scale_factor : float | None (default) + scale_factor : float | None The scale factor to use when displaying glyphs for vector-valued data. vector_alpha : float | None diff --git a/mne/viz/ica.py b/mne/viz/ica.py index 3c2ae69cbdf..a3f4045bfc0 100644 --- a/mne/viz/ica.py +++ b/mne/viz/ica.py @@ -676,9 +676,9 @@ def _prepare_data_ica_properties(inst, ica, reject_by_annotation=True, reject="a The ICA solution. inst : instance of Epochs or Raw The data to use in plotting properties. - reject_by_annotation : bool, optional + reject_by_annotation : bool [description], by default True - reject : str, optional + reject : str [description], by default 'auto' Returns @@ -1075,7 +1075,7 @@ def plot_ica_overlay( before and after cleaning. A second panel with the RMS for MEG sensors and the :term:`GFP` for EEG sensors is displayed. If `~mne.Evoked`, butterfly traces for signals before and after cleaning will be superimposed. - exclude : array-like of int | None (default) + exclude : array-like of int | None The components marked for exclusion. If ``None`` (default), the components listed in ``ICA.exclude`` will be used. %(picks_base)s all channels that were included during fitting. diff --git a/mne/viz/topomap.py b/mne/viz/topomap.py index 964faf8224e..d1ab1f00587 100644 --- a/mne/viz/topomap.py +++ b/mne/viz/topomap.py @@ -3885,7 +3885,7 @@ def plot_arrowmap( info_to : instance of Info | None The measurement info to interpolate to. If None, it is assumed to be the same as info_from. - scale : float, default 3e-10 + scale : float To scale the arrows. %(vlim_plot_topomap)s From d84f84436e961212f535a3e583d109489f971494 Mon Sep 17 00:00:00 2001 From: Daria Agafonova Date: Fri, 24 Jul 2026 19:49:57 +0200 Subject: [PATCH 2/3] DOC Fix changelog and parameter type formatting --- doc/changes/dev/{14095.other.rst => 14100.other.rst} | 0 mne/decoding/_fixes.py | 2 +- mne/decoding/base.py | 2 +- mne/export/_egimff.py | 2 +- mne/io/base.py | 2 +- mne/io/eeglab/eeglab.py | 2 +- mne/io/egi/egimff.py | 2 +- mne/minimum_norm/time_frequency.py | 4 ++-- mne/preprocessing/artifact_detection.py | 2 +- mne/preprocessing/xdawn.py | 2 +- mne/stats/permutations.py | 2 +- mne/tests/test_docstring_parameters.py | 5 ++++- mne/utils/docs.py | 2 +- 13 files changed, 16 insertions(+), 13 deletions(-) rename doc/changes/dev/{14095.other.rst => 14100.other.rst} (100%) diff --git a/doc/changes/dev/14095.other.rst b/doc/changes/dev/14100.other.rst similarity index 100% rename from doc/changes/dev/14095.other.rst rename to doc/changes/dev/14100.other.rst diff --git a/mne/decoding/_fixes.py b/mne/decoding/_fixes.py index 813c74343a6..8ab25bc13c6 100644 --- a/mne/decoding/_fixes.py +++ b/mne/decoding/_fixes.py @@ -65,7 +65,7 @@ def validate_data( call to `partial_fit`. All other methods that validate `X` should set `reset=False`. - validate_separately : False or tuple of dicts + validate_separately : False | tuple of dicts Only used if `y` is not `None`. If `False`, call :func:`~sklearn.utils.check_X_y`. Else, it must be a tuple of kwargs to be used for calling :func:`~sklearn.utils.check_array` on `X` diff --git a/mne/decoding/base.py b/mne/decoding/base.py index fe2707e1fd1..07de1a406d8 100644 --- a/mne/decoding/base.py +++ b/mne/decoding/base.py @@ -844,7 +844,7 @@ def cross_val_multiscore( %(verbose)s fit_params : dict Parameters to pass to the fit method of the estimator. - pre_dispatch : int, or str + pre_dispatch : int | str Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched diff --git a/mne/export/_egimff.py b/mne/export/_egimff.py index 6e041dec0a7..3804c02019f 100644 --- a/mne/export/_egimff.py +++ b/mne/export/_egimff.py @@ -27,7 +27,7 @@ def export_evokeds_mff(fname, evoked, history=None, *, overwrite=False, verbose= List of evoked datasets to export to one file. Note that the measurement info from the first evoked instance is used, so be sure that information matches. - history : None | list of dict + history : list of dict | None Optional list of history entries (dictionaries) to be written to history.xml. This must adhere to the format described in mffpy.xml_files.History.content. If None, no history.xml will be diff --git a/mne/io/base.py b/mne/io/base.py index 6064e067f7f..3aa7c4b0a49 100644 --- a/mne/io/base.py +++ b/mne/io/base.py @@ -404,7 +404,7 @@ def _read_segment( If omitted, data is included to the end. sel : array Indices of channels to select. - data_buffer : array or str + data_buffer : array | str numpy array to fill with data read, must have the correct shape. If str, a np.memmap with the correct data type will be used to store the data. diff --git a/mne/io/eeglab/eeglab.py b/mne/io/eeglab/eeglab.py index a1aab6aa2dc..4fc6ce3bae6 100644 --- a/mne/io/eeglab/eeglab.py +++ b/mne/io/eeglab/eeglab.py @@ -575,7 +575,7 @@ class EpochsEEGLAB(BaseEpochs): EEGLAB (.set) file with each descriptions copied from ``eventtype``. tmin : float Start time before event. - baseline : None or tuple of length 2 + baseline : tuple of length 2 | None The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". diff --git a/mne/io/egi/egimff.py b/mne/io/egi/egimff.py index 56a68256a14..f734e45bf66 100644 --- a/mne/io/egi/egimff.py +++ b/mne/io/egi/egimff.py @@ -693,7 +693,7 @@ def read_evokeds_mff( channel_naming : str Channel naming convention for EEG channels. Defaults to 'E%%d' (resulting in channel names 'E1', 'E2', 'E3'...). - baseline : None or tuple of length 2 + baseline : tuple of length 2 | None The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". If a is None the beginning of the data is used and if b is None then b diff --git a/mne/minimum_norm/time_frequency.py b/mne/minimum_norm/time_frequency.py index 30d92ca71c2..00cc4d6fa79 100644 --- a/mne/minimum_norm/time_frequency.py +++ b/mne/minimum_norm/time_frequency.py @@ -214,7 +214,7 @@ def source_band_induced_power( Do convolutions in time or frequency domain with FFT. decim : int Temporal decimation factor. - baseline : None or tuple, shape (2,) + baseline : tuple of length 2 | None The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". If a is None the beginning of the data is used and if b is None then b @@ -640,7 +640,7 @@ def source_induced_power( If "normal", rather than pooling the orientations by taking the norm, only the radial component is kept. This is only implemented when working with loose orientations. - baseline : None or tuple of length 2 + baseline : tuple of length 2 | None The time interval to apply baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". diff --git a/mne/preprocessing/artifact_detection.py b/mne/preprocessing/artifact_detection.py index 32758dec888..7d286958ea1 100644 --- a/mne/preprocessing/artifact_detection.py +++ b/mne/preprocessing/artifact_detection.py @@ -176,7 +176,7 @@ def annotate_movement( Head translation velocity limit in meters per second. mean_distance_limit : float Head position limit from mean recording in meters. - use_dev_head_trans : 'average' | 'info' + use_dev_head_trans : 'average' | 'info' Identify the device to head transform used to define the fixed HPI locations for computing moving distances. If ``average`` the average device to head transform is diff --git a/mne/preprocessing/xdawn.py b/mne/preprocessing/xdawn.py index b0ebaa6c593..f985b94ce28 100644 --- a/mne/preprocessing/xdawn.py +++ b/mne/preprocessing/xdawn.py @@ -229,7 +229,7 @@ class Xdawn(XdawnTransformer): signal_cov : None | Covariance | ndarray, shape (n_channels, n_channels) (default None). The signal covariance used for whitening of the data. if None, the covariance is estimated from the epochs signal. - correct_overlap : 'auto' or bool + correct_overlap : 'auto' | bool Compute the independent evoked responses per condition, while correcting for event overlaps if any. If 'auto', then overlapp_correction = True if the events do overlap. diff --git a/mne/stats/permutations.py b/mne/stats/permutations.py index 60f9ce40052..903e1b56881 100644 --- a/mne/stats/permutations.py +++ b/mne/stats/permutations.py @@ -45,7 +45,7 @@ def permutation_t_test( permutations are tested. It's the exact test, that can be untractable when the number of samples is big (e.g. > 20). If n_permutations >= 2**n_samples then the exact test is performed. - tail : -1 or 0 or 1 + tail : -1 | 0 | 1 If tail is 1, the alternative hypothesis is that the mean of the data is greater than 0 (upper tailed test). If tail is 0, the alternative hypothesis is that the mean of the data is different diff --git a/mne/tests/test_docstring_parameters.py b/mne/tests/test_docstring_parameters.py index ac888f1b70b..87526151371 100644 --- a/mne/tests/test_docstring_parameters.py +++ b/mne/tests/test_docstring_parameters.py @@ -104,7 +104,7 @@ def _func_name(func, cls=None): } bad_docstring_type = re.compile( r"(?:\(\s*default\b|,\s*default(?=\s|=|:)|" - r"(?:^|,)\s*(?:optional|\(\s*optional\s*\))(?:$|\s*\())", + r"(?:^|,)\s*(?:optional|\(\s*optional\s*\))(?=\s*(?:$|[|,])))", re.IGNORECASE, ) subclass_name_ignores = ( @@ -134,9 +134,12 @@ def _func_name(func, cls=None): [ ("bool, optional", True), ("bool, (optional)", True), + ("bool, optional | str", True), + ("bool, (optional) | str", True), ("bool, default=True", True), ("bool (default True)", True), ('{"default", "pandas"}', False), + ("{'optional', 'required'}", False), ("bool | None", False), ], ) diff --git a/mne/utils/docs.py b/mne/utils/docs.py index 3f3a8a7485e..42be1145233 100644 --- a/mne/utils/docs.py +++ b/mne/utils/docs.py @@ -3687,7 +3687,7 @@ def _reflow_param_docstring(docstring, has_first_line=True, width=75): """ docdict["preload"] = """ -preload : bool or str +preload : bool | str Preload data into memory for data manipulation and faster indexing. If True, the data will be preloaded into memory (fast, requires large amount of memory). If preload is a string, preload is the From 20d3a123ccfe0dec65953c911861460aacae92eb Mon Sep 17 00:00:00 2001 From: Daria Agafonova Date: Sat, 25 Jul 2026 22:23:20 +0200 Subject: [PATCH 3/3] DOC Address review comments on parameter types --- mne/decoding/_fixes.py | 4 ++-- mne/decoding/ssd.py | 2 +- mne/decoding/time_frequency.py | 2 +- mne/decoding/transformer.py | 2 +- mne/forward/forward.py | 2 +- mne/tests/test_docstring_parameters.py | 23 +++++++++++++++++++++++ mne/time_frequency/tfr.py | 4 ++-- 7 files changed, 31 insertions(+), 8 deletions(-) diff --git a/mne/decoding/_fixes.py b/mne/decoding/_fixes.py index 8ab25bc13c6..e66f4e04b2a 100644 --- a/mne/decoding/_fixes.py +++ b/mne/decoding/_fixes.py @@ -33,7 +33,7 @@ def validate_data( The estimator to validate the input for. X : {array-like, sparse matrix, dataframe} of shape \ - (n_samples, n_features), default='no validation' + (n_samples, n_features) | 'no_validation' The input samples. If `'no_validation'`, no validation is performed on `X`. This is useful for meta-estimator which can delegate input validation to @@ -41,7 +41,7 @@ def validate_data( the only accepted `check_params` are `multi_output` and `y_numeric`. - y : array-like of shape (n_samples,) + y : array-like of shape (n_samples,) | None | 'no_validation' The targets. - If `None`, :func:`~sklearn.utils.check_array` is called on `X`. If diff --git a/mne/decoding/ssd.py b/mne/decoding/ssd.py index d00a17ca626..522e2c53753 100644 --- a/mne/decoding/ssd.py +++ b/mne/decoding/ssd.py @@ -59,7 +59,7 @@ class SSD(_GEDTransformer): return_filtered : bool If return_filtered is True, data is bandpassed and projected onto the SSD components. - n_fft : int + n_fft : int | None If sort_by_spectral_ratio is set to True, then the SSD sources will be sorted according to their spectral ratio which is calculated based on :func:`mne.time_frequency.psd_array_welch`. The n_fft parameter sets the diff --git a/mne/decoding/time_frequency.py b/mne/decoding/time_frequency.py index bbfe57277ca..e499b47241e 100644 --- a/mne/decoding/time_frequency.py +++ b/mne/decoding/time_frequency.py @@ -30,7 +30,7 @@ class TimeFrequency(MNETransformerMixin, BaseEstimator): n_cycles : float | array of float Number of cycles in the Morlet wavelet. Fixed number or one per frequency. - time_bandwidth : float + time_bandwidth : float | None If None and method=multitaper, will be set to 4.0 (3 tapers). Time x (Full) Bandwidth product. Only applies if method == 'multitaper'. The number of good tapers (low-bias) is diff --git a/mne/decoding/transformer.py b/mne/decoding/transformer.py index 5ec026b0a39..845a03e4f76 100644 --- a/mne/decoding/transformer.py +++ b/mne/decoding/transformer.py @@ -138,7 +138,7 @@ class Scaler(MNETransformerMixin, BaseEstimator): Parameters ---------- %(info)s Only necessary if ``scalings`` is a dict or None. - scalings : dict, str + scalings : dict | str | None Scaling method to be applied to data channel wise. * if scalings is None (default), scales mag by 1e15, grad by 1e13, diff --git a/mne/forward/forward.py b/mne/forward/forward.py index 08269704c08..3602362eb20 100644 --- a/mne/forward/forward.py +++ b/mne/forward/forward.py @@ -1364,7 +1364,7 @@ def compute_depth_prior( The ``limit_depth_chs`` argument can take the following values: - * : data:`python:True` + * :data:`python:True` (default) Use only grad channels in depth weighting (equivalent to MNE C minimum-norm code). If grad channels aren't present, only mag channels will be used (if no mag, then eeg). This makes the depth diff --git a/mne/tests/test_docstring_parameters.py b/mne/tests/test_docstring_parameters.py index 87526151371..69f504817c1 100644 --- a/mne/tests/test_docstring_parameters.py +++ b/mne/tests/test_docstring_parameters.py @@ -148,6 +148,29 @@ def test_bad_docstring_type(type_description, is_bad): assert bool(bad_docstring_type.search(type_description)) == is_bad +def test_bad_docstring_type_ignores_notes(): + """Test that defaults outside parameter types are not checked.""" + from numpydoc.docscrape import FunctionDoc + + def func(param): + """Do something. + + Parameters + ---------- + param : bool + A parameter. + + Notes + ----- + * :data:`python:True` (default) + A valid default in the Notes section. + """ + + params = FunctionDoc(func)["Parameters"] + assert [param.type for param in params] == ["bool"] + assert not any(bad_docstring_type.search(param.type) for param in params) + + def check_parameters_match(func, *, cls=None, where): """Check docstring, return list of incorrect results.""" from numpydoc.docscrape import FunctionDoc diff --git a/mne/time_frequency/tfr.py b/mne/time_frequency/tfr.py index 61824c62f31..090df93dc5e 100644 --- a/mne/time_frequency/tfr.py +++ b/mne/time_frequency/tfr.py @@ -95,7 +95,7 @@ def morlet(sfreq, freqs, n_cycles=7.0, sigma=None, zero_mean=False): n_cycles : float | array-like, shape (n_freqs,) Number of cycles. Can be a fixed number (float) or one per frequency (array-like). - sigma : float + sigma : float | None It controls the width of the wavelet ie its temporal resolution. If sigma is None the temporal resolution is adapted with the frequency like for all wavelet transform. @@ -460,7 +460,7 @@ def _compute_tfr( zero_mean : bool | None None means True for method='multitaper' and False for method='morlet'. If True, make sure the wavelets have a mean of zero. - time_bandwidth : float + time_bandwidth : float | None If None and method=multitaper, will be set to 4.0 (3 tapers). Time x (Full) Bandwidth product. Only applies if method == 'multitaper'. The number of good tapers (low-bias) is