code: def _prepare_weights(
      forward, gain, source_weighting, weights, weights_min
  ):
      mask = None
      if isinstance(weights, _BaseSourceEstimate):
          weights = np.max(np.abs(weights.data), axis=1)
      weights_max = np.max(weights)
      if weights_min > weights_max:
          raise ValueError(
              "weights_min > weights_max (%s > %s)"
              % (weights_min, weights_max)
          )
      weights_min = weights_min / weights_max
      weights = weights / weights_max
      n_dip_per_pos = 1 if is_fixed_orient(forward) else 3
      weights = np.ravel(np.tile(weights, [n_dip_per_pos, 1]).T)
      if len(weights) != gain.shape[1]:
          raise ValueError(
              "weights do not have the correct dimension "
              " (%d != %d)" % (len(weights), gain.shape[1])
          )
      if len(source_weighting.shape) == 1:
          source_weighting *= weights
      else:
          source_weighting *= weights[:, None]
      gain *= weights[None, :]
  
      if weights_min is not None:
          mask = weights > weights_min
          gain = gain[:, mask]
          n_sources = np.sum(mask) // n_dip_per_pos
          logger.info("Reducing source space to %d sources" % n_sources)
  
      return gain, source_weighting, mask
  
imports: import numpy
  from .._fiff.proj import deactivate_proj
  from ..dipole import Dipole
  from ..fixes import _safe_svd
  from ..forward import is_fixed_orient
  from ..minimum_norm.inverse import _check_reference, _log_exp_var, _prepare_forward, combine_xyz
  from ..source_estimate import SourceEstimate, _BaseSourceEstimate, _make_stc
  from ..utils import _check_depth, _check_option, _validate_type, check_random_state, logger, sum_squared, verbose, warn
  from .mxne_optim import _Phi, groups_norm2, iterative_mixed_norm_solver, iterative_tf_mixed_norm_solver, mixed_norm_solver, norm_epsilon_inf, norm_l2inf, tf_mixed_norm_solver
label_desc: Use image node_id 2 for calling a global function with example usage: _prepare_weights(forward, gain, source_weighting, weights, weights_min) and returns: gain,  source_weighting,  mask