code: def _get_hpi_initial_fit(info, adjust=False, verbose=None):
      """Get HPI fit locations from raw."""
      if info["hpi_results"] is None or len(info["hpi_results"]) == 0:
          raise RuntimeError(
              "no initial cHPI head localization performed"
          )
  
      hpi_result = info["hpi_results"][-1]
      hpi_dig = sorted(
          [d for d in info["dig"] if d["kind"] == FIFF.FIFFV_POINT_HPI],
          key=lambda x: x["ident"],
      )  # ascending (dig) order
      if len(hpi_dig) == 0:  # CTF data, probably
          msg = "HPIFIT: No HPI dig points, using hpifit result"
          hpi_dig = sorted(
              hpi_result["dig_points"], key=lambda x: x["ident"]
          )
          if all(
              d["coord_frame"]
              in (FIFF.FIFFV_COORD_DEVICE, FIFF.FIFFV_COORD_UNKNOWN)
              for d in hpi_dig
          ):
              # Do not modify in place!
              hpi_dig = copy.deepcopy(hpi_dig)
              msg += " transformed to head coords"
              for dig in hpi_dig:
                  dig.update(
                      r=apply_trans(info["dev_head_t"], dig["r"]),
                      coord_frame=FIFF.FIFFV_COORD_HEAD,
                  )
          logger.debug(msg)
  
      # zero-based indexing, dig->info
      # CTF does not populate some entries so we use .get here
      pos_order = (
          hpi_result.get("order", np.arange(1, len(hpi_dig) + 1)) - 1
      )
      used = hpi_result.get("used", np.arange(len(hpi_dig)))
      dist_limit = hpi_result.get("dist_limit", 0.005)
      good_limit = hpi_result.get("good_limit", 0.98)
      goodness = hpi_result.get("goodness", np.ones(len(hpi_dig)))
  
      # this shouldn't happen, eventually we could add the transforms
      # necessary to put it in head coords
      if not all(
          d["coord_frame"] == FIFF.FIFFV_COORD_HEAD for d in hpi_dig
      ):
          raise RuntimeError("cHPI coordinate frame incorrect")
      # Give the user some info
      logger.info(
          f"HPIFIT: {len(pos_order)} coils digitized in order "
          f"{' '.join(str(o + 1) for o in pos_order)}"
      )
      logger.debug(
          f"HPIFIT: {len(used)} coils accepted: {' '.join(str(h) for h in used)}"
      )
      hpi_rrs = np.array([d["r"] for d in hpi_dig])[pos_order]
      assert len(hpi_rrs) >= 3
  
      # Fitting errors
      hpi_rrs_fit = sorted(
          [d for d in info["hpi_results"][-1]["dig_points"]],
          key=lambda x: x["ident"],
      )
      hpi_rrs_fit = np.array([d["r"] for d in hpi_rrs_fit])
      # hpi_result['dig_points'] are in FIFFV_COORD_UNKNOWN coords, but this
      # is probably a misnomer because it should be FIFFV_COORD_DEVICE for this
      # to work
      assert hpi_result["coord_trans"]["to"] == FIFF.FIFFV_COORD_HEAD
      hpi_rrs_fit = apply_trans(
          hpi_result["coord_trans"]["trans"], hpi_rrs_fit
      )
      if "moments" in hpi_result:
          logger.debug(
              "Hpi coil moments (%d %d):"
              % hpi_result["moments"].shape[::-1]
          )
          for moment in hpi_result["moments"]:
              logger.debug("{:g} {:g} {:g}".format(*tuple(moment)))
      errors = np.linalg.norm(hpi_rrs - hpi_rrs_fit, axis=1)
      logger.debug(
          f"HPIFIT errors:  {', '.join(f'{1000 * e:0.1f}' for e in errors)} mm."
      )
      if errors.sum() < len(errors) * dist_limit:
          logger.info("HPI consistency of isotrak and hpifit is OK.")
      elif not adjust and (len(used) == len(hpi_dig)):
          warn("HPI consistency of isotrak and hpifit is poor.")
      else:
          # adjust HPI coil locations using the hpifit transformation
          for hi, (err, r_fit) in enumerate(zip(errors, hpi_rrs_fit)):
              # transform to head frame
              d = 1000 * err
              if not adjust:
                  if err >= dist_limit:
                      warn(
                          f"Discrepancy of HPI coil {hi + 1} isotrak and hpifit is "
                          f"{d:.1f} mm!"
                      )
              elif hi + 1 not in used:
                  if goodness[hi] >= good_limit:
                      logger.info(
                          f"Note: HPI coil {hi + 1} isotrak is adjusted by {d:.1f} mm!"
                      )
                      hpi_rrs[hi] = r_fit
                  else:
                      warn(
                          f"Discrepancy of HPI coil {hi + 1} isotrak and hpifit of "
                          f"{d:.1f} mm was not adjusted!"
                      )
      logger.debug(
          f"HP fitting limits: err = {1000 * dist_limit:.1f} mm, gval = {good_limit:.3f}."
      )
  
      return hpi_rrs.astype(float)
  
imports: import copy
  import itertools
  from functools import partial
  import numpy
  from scipy.linalg import orth
  from scipy.optimize import fmin_cobyla
  from scipy.spatial.distance import cdist
  from ._fiff.constants import FIFF
  from ._fiff.meas_info import Info, _simplify_info
  from ._fiff.pick import _picks_to_idx, pick_channels, pick_channels_regexp, pick_info, pick_types
  from ._fiff.proj import Projection, setup_proj
  from .channels.channels import _get_meg_system
  from .cov import compute_whitener, make_ad_hoc_cov
  from .dipole import _make_guesses
  from .event import find_events
  from .fixes import jit
  from .forward import _concatenate_coils, _create_meg_coils, _magnetic_dipole_field_vec
  from .io import BaseRaw
  from .io.ctf.trans import _make_ctf_coord_trans_set
  from .io.kit.constants import KIT
  from .io.kit.kit import RawKIT
  from .preprocessing.maxwell import _get_mf_picks_fix_mags, _prep_mf_coils, _regularize_out, _sss_basis
  from .transforms import _angle_between_quats, _fit_matched_points, _quat_to_affine, als_ras_trans, apply_trans, invert_transform, quat_to_rot, rot_to_quat
  from .utils import ProgressBar, _check_fname, _check_option, _on_missing, _pl, _validate_type, _verbose_safe_false, logger, use_log_level, verbose, warn
label_desc: Use image node_id 7 for calling a global function with example usage: _get_hpi_initial_fit(info, adjust, verbose) and returns: hpi_rrs