code: def test_compute_covariance_auto_reg(rank):
      """Test automated regularization."""
      pytest.importorskip("sklearn")
      raw = read_raw_fif(raw_fname, preload=True)
      raw.resample(100, npad="auto")  # much faster estimation
      events = find_events(raw, stim_channel="STI 014")
      event_ids = [1, 2, 3, 4]
      reject = dict(mag=4e-12)
  
      # cov with merged events and keep_sample_mean=True
      events_merged = merge_events(events, event_ids, 1234)
      # we need a few channels for numerical reasons in PCA/FA
      picks = pick_types(raw.info, meg="mag", eeg=False)[:10]
      raw.pick([raw.ch_names[pick] for pick in picks])
      raw.info.normalize_proj()
      epochs = Epochs(
          raw,
          events_merged,
          1234,
          tmin=-0.2,
          tmax=0,
          baseline=(-0.2, -0.1),
          proj=True,
          reject=reject,
          preload=True,
      )
      epochs = epochs.crop(None, 0)[:5]
  
      method_params = dict(
          factor_analysis=dict(iter_n_components=[3]),
          pca=dict(iter_n_components=[3]),
      )
  
      covs = compute_covariance(
          epochs,
          method="auto",
          method_params=method_params,
          return_estimators=True,
          rank=rank,
      )
      # make sure regularization produces structured differences
      diag_mask = np.eye(len(epochs.ch_names)).astype(bool)
      off_diag_mask = np.invert(diag_mask)
      for cov_a, cov_b in itt.combinations(covs, 2):
          if (
              cov_a["method"] == "diagonal_fixed"
              and
              # here we have diagonal or no regularization.
              cov_b["method"] == "empirical"
              and rank == "full"
          ):
              assert not np.any(
                  cov_a["data"][diag_mask] == cov_b["data"][diag_mask]
              )
  
              # but the rest is the same
              assert_allclose(
                  cov_a["data"][off_diag_mask],
                  cov_b["data"][off_diag_mask],
                  rtol=1e-12,
              )
  
          else:
              # and here we have shrinkage everywhere.
              assert not np.any(
                  cov_a["data"][diag_mask] == cov_b["data"][diag_mask]
              )
  
              assert not np.any(
                  cov_a["data"][diag_mask] == cov_b["data"][diag_mask]
              )
  
      logliks = [c["loglik"] for c in covs]
      assert np.diff(logliks).max() <= 0  # descending order
  
      methods = [
          "empirical",
          "ledoit_wolf",
          "oas",
          "shrunk",
          "shrinkage",
      ]
      if rank == "full":
          methods.extend(["factor_analysis", "pca"])
      with catch_logging() as log:
          cov3 = compute_covariance(
              epochs,
              method=methods,
              method_params=method_params,
              projs=None,
              return_estimators=True,
              rank=rank,
              verbose=True,
          )
      log = log.getvalue().split("\n")
      if rank is None:
          assert (
              "    Setting small MAG eigenvalues to zero (without PCA)"
              in log
          )
          assert "Reducing data rank from 10 -> 7" in log
      else:
          assert "Reducing" not in log
      method_names = [cov["method"] for cov in cov3]
      best_bounds = [-45, -35]
      bounds = [-55, -45] if rank == "full" else best_bounds
      for method in set(methods) - {"empirical", "shrunk"}:
          this_lik = cov3[method_names.index(method)]["loglik"]
          assert bounds[0] < this_lik < bounds[1]
      this_lik = cov3[method_names.index("shrunk")]["loglik"]
      assert best_bounds[0] < this_lik < best_bounds[1]
      this_lik = cov3[method_names.index("empirical")]["loglik"]
      bounds = [-110, -100] if rank == "full" else best_bounds
      assert bounds[0] < this_lik < bounds[1]
  
      assert_equal({c["method"] for c in cov3}, set(methods))
  
      cov4 = compute_covariance(
          epochs,
          method=methods,
          method_params=method_params,
          projs=None,
          return_estimators=False,
          rank=rank,
      )
      assert cov3[0]["method"] == cov4["method"]  # ordering
  
      # invalid prespecified method
      pytest.raises(
          ValueError, compute_covariance, epochs, method="pizza"
      )
  
      # invalid scalings
      pytest.raises(
          ValueError,
          compute_covariance,
          epochs,
          method="shrunk",
          scalings=dict(misc=123),
      )
  
imports: import itertools
  import sys
  from inspect import signature
  from pathlib import Path
  import numpy
  import pytest
  from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_equal, assert_equal
  from mne import Epochs, compute_covariance, compute_proj_raw, compute_rank, compute_raw_covariance, create_info, find_events, make_ad_hoc_cov, make_fixed_length_events, merge_events, pick_channels_cov, pick_info, pick_types, read_cov, read_evokeds, write_cov
  from mne._fiff.pick import _DATA_CH_TYPES_SPLIT
  from mne.channels import equalize_channels
  from mne.cov import _auto_low_rank_model, _regularized_covariance, compute_whitener, prepare_noise_cov, regularize, whiten_evoked
  from mne.datasets import testing
  from mne.fixes import _safe_svd
  from mne.io import RawArray, read_info, read_raw_ctf, read_raw_fif
  from mne.preprocessing import maxwell_filter
  from mne.rank import _compute_rank_int
  from mne.utils import _record_warnings, assert_snr, catch_logging
label_desc: Use image node_id 16 for calling a global function with example usage: test_compute_covariance_auto_reg(rank) without return types