code: def _do_forward_solution(
      subject,
      meas,
      fname=None,
      src=None,
      spacing=None,
      mindist=None,
      bem=None,
      mri=None,
      trans=None,
      eeg=True,
      meg=True,
      fixed=False,
      grad=False,
      mricoord=False,
      overwrite=False,
      subjects_dir=None,
      verbose=None,
  ):
      """Calculate a forward solution for a subject using MNE-C routines.
  
      This is kept around for testing purposes.
  
      This function wraps to mne_do_forward_solution, so the mne
      command-line tools must be installed and accessible from Python.
  
      Parameters
      ----------
      subject : str
          Name of the subject.
      meas : Raw | Epochs | Evoked | str
          If Raw or Epochs, a temporary evoked file will be created and
          saved to a temporary directory. If str, then it should be a
          filename to a file with measurement information the mne
          command-line tools can understand (i.e., raw or evoked).
      fname : path-like | None
          Destination forward solution filename. If None, the solution
          will be created in a temporary directory, loaded, and deleted.
      src : str | None
          Source space name. If None, the MNE default is used.
      spacing : str
          The spacing to use. Can be ``'#'`` for spacing in mm, ``'ico#'`` for a
          recursively subdivided icosahedron, or ``'oct#'`` for a recursively
          subdivided octahedron (e.g., ``spacing='ico4'``). Default is 7 mm.
      mindist : float | str | None
          Minimum distance measof sources from inner skull surface (in mm).
          If None, the MNE default value is used. If string, ``'all'``
          indicates to include all points.
      bem : str | None
          Name of the BEM to use (e.g., ``"sample-5120-5120-5120"``). If None
          (Default), the MNE default will be used.
      mri : dict | path-like | None
          The name of the trans file in FIF format.
          If None, ``trans`` must not be None.
      trans : dict | path-like | None
          File name of the trans file in text format.
          If None, ``mri`` must not be None.
      eeg : bool
          If True (Default), include EEG computations.
      meg : bool
          If True (Default), include MEG computations.
      fixed : bool
          If True, make a fixed-orientation forward solution (Default:
          False). Note that fixed-orientation inverses can still be
          created from free-orientation forward solutions.
      grad : bool
          If True, compute the gradient of the field with respect to the
          dipole coordinates as well (Default: False).
      mricoord : bool
          If True, calculate in MRI coordinates (Default: False)
      %(overwrite)s
      %(subjects_dir)s
      %(verbose)s
  
      See Also
      --------
      make_forward_solution
  
      Returns
      -------
      fwd : Forward
          The generated forward solution.
      """
      if not has_mne_c():
          raise RuntimeError(
              "mne command line tools could not be found"
          )
  
      # check for file existence
      temp_dir = Path(tempfile.mkdtemp())
      if fname is None:
          fname = temp_dir / "temp-fwd.fif"
      _check_fname(fname, overwrite)
      _validate_type(subject, "str", "subject")
  
      # check for meas to exist as string, or try to make evoked
      _validate_type(
          meas, ("path-like", BaseRaw, BaseEpochs, Evoked), "meas"
      )
      if isinstance(meas, (BaseRaw, BaseEpochs, Evoked)):
          meas_file = op.join(temp_dir, "info.fif")
          write_info(meas_file, meas.info)
          meas = meas_file
      else:
          meas = str(
              _check_fname(meas, overwrite="read", must_exist=True)
          )
  
      # deal with trans/mri
      if mri is not None and trans is not None:
          raise ValueError("trans and mri cannot both be specified")
      if mri is None and trans is None:
          # MNE allows this to default to a trans/mri in the subject's dir,
          # but let's be safe here and force the user to pass us a trans/mri
          raise ValueError("Either trans or mri must be specified")
  
      if trans is not None:
          if isinstance(trans, dict):
              trans_data = deepcopy(trans)
              trans = temp_dir / "trans-trans.fif"
              try:
                  write_trans(trans, trans_data)
              except Exception:
                  raise OSError(
                      "trans was a dict, but could not be "
                      "written to disk as a transform file"
                  )
          elif isinstance(trans, (str, Path, PathLike)):
              _check_fname(trans, "read", must_exist=True, name="trans")
              trans = Path(trans)
          else:
              raise ValueError("trans must be a path or dict")
      if mri is not None:
          if isinstance(mri, dict):
              mri_data = deepcopy(trans)
              mri = temp_dir / "mri-trans.fif"
              try:
                  write_trans(mri, mri_data)
              except Exception:
                  raise OSError(
                      "mri was a dict, but could not be "
                      "written to disk as a transform file"
                  )
          elif isinstance(mri, (str, Path, PathLike)):
              _check_fname(mri, "read", must_exist=True, name="mri")
              mri = Path(mri)
          else:
              raise ValueError("mri must be a path or dict")
  
      # deal with meg/eeg
      if not meg and not eeg:
          raise ValueError("meg or eeg (or both) must be True")
  
      if not fname.suffix == ".fif":
          raise ValueError("Forward name does not end with .fif")
      path = fname.parent.absolute()
      fname = fname.name
  
      # deal with mindist
      if mindist is not None:
          if isinstance(mindist, str):
              if not mindist.lower() == "all":
                  raise ValueError('mindist, if string, must be "all"')
              mindist = ["--all"]
          else:
              mindist = ["--mindist", "%g" % mindist]
  
      # src, spacing, bem
      for element, name, kind in zip(
          (src, spacing, bem),
          ("src", "spacing", "bem"),
          ("path-like", "str", "path-like"),
      ):
          if element is not None:
              _validate_type(element, kind, name, "%s or None" % kind)
  
      # put together the actual call
      cmd = [
          "mne_do_forward_solution",
          "--subject",
          subject,
          "--meas",
          meas,
          "--fwd",
          fname,
          "--destdir",
          str(path),
      ]
      if src is not None:
          cmd += ["--src", src]
      if spacing is not None:
          if spacing.isdigit():
              pass  # spacing in mm
          else:
              # allow both "ico4" and "ico-4" style values
              match = re.match(r"(oct|ico)-?(\d+)$", spacing)
              if match is None:
                  raise ValueError(
                      "Invalid spacing parameter: %r" % spacing
                  )
              spacing = "-".join(match.groups())
          cmd += ["--spacing", spacing]
      if mindist is not None:
          cmd += mindist
      if bem is not None:
          cmd += ["--bem", bem]
      if mri is not None:
          cmd += ["--mri", "%s" % str(mri.absolute())]
      if trans is not None:
          cmd += ["--trans", "%s" % str(trans.absolute())]
      if not meg:
          cmd.append("--eegonly")
      if not eeg:
          cmd.append("--megonly")
      if fixed:
          cmd.append("--fixed")
      if grad:
          cmd.append("--grad")
      if mricoord:
          cmd.append("--mricoord")
      if overwrite:
          cmd.append("--overwrite")
  
      env = os.environ.copy()
      subjects_dir = str(
          get_subjects_dir(subjects_dir, raise_error=True)
      )
      env["SUBJECTS_DIR"] = subjects_dir
  
      try:
          logger.info(
              "Running forward solution generation command with "
              "subjects_dir %s" % subjects_dir
          )
          run_subprocess(cmd, env=env)
      except Exception:
          raise
      else:
          fwd = read_forward_solution(path / fname, verbose=False)
      finally:
          shutil.rmtree(temp_dir, ignore_errors=True)
      return fwd
  
imports: import os
  import re
  import shutil
  import tempfile
  from copy import deepcopy
  from os import PathLike
  from os import path
  from pathlib import Path
  from time import time
  import numpy
  from scipy import sparse
  from .._fiff.constants import FIFF
  from .._fiff.matrix import _read_named_matrix, _transpose_named_matrix, write_named_matrix
  from .._fiff.meas_info import Info, _make_ch_names_mapping, _read_bad_channels, _read_extended_ch_info, _write_bad_channels, _write_ch_infos, write_info
  from .._fiff.open import fiff_open
  from .._fiff.pick import pick_channels, pick_channels_forward, pick_info, pick_types
  from .._fiff.tag import find_tag, read_tag
  from .._fiff.tree import dir_tree_find
  from .._fiff.write import end_block, start_and_end_file, start_block, write_coord_trans, write_id, write_int, write_string
  from ..epochs import BaseEpochs
  from ..evoked import Evoked, EvokedArray
  from ..html_templates import _get_html_template
  from ..io import BaseRaw, RawArray
  from ..label import Label
  from ..source_estimate import _BaseSourceEstimate, _BaseVectorSourceEstimate
  from ..source_space._source_space import _get_src_nn, _read_source_spaces_from_tree, _set_source_space_vertices, _src_kind_dict, _write_source_spaces_to_fid, find_source_space_hemi
  from ..surface import _normal_orth
  from ..transforms import invert_transform, transform_surface_to, write_trans
  from ..utils import _check_compensation_grade, _check_fname, _check_option, _check_stc_units, _import_h5io_funcs, _on_missing, _stamp_to_dt, _validate_type, check_fname, fill_doc, get_subjects_dir, has_mne_c, logger, repr_html, run_subprocess, verbose, warn
label_desc: Use image node_id 28 for calling a global function with example usage: _do_forward_solution(subject, meas, fname, src, spacing, mindist, bem, mri, trans, eeg, meg, fixed, grad, mricoord, overwrite, subjects_dir, verbose) and returns: fwd