code: def _set_montage(
      info,
      montage,
      match_case=True,
      match_alias=False,
      on_missing="raise",
  ):
      """Apply montage to data.
  
      With a DigMontage, this function will replace the digitizer info with
      the values specified for the particular montage.
  
      Usually, a montage is expected to contain the positions of all EEG
      electrodes and a warning is raised when this is not the case.
  
      Parameters
      ----------
      %(info_not_none)s
      %(montage)s
      %(match_case)s
      %(match_alias)s
      %(on_missing_montage)s
  
      Notes
      -----
      This function will change the info variable in place.
      """
      _validate_type(montage, (DigMontage, None, str), "montage")
      if montage is None:
          # Next line modifies info['dig'] in place
          with info._unlock():
              info["dig"] = None
          for ch in info["chs"]:
              # Next line modifies info['chs'][#]['loc'] in place
              ch["loc"] = np.full(12, np.nan)
          return
      if isinstance(montage, str):  # load builtin montage
          _check_option(
              parameter="montage",
              value=montage,
              allowed_values=[
                  m.name for m in _BUILTIN_STANDARD_MONTAGES
              ],
          )
          montage = make_standard_montage(montage)
  
      mnt_head = _get_montage_in_head(montage)
      del montage
  
      def _backcompat_value(pos, ref_pos):
          if any(np.isnan(pos)):
              return np.full(6, np.nan)
          else:
              return np.concatenate((pos, ref_pos))
  
      # get the channels in the montage in head
      ch_pos = mnt_head._get_ch_pos()
  
      # only get the eeg, seeg, dbs, ecog channels
      picks = pick_types(
          info,
          meg=False,
          eeg=True,
          seeg=True,
          dbs=True,
          ecog=True,
          exclude=(),
      )
      non_picks = np.setdiff1d(np.arange(info["nchan"]), picks)
  
      # get the reference position from the loc[3:6]
      chs = [info["chs"][ii] for ii in picks]
      non_names = [info["chs"][ii]["ch_name"] for ii in non_picks]
      del picks
      ref_pos = np.array([ch["loc"][3:6] for ch in chs])
  
      # keep reference location from EEG-like channels if they
      # already exist and are all the same.
      # Note: ref position is an empty list for fieldtrip data
      if (
          len(ref_pos)
          and ref_pos[0].any()
          and (ref_pos[0] == ref_pos).all()
      ):
          eeg_ref_pos = ref_pos[0]
          # since we have an EEG reference position, we have
          # to add it into the info['dig'] as EEG000
          custom_eeg_ref_dig = True
      else:
          refs = set(ch_pos) & {"EEG000", "REF"}
          assert len(refs) <= 1
          eeg_ref_pos = (
              np.zeros(3) if not refs else ch_pos.pop(refs.pop())
          )
          custom_eeg_ref_dig = False
      del ref_pos
  
      # This raises based on info being subset/superset of montage
      info_names = [ch["ch_name"] for ch in chs]
      dig_names = mnt_head._get_dig_names()
      ref_names = [None, "EEG000", "REF"]
  
      if match_case:
          info_names_use = info_names
          dig_names_use = dig_names
          non_names_use = non_names
      else:
          ch_pos_use = OrderedDict(
              (name.lower(), pos) for name, pos in ch_pos.items()
          )
          info_names_use = [name.lower() for name in info_names]
          dig_names_use = [
              name.lower() if name is not None else name
              for name in dig_names
          ]
          non_names_use = [name.lower() for name in non_names]
          ref_names = [
              name.lower() if name is not None else name
              for name in ref_names
          ]
          n_dup = len(ch_pos) - len(ch_pos_use)
          if n_dup:
              raise ValueError(
                  "Cannot use match_case=False as %s montage "
                  "name(s) require case sensitivity" % n_dup
              )
          n_dup = len(info_names_use) - len(set(info_names_use))
          if n_dup:
              raise ValueError(
                  "Cannot use match_case=False as %s channel "
                  "name(s) require case sensitivity" % n_dup
              )
          ch_pos = ch_pos_use
          del ch_pos_use
      del dig_names
  
      # use lookup table to match unrecognized channel names to known aliases
      if match_alias:
          alias_dict = (
              match_alias
              if isinstance(match_alias, dict)
              else CHANNEL_LOC_ALIASES
          )
          if not match_case:
              alias_dict = {
                  ch_name.lower(): ch_alias.lower()
                  for ch_name, ch_alias in alias_dict.items()
              }
  
          # excluded ch_alias not in info, to prevent unnecessary mapping and
          # warning messages based on aliases.
          alias_dict = {
              ch_name: ch_alias
              for ch_name, ch_alias in alias_dict.items()
          }
          info_names_use = [
              alias_dict.get(ch_name, ch_name)
              for ch_name in info_names_use
          ]
          non_names_use = [
              alias_dict.get(ch_name, ch_name)
              for ch_name in non_names_use
          ]
  
      # warn user if there is not a full overlap of montage with info_chs
      missing = np.where([use not in ch_pos for use in info_names_use])[
          0
      ]
      if len(missing):  # DigMontage is subset of info
          missing_names = [info_names[ii] for ii in missing]
          pl = _pl(missing)
          are_is = "are" if pl else "is"
          missing_coord_msg = (
              f"DigMontage is only a subset of info. There {are_is} "
              f"{len(missing)} channel position{pl} not present in the "
              f"DigMontage. The channel{pl} missing from the montage {are_is}:"
              f"\n\n{missing_names}.\n\nConsider using inst.rename_channels to "
              "match the montage nomenclature, or inst.set_channel_types if "
              f"{'these' if pl else 'this'} {are_is} not {'' if pl else 'an '}"
              f"EEG channel{pl}, or use the on_missing parameter if the channel "
              f"position{pl} {are_is} allowed to be unknown in your analyses."
          )
          _on_missing(on_missing, missing_coord_msg)
  
          # set ch coordinates and names from digmontage or nan coords
          for ii in missing:
              ch_pos[info_names_use[ii]] = [np.nan] * 3
      del info_names
  
      assert len(non_names_use) == len(non_names)
      # There are no issues here with fNIRS being in non_names_use because
      # these names are like "D1_S1_760" and the ch_pos for a fNIRS montage
      # will have entries "D1" and "S1".
      extra = np.where([non in ch_pos for non in non_names_use])[0]
      if len(extra):
          types = "/".join(
              sorted(
                  set(channel_type(info, non_picks[ii]) for ii in extra)
              )
          )
          names = [non_names[ii] for ii in extra]
          warn(
              f"Not setting position{_pl(extra)} of {len(extra)} {types} "
              f"channel{_pl(extra)} found in montage:\n{names}\n"
              "Consider setting the channel types to be of "
              f'{docdict["montage_types"]} '
              "using inst.set_channel_types before calling inst.set_montage, "
              "or omit these channels when creating your montage."
          )
  
      for ch, use in zip(chs, info_names_use):
          # Next line modifies info['chs'][#]['loc'] in place
          if use in ch_pos:
              ch["loc"][:6] = _backcompat_value(
                  ch_pos[use], eeg_ref_pos
              )
          ch["coord_frame"] = FIFF.FIFFV_COORD_HEAD
      del ch_pos
  
      # XXX this is probably wrong as it uses the order from the montage
      # rather than the order of our info['ch_names'] ...
      digpoints = [
          mnt_head.dig[ii]
          for ii, name in enumerate(dig_names_use)
          if name in (info_names_use + ref_names)
      ]
  
      # get a copy of the old dig
      if info["dig"] is not None:
          old_dig = info["dig"].copy()
      else:
          old_dig = []
  
      # determine if needed to add an extra EEG REF DigPoint
      if custom_eeg_ref_dig:
          # ref_name = 'EEG000' if match_case else 'eeg000'
          ref_dig_dict = {
              "kind": FIFF.FIFFV_POINT_EEG,
              "r": eeg_ref_pos,
              "ident": 0,
              "coord_frame": info["dig"].pop()["coord_frame"],
          }
          ref_dig_point = _format_dig_points([ref_dig_dict])[0]
          # only append the reference dig point if it was already
          # in the old dig
          if ref_dig_point in old_dig:
              digpoints.append(ref_dig_point)
      # Next line modifies info['dig'] in place
      with info._unlock():
          info["dig"] = _format_dig_points(
              digpoints, enforce_order=True
          )
      del digpoints
  
      # TODO: Ideally we would have a check like this, but read_raw_bids for ECoG
      # allows for a montage to be set without any fiducials, then silently the
      # info['dig'] can end up in the MNI_TAL frame... only because in our
      # conversion code, UNKNOWN is treated differently from any other frame
      # (e.g., MNI_TAL). We should clean this up at some point...
      # missing_fids = sum(
      #     d['kind'] == FIFF.FIFFV_POINT_CARDINAL for d in info['dig'][:3]) != 3
      # if missing_fids:
      #     raise RuntimeError(
      #         'Could not find all three fiducials in the montage, this should '
      #         'not happen. Please contact MNE-Python developers.')
  
      # Handle fNIRS with source, detector and channel
      fnirs_picks = _picks_to_idx(info, "fnirs", allow_empty=True)
      if len(fnirs_picks) > 0:
          _set_montage_fnirs(info, mnt_head)
  
imports: import os.path
  import re
  from collections import OrderedDict
  from copy import deepcopy
  from dataclasses import dataclass
  import numpy
  from .._fiff._digitization import _coord_frame_const, _count_points_by_type, _ensure_fiducials_head, _format_dig_points, _get_data_as_dict_from_dig, _get_dig_eeg, _get_fid_coords, _make_dig_points, _read_dig_fif, write_dig
  from .._fiff.constants import CHANNEL_LOC_ALIASES, FIFF
  from .._fiff.meas_info import create_info
  from .._fiff.open import fiff_open
  from .._fiff.pick import _picks_to_idx, channel_type, pick_types
  from .._freesurfer import get_mni_fiducials
  from ..defaults import HEAD_SIZE_DEFAULT
  from ..transforms import Transform, _ensure_trans, _fit_matched_points, _frame_to_str, _quat_to_affine, _sph_to_cart, _topo_to_sph, _verbose_frames, apply_trans, get_ras_to_neuromag_trans
  from ..utils import _check_fname, _check_option, _on_missing, _pl, _validate_type, copy_function_doc_to_method_doc, fill_doc, verbose, warn
  from ..utils.docs import docdict
  from ..viz import plot_montage
  from ._dig_montage_utils import _parse_brainvision_dig_montage, _read_dig_montage_egi
label_desc: Use image node_id 14 for calling a global function with example usage: _set_montage(info, montage, match_case, match_alias, on_missing) and returns: np, np