code: def prepare_inverse_operator(
      orig,
      nave,
      lambda2,
      method="dSPM",
      method_params=None,
      copy=True,
      verbose=None,
  ):
      """Prepare an inverse operator for actually computing the inverse.
  
      Parameters
      ----------
      orig : dict
          The inverse operator structure read from a file.
      nave : int
          Number of averages (scales the noise covariance).
      lambda2 : float
          The regularization factor. Recommended to be 1 / SNR**2.
      method : "MNE" | "dSPM" | "sLORETA" | "eLORETA"
          Use minimum norm, dSPM (default), sLORETA, or eLORETA.
      method_params : dict | None
          Additional options for eLORETA. See Notes of :func:`apply_inverse`.
  
          .. versionadded:: 0.16
      copy : bool | str
          If True (default), copy the inverse. False will not copy.
          Can be "non-src" to avoid copying the source space, which typically
          is not modified and can be large in memory.
  
          .. versionadded:: 0.21
      %(verbose)s
  
      Returns
      -------
      inv : instance of InverseOperator
          Prepared inverse operator.
      """
      if nave <= 0:
          raise ValueError("The number of averages should be positive")
  
      _validate_type(copy, (bool, str), "copy")
      if isinstance(copy, str):
          _check_option(
              "copy", copy, ("non-src",), extra="when a string"
          )
      logger.info("Preparing the inverse operator for use...")
      inv = orig
      if copy:
          src = orig["src"]
          if copy == "non-src":
              orig["src"] = None
          try:
              inv = orig.copy()
          finally:
              orig["src"] = src
          if copy == "non-src":
              inv["src"] = src
      del orig
  
      #
      #   Scale some of the stuff
      #
      scale = float(inv["nave"]) / nave
      inv["noise_cov"]["data"] = scale * inv["noise_cov"]["data"]
      # deal with diagonal case
      if inv["noise_cov"]["data"].ndim == 1:
          logger.info("    Diagonal noise covariance found")
          inv["noise_cov"]["eig"] = inv["noise_cov"]["data"]
          inv["noise_cov"]["eigvec"] = np.eye(
              len(inv["noise_cov"]["data"])
          )
  
      inv["noise_cov"]["eig"] = scale * inv["noise_cov"]["eig"]
      inv["source_cov"]["data"] = scale * inv["source_cov"]["data"]
      #
      if inv["eigen_leads_weighted"]:
          inv["eigen_leads"]["data"] = (
              sqrt(scale) * inv["eigen_leads"]["data"]
          )
  
      logger.info(
          "    Scaled noise and source covariance from nave = %d to"
          " nave = %d" % (inv["nave"], nave)
      )
      inv["nave"] = nave
      #
      #   Create the diagonal matrix for computing the regularized inverse
      #
      inv["reginv"] = _compute_reginv(inv, lambda2)
      logger.info("    Created the regularized inverter")
      #
      #   Create the projection operator
      #
      inv["proj"], ncomp, _ = make_projector(
          inv["projs"], inv["noise_cov"]["names"]
      )
      if ncomp > 0:
          logger.info(
              "    Created an SSP operator (subspace dimension = %d)"
              % ncomp
          )
      else:
          logger.info(
              "    The projection vectors do not apply to these "
              "channels."
          )
  
      #
      #   Create the whitener
      #
  
      inv["whitener"], _, inv["colorer"] = compute_whitener(
          inv["noise_cov"], pca="white", return_colorer=True
      )
  
      #
      #   Finally, compute the noise-normalization factors
      #
      inv["noisenorm"] = []
      if method == "eLORETA":
          _compute_eloreta(inv, lambda2, method_params)
      elif method != "MNE":
          logger.info(
              "    Computing noise-normalization factors (%s)..."
              % method
          )
          # Here we have::
          #
          #     inv['reginv'] = sing / (sing ** 2 + lambda2)
          #
          # where ``sing`` are the singular values of the whitened gain matrix.
          if method == "dSPM":
              # dSPM normalization
              noise_weight = inv["reginv"]
          elif method == "sLORETA":
              # sLORETA normalization is given by the square root of the
              # diagonal entries of the resolution matrix R, which is
              # the product of the inverse and forward operators as:
              #
              #     w = diag(diag(R)) ** 0.5
              #
              noise_weight = inv["reginv"] * np.sqrt(
                  1.0 + inv["sing"] ** 2 / lambda2
              )
  
          noise_norm = np.zeros(inv["eigen_leads"]["nrow"])
          (nrm2,) = linalg.get_blas_funcs(("nrm2",), (noise_norm,))
          if inv["eigen_leads_weighted"]:
              for k in range(inv["eigen_leads"]["nrow"]):
                  one = inv["eigen_leads"]["data"][k, :] * noise_weight
                  noise_norm[k] = nrm2(one)
          else:
              for k in range(inv["eigen_leads"]["nrow"]):
                  one = (
                      sqrt(inv["source_cov"]["data"][k])
                      * inv["eigen_leads"]["data"][k, :]
                      * noise_weight
                  )
                  noise_norm[k] = nrm2(one)
  
          #
          #   Compute the final result
          #
          if inv["source_ori"] == FIFF.FIFFV_MNE_FREE_ORI:
              #
              #   The three-component case is a little bit more involved
              #   The variances at three consecutive entries must be squared and
              #   added together
              #
              #   Even in this case return only one noise-normalization factor
              #   per source location
              #
              noise_norm = combine_xyz(noise_norm[:, None]).ravel()
          inv["noisenorm"] = 1.0 / np.abs(noise_norm)
          logger.info("[done]")
      else:
          inv["noisenorm"] = []
  
      return InverseOperator(inv)
  
imports: from copy import deepcopy
  from math import sqrt
  import numpy
  from scipy import linalg
  from scipy.stats import chi2
  from .._fiff.constants import FIFF
  from .._fiff.matrix import _read_named_matrix, _transpose_named_matrix, write_named_matrix
  from .._fiff.open import fiff_open
  from .._fiff.pick import channel_type, pick_channels, pick_info, pick_types
  from .._fiff.proj import _electrode_types, _needs_eeg_average_ref_proj, _read_proj, _write_proj, make_projector
  from .._fiff.tag import find_tag
  from .._fiff.tree import dir_tree_find
  from .._fiff.write import end_block, start_and_end_file, start_block, write_coord_trans, write_float, write_float_matrix, write_int, write_string
  from ..cov import Covariance, _read_cov, _write_cov, compute_whitener, prepare_noise_cov
  from ..epochs import BaseEpochs, EpochsArray
  from ..evoked import Evoked, EvokedArray
  from ..fixes import _safe_svd
  from ..forward import _read_forward_meas_info, _select_orient_forward, compute_depth_prior, compute_orient_prior, convert_forward_solution, is_fixed_orient
  from ..forward.forward import _triage_loose, write_forward_meas_info
  from ..html_templates import _get_html_template
  from ..io import BaseRaw
  from ..source_estimate import _get_src_type, _make_stc
  from ..source_space._source_space import _get_src_nn, _get_vertno, _read_source_spaces_from_tree, _write_source_spaces_to_fid, find_source_space_hemi, label_src_vertno_sel
  from ..surface import _normal_orth
  from ..time_frequency.tfr import _check_tfr_complex
  from ..transforms import _ensure_trans, transform_surface_to
  from ..utils import _check_compensation_grade, _check_depth, _check_fname, _check_option, _check_src_normal, _validate_type, _verbose_safe_false, check_fname, logger, repr_html, verbose, warn
  from ._eloreta import _compute_eloreta
label_desc: Use image node_id 8 for calling a global function with example usage: prepare_inverse_operator(orig, nave, lambda2, method, method_params, copy, verbose) and returns: InverseOperator