code: def test_find_bad_channels_maxwell(
      fname,
      bads,
      annot,
      add_ch,
      ignore_ref,
      want_bads,
      return_scores,
      h_freq,
      meas_date,
  ):
      """Test automatic bad channel detection."""
      if fname.suffix == ".ds":
          raw = read_raw_ctf(fname).load_data()
          flat_idx = 33
      else:
          raw = read_raw_fif(fname)
          raw.fix_mag_coil_types().load_data().pick("meg", exclude=())
          flat_idx = 1
      if meas_date is None:
          raw.set_meas_date(None)
      else:
          assert meas_date == "raw"
      raw.filter(None, 40)
      raw.info["bads"] = bads
      raw._data[
          flat_idx
      ] = 0  # MaxFilter didn't have this but doesn't affect it
      want_flats = [raw.ch_names[flat_idx]]
      raw.apply_gradient_compensation(0)
  
      min_count = 5
  
      if add_ch:
          raw_eeg = read_raw_fif(fname)
          raw_eeg.pick("eeg", exclude=()).load_data()
          with raw_eeg.info._unlock():
              raw_eeg.info["lowpass"] = 40.0
          raw = raw_eeg.add_channels([raw])  # prepend the EEG channels
          assert 0 in pick_types(raw.info, meg=False, eeg=True)
      if ignore_ref:
          # Fake a bad one, otherwise we don't find any
          assert 42 in pick_types(raw.info, meg=True, ref_meg=False)
          assert raw.ch_names[42:43] == want_bads
          raw._data[42] += np.random.RandomState(0).randn(
              len(raw.times)
          )
      # maxfilter -autobad on -v -f test_raw.fif -force -cal off -ctc off -regularize off -list -o test_raw.fif -f ~/mne_data/MNE-testing-data/MEG/sample/sample_audvis_trunc_raw.fif  # noqa: E501
      if annot:
          # do a problematic one (gh-7741): exactly one "step" unit
          step = int(round(raw.info["sfreq"] * 5.0))
          dt = 1.0 / raw.info["sfreq"]
          assert step == 1502
          raw.annotations.append(step * dt + raw._first_time, dt, "BAD")
      with catch_logging() as log:
          return_vals = find_bad_channels_maxwell(
              raw,
              origin=(0.0, 0.0, 0.04),
              regularize=None,
              bad_condition="ignore",
              skip_by_annotation="BAD",
              verbose=True,
              ignore_ref=ignore_ref,
              min_count=min_count,
              return_scores=return_scores,
              h_freq=h_freq,
          )
  
      if return_scores:
          assert len(return_vals) == 3
          got_bads, got_flats, got_scores = return_vals
      else:
          assert len(return_vals) == 2
          got_bads, got_flats = return_vals
  
      if isinstance(want_bads, list):
          assert got_bads == want_bads  # from MaxFilter
      else:
          assert want_bads.intersection(set(got_bads))
      assert got_flats == want_flats
      log = log.getvalue()
      assert "Interval   1:    0.00" in log
      assert "Interval   2:    5.00" in log
  
      if h_freq is not None and h_freq > raw.info["lowpass"]:
          assert "data has already been low-pass filtered" in log
  
      if return_scores:
          meg_chs = raw.copy().pick("meg", exclude=[]).ch_names
          ch_types = raw.get_channel_types(meg_chs)
  
          assert list(got_scores["ch_names"]) == meg_chs
          assert list(got_scores["ch_types"]) == ch_types
          # Check that time is monotonically increasing.
          assert (np.diff(got_scores["bins"].flatten()) >= 0).all()
  
          assert (
              got_scores["scores_flat"].shape
              == got_scores["scores_noisy"].shape
              == (len(meg_chs), len(got_scores["bins"]))
          )
  
          assert (
              got_scores["limits_flat"].shape
              == got_scores["limits_noisy"].shape
              == (len(meg_chs), 1)
          )
  
          # Check "flat" scores.
          scores_flat = got_scores["scores_flat"]
          limits_flat = got_scores["limits_flat"]
          # Deal with NaN's in the scores (can't use np.less directly because of
          # https://github.com/numpy/numpy/issues/17198)
          scores_flat[np.isnan(scores_flat)] = np.inf
          limits_flat[np.isnan(limits_flat)] = -np.inf
          n_segments_below_limit = (scores_flat < limits_flat).sum(-1)
          ch_idx = np.where(
              n_segments_below_limit
              >= min(min_count, len(got_scores["bins"]))
          )
          flats = set(got_scores["ch_names"][ch_idx])
          assert flats == set(want_flats)
  
          # Check "noisy" scores.
          scores_noisy = got_scores["scores_noisy"]
          limits_noisy = got_scores["limits_noisy"]
          scores_noisy[np.isnan(scores_noisy)] = -np.inf
          limits_noisy[np.isnan(limits_noisy)] = np.inf
          n_segments_beyond_limit = (scores_noisy > limits_noisy).sum(
              -1
          )
          ch_idx = np.where(
              n_segments_beyond_limit
              >= min(min_count, len(got_scores["bins"]))
          )
          bads = set(got_scores["ch_names"][ch_idx])
          assert bads == set(want_bads)
  
imports: import pathlib
  import re
  from contextlib import contextmanager
  from pathlib import Path
  import numpy
  import pytest
  from numpy.testing import assert_allclose, assert_array_equal
  from scipy import sparse
  from scipy.special import sph_harm
  import mne
  from mne import compute_raw_covariance, concatenate_raws, pick_info, pick_types
  from mne._fiff.constants import FIFF
  from mne.annotations import _annotations_starts_stops
  from mne.chpi import filter_chpi, read_head_pos
  from mne.datasets import testing
  from mne.forward import _prep_meg_channels, use_coil_def
  from mne.io import BaseRaw, read_info, read_raw_bti, read_raw_ctf, read_raw_fif, read_raw_kit
  from mne.preprocessing import annotate_amplitude, annotate_movement, compute_maxwell_basis, find_bad_channels_maxwell, maxwell_filter, maxwell_filter_prepare_emptyroom
  from mne.preprocessing.maxwell import _bases_complex_to_real, _bases_real_to_complex, _get_n_moments, _prep_mf_coils, _sh_complex_to_real, _sh_negate, _sh_real_to_complex, _sss_basis_basic, _trans_sss_basis
  from mne.rank import _compute_rank_int, _get_rank_sss, compute_rank
  from mne.utils import _record_warnings, assert_meg_snr, buggy_mkl_svd, catch_logging, object_diff, use_log_level
label_desc: Use image node_id 26 for calling a global function with example usage: test_find_bad_channels_maxwell(fname, bads, annot, add_ch, ignore_ref, want_bads, return_scores, h_freq, meas_date) without return types