code: def _prepare_for_forward(
      src,
      mri_head_t,
      info,
      bem,
      mindist,
      n_jobs,
      bem_extra="",
      trans="",
      info_extra="",
      meg=True,
      eeg=True,
      ignore_ref=False,
      allow_bem_none=False,
      verbose=None,
  ):
      """Prepare for forward computation.
  
      The sensors dict contains keys for each sensor type, e.g. 'meg', 'eeg'.
      The vale for each of these is a dict that comes from _prep_meg_channels or
      _prep_eeg_channels. Each dict contains:
  
      - defs : a list of dicts (one per channel) with 'rmag', 'cosmag', etc.
      - ch_names: a list of str channel names corresponding to the defs
      - compensator (optional): the ndarray compensation matrix to apply
      - post_picks (optional): the ndarray of indices to pick after applying the
        compensator
      """
      # Read the source locations
      logger.info("")
      # let's make a copy in case we modify something
      src = _ensure_src(src).copy()
      nsource = sum(s["nuse"] for s in src)
      if nsource == 0:
          raise RuntimeError(
              "No sources are active in these source spaces. "
              '"do_all" option should be used.'
          )
      logger.info(
          "Read %d source spaces a total of %d active source locations"
          % (len(src), nsource)
      )
      # Delete some keys to clean up the source space:
      for key in ["working_dir", "command_line"]:
          if key in src.info:
              del src.info[key]
  
      # Read the MRI -> head coordinate transformation
      logger.info("")
      _print_coord_trans(mri_head_t)
  
      # make a new dict with the relevant information
      arg_list = [
          info_extra,
          trans,
          src,
          bem_extra,
          meg,
          eeg,
          mindist,
          n_jobs,
          verbose,
      ]
      cmd = "make_forward_solution(%s)" % (
          ", ".join([str(a) for a in arg_list])
      )
      mri_id = dict(
          machid=np.zeros(2, np.int32), version=0, secs=0, usecs=0
      )
  
      info_trans = str(trans) if isinstance(trans, Path) else trans
      info = Info(
          chs=info["chs"],
          comps=info["comps"],
          dev_head_t=info["dev_head_t"],
          mri_file=info_trans,
          mri_id=mri_id,
          meas_file=info_extra,
          meas_id=None,
          working_dir=os.getcwd(),
          command_line=cmd,
          bads=info["bads"],
          mri_head_t=mri_head_t,
      )
      info._update_redundant()
      info._check_consistency()
      logger.info("")
  
      sensors = dict()
      if (
          meg
          and len(pick_types(info, meg=True, ref_meg=False, exclude=[]))
          > 0
      ):
          sensors["meg"] = _prep_meg_channels(
              info, ignore_ref=ignore_ref
          )
      if eeg and len(pick_types(info, eeg=True, exclude=[])) > 0:
          sensors["eeg"] = _prep_eeg_channels(info)
  
      # Check that some channels were found
      if len(sensors) == 0:
          raise RuntimeError("No MEG or EEG channels found.")
  
      # pick out final info
      info = pick_info(
          info,
          pick_types(info, meg=meg, eeg=eeg, ref_meg=False, exclude=[]),
      )
  
      # Transform the source spaces into the appropriate coordinates
      # (will either be HEAD or MRI)
      for s in src:
          transform_surface_to(s, "head", mri_head_t)
      logger.info(
          "Source spaces are now in %s coordinates."
          % _coord_frame_name(s["coord_frame"])
      )
  
      # Prepare the BEM model
      eegnames = sensors.get("eeg", dict()).get("ch_names", [])
      bem = _setup_bem(
          bem,
          bem_extra,
          len(eegnames),
          mri_head_t,
          allow_none=allow_bem_none,
      )
      del eegnames
  
      # Circumvent numerical problems by excluding points too close to the skull,
      # and check that sensors are not inside any BEM surface
      if bem is not None:
          if not bem["is_sphere"]:
              check_surface = "inner skull surface"
              inner_skull = _bem_find_surface(bem, "inner_skull")
              check_inside = _filter_source_spaces(
                  inner_skull, mindist, mri_head_t, src, n_jobs
              )
              logger.info("")
              if len(bem["surfs"]) == 3:
                  check_surface = "scalp surface"
                  check_inside = _CheckInside(
                      _bem_find_surface(bem, "head")
                  )
          else:
              check_surface = "outermost sphere shell"
              if len(bem["layers"]) == 0:
  
                  def check_inside(x):
                      return np.zeros(len(x), bool)
  
              else:
  
                  def check_inside(x):
                      return (
                          np.linalg.norm(x - bem["r0"], axis=1)
                          < bem["layers"][-1]["rad"]
                      )
  
          if "meg" in sensors:
              meg_loc = apply_trans(
                  invert_transform(mri_head_t),
                  np.array(
                      [coil["r0"] for coil in sensors["meg"]["defs"]]
                  ),
              )
              n_inside = check_inside(meg_loc).sum()
              if n_inside:
                  raise RuntimeError(
                      f"Found {n_inside} MEG sensor{_pl(n_inside)} inside the "
                      f"{check_surface}, perhaps coordinate frames and/or "
                      "coregistration must be incorrect"
                  )
  
      rr = np.concatenate([s["rr"][s["vertno"]] for s in src])
      if len(rr) < 1:
          raise RuntimeError(
              "No points left in source space after excluding "
              "points close to inner skull."
          )
  
      # deal with free orientations:
      source_nn = np.tile(np.eye(3), (len(rr), 1))
      update_kwargs = dict(
          nchan=len(info["ch_names"]),
          nsource=len(rr),
          info=info,
          src=src,
          source_nn=source_nn,
          source_rr=rr,
          surf_ori=False,
          mri_head_t=mri_head_t,
      )
      return sensors, rr, info, update_kwargs, bem
  
imports: import os
  import os.path
  from contextlib import contextmanager
  from copy import deepcopy
  from pathlib import Path
  import numpy
  from .._fiff.compensator import get_current_comp, make_compensator
  from .._fiff.constants import FIFF, FWD
  from .._fiff.meas_info import Info, read_info
  from .._fiff.pick import _has_kit_refs, pick_info, pick_types
  from .._fiff.tag import _loc_to_coil_trans, _loc_to_eeg_loc
  from ..bem import ConductorModel, _bem_find_surface, read_bem_solution
  from ..source_estimate import VolSourceEstimate
  from ..source_space._source_space import _complete_vol_src, _ensure_src, _filter_source_spaces, _make_discrete_source_space
  from ..surface import _CheckInside, _normalize_vectors
  from ..transforms import Transform, _coord_frame_name, _ensure_trans, _get_trans, _print_coord_trans, apply_trans, invert_transform, transform_surface_to
  from ..utils import _check_fname, _pl, _validate_type, logger, verbose, warn
  from ._compute_forward import _compute_forwards
  from .forward import _FWD_ORDER, Forward, _merge_fwds, convert_forward_solution
label_desc: Use image node_id 11 for calling a global function with example usage: _prepare_for_forward(src, mri_head_t, info, bem, mindist, n_jobs, bem_extra, trans, info_extra, meg, eeg, ignore_ref, allow_bem_none, verbose) and returns: sensors,  rr,  info,  update_kwargs,  bem, np, unknown