code: def _adjust_mag_normals(info, data, origin, ext_order):
      """Adjust coil normals using magnetometers and empty-room data."""
      # in principle we could allow using just mag or mag+grad, but MF uses
      # just mag so let's follow suit
      mag_scale = 100.0
      picks_use = pick_types(info, meg="mag", exclude="bads")
      picks_meg = pick_types(info, meg=True, exclude=())
      picks_mag_orig = pick_types(info, meg="mag", exclude="bads")
      info = pick_info(info, picks_use)  # copy
      data = data[picks_use]
      cals = np.ones((len(data), 1))
      angles = np.zeros(len(cals))
      picks_mag = pick_types(info, meg="mag")
      data[picks_mag] *= mag_scale
      # Transform variables so we're only dealing with good mags
      exp = dict(int_order=0, ext_order=ext_order, origin=origin)
      all_coils = _prep_mf_coils(info, ignore_ref=True)
      S_tot = _trans_sss_basis(exp, all_coils, coil_scale=mag_scale)
      first_err = _data_err(data, S_tot, cals)
      count = 0
      # two passes: first do the worst, then do all in order
      zs = np.array([ch["loc"][-3:] for ch in info["chs"]])
      zs /= np.linalg.norm(zs, axis=-1, keepdims=True)
      orig_zs = zs.copy()
      match_idx = dict()
      locs = np.array([ch["loc"] for ch in info["chs"]])
      for pick in picks_mag:
          match_idx[pick] = _matched_loc_idx(locs[pick], locs)
      counts = defaultdict(lambda: 0)
      for ki, kind in enumerate(("worst first", "in order")):
          logger.info(
              f"        Magnetometer normal adjustment ({kind}) ..."
          )
          S_tot = _trans_sss_basis(exp, all_coils, coil_scale=mag_scale)
          for pick in picks_mag:
              err = _data_err(data, S_tot, cals, axis=1)
  
              # First pass: do worst; second pass: do all in order (up to 3x/sen)
              if ki == 0:
                  order = list(np.argsort(err[picks_mag]))
                  cal_idx = 0
                  while len(order) > 0:
                      cal_idx = picks_mag[order.pop(-1)]
                      if counts[cal_idx] < 3:
                          break
                  if err[cal_idx] < 2.5:
                      break  # move on to second loop
              else:
                  cal_idx = pick
              counts[cal_idx] += 1
              assert cal_idx in picks_mag
              count += 1
              old_z = zs[cal_idx].copy()
              objective = partial(
                  _cal_sss_target,
                  old_z=old_z,
                  all_coils=all_coils,
                  cal_idx=cal_idx,
                  data=data,
                  cals=cals,
                  match_idx=match_idx,
                  S_tot=S_tot,
                  origin=origin,
                  ext_order=ext_order,
              )
  
              # Figure out the additive term for z-component
              zs[cal_idx] = fmin_cobyla(
                  objective,
                  old_z,
                  cons=(),
                  rhobeg=1e-3,
                  rhoend=1e-4,
                  disp=False,
              )
  
              # Do in-place adjustment to all_coils
              cals[cal_idx] = 1.0 / np.linalg.norm(zs[cal_idx])
              zs[cal_idx] *= cals[cal_idx]
              for idx in match_idx[cal_idx]:
                  _rotate_coil(
                      zs[cal_idx], old_z, all_coils, idx, inplace=True
                  )
  
              # Recalculate S_tot, taking into account rotations
              S_tot = _trans_sss_basis(exp, all_coils)
  
              # Reprt results
              old_err = err[cal_idx]
              new_err = _data_err(data, S_tot, cals, idx=cal_idx)
              angles[cal_idx] = np.abs(
                  np.rad2deg(
                      _vector_angle(zs[cal_idx], orig_zs[cal_idx])
                  )
              )
              ch_name = info["ch_names"][cal_idx]
              logger.debug(
                  f"        Optimization step {count:3d} ｜ "
                  f"{ch_name} ({counts[cal_idx]}) ｜ "
                  f"res {old_err:5.2f}→{new_err:5.2f}% ｜ "
                  f"×{cals[cal_idx, 0]:0.3f} ｜ {angles[cal_idx]:0.2f}°"
              )
      last_err = _data_err(data, S_tot, cals)
      # Chunk is usable if all angles and errors are both small
      reason = list()
      max_angle = np.max(angles)
      if max_angle >= 5.0:
          reason.append(f"max angle {max_angle:0.2f} >= 5°")
      each_err = _data_err(data, S_tot, cals, axis=-1)[picks_mag]
      n_bad = (each_err > 5.0).sum()
      if n_bad:
          reason.append(f"{n_bad} residual{_pl(n_bad)} > 5%")
      reason = ", ".join(reason)
      if reason:
          reason = f" ({reason})"
      good = not bool(reason)
      assert np.allclose(np.linalg.norm(zs, axis=1), 1.0)
      logger.info(
          f"        Fit mismatch {first_err:0.2f}→{last_err:0.2f}%"
      )
      logger.info(
          f'        Data segment {"" if good else "un"}usable{reason}'
      )
      # Reformat zs and cals to be the n_mags (including bads)
      assert zs.shape == (len(data), 3)
      assert cals.shape == (len(data), 1)
      imb_cals = np.ones(len(picks_meg))
      imb_cals[picks_mag_orig] = cals[:, 0]
      return zs, imb_cals, good
  
imports: from collections import defaultdict
  from functools import partial
  import numpy
  from scipy.optimize import fmin_cobyla
  from .._fiff.pick import pick_info, pick_types
  from .._fiff.tag import _coil_trans_to_loc, _loc_to_coil_trans
  from ..bem import _check_origin
  from ..io import BaseRaw
  from ..transforms import _find_vector_rotation
  from ..utils import _check_fname, _check_option, _ensure_int, _pl, _reg_pinv, _validate_type, check_fname, logger, verbose
  from .maxwell import _col_norm_pinv, _get_grad_point_coilsets, _prep_fine_cal, _prep_mf_coils, _read_cross_talk, _trans_sss_basis
label_desc: Use image node_id 5 for calling a global function with example usage: _adjust_mag_normals(info, data, origin, ext_order) and returns: zs,  imb_cals,  good