code: def efficient_pnp(
      x: torch.Tensor,
      y: torch.Tensor,
      weights: Optional[torch.Tensor] = None,
      skip_quadratic_eq: bool = False,
  ) -> EpnpSolution:
      """
      Implements Efficient PnP algorithm [1] for Perspective-n-Points problem:
      finds a camera position (defined by rotation `R` and translation `T`) that
      minimizes re-projection error between the given 3D points `x` and
      the corresponding uncalibrated 2D points `y`, i.e. solves
  
      `y[i] = Proj(x[i] R[i] + T[i])`
  
      in the least-squares sense, where `i` are indices within the batch, and
      `Proj` is the perspective projection operator: `Proj([x y z]) = [x/z y/z]`.
      In the noise-less case, 4 points are enough to find the solution as long
      as they are not co-planar.
  
      Args:
          x: Batch of 3-dimensional points of shape `(minibatch, num_points, 3)`.
          y: Batch of 2-dimensional points of shape `(minibatch, num_points, 2)`.
          weights: Batch of non-negative weights of
              shape `(minibatch, num_point)`. `None` means equal weights.
          skip_quadratic_eq: If True, assumes the solution space for the
              linear system is one-dimensional, i.e. takes the scaled eigenvector
              that corresponds to the smallest eigenvalue as a solution.
              If False, finds the candidate coordinates in the potentially
              4D null space by approximately solving the systems of quadratic
              equations. The best candidate is chosen by examining the 2D
              re-projection error. While this option finds a better solution,
              especially when the number of points is small or perspective
              distortions are low (the points are far away), it may be more
              difficult to back-propagate through.
  
      Returns:
          `EpnpSolution` namedtuple containing elements:
          **x_cam**: Batch of transformed points `x` that is used to find
              the camera parameters, of shape `(minibatch, num_points, 3)`.
              In the general (noisy) case, they are not exactly equal to
              `x[i] R[i] + T[i]` but are some affine transform of `x[i]`s.
          **R**: Batch of rotation matrices of shape `(minibatch, 3, 3)`.
          **T**: Batch of translation vectors of shape `(minibatch, 3)`.
          **err_2d**: Batch of mean 2D re-projection errors of shape
              `(minibatch,)`. Specifically, if `yhat` is the re-projection for
              the `i`-th batch element, it returns `sum_j norm(yhat_j - y_j)`
              where `j` iterates over points and `norm` denotes the L2 norm.
          **err_3d**: Batch of mean algebraic errors of shape `(minibatch,)`.
              Specifically, those are squared distances between `x_world` and
              estimated points on the rays defined by `y`.
  
      [1] Moreno-Noguer, F., Lepetit, V., & Fua, P. (2009).
      EPnP: An Accurate O(n) solution to the PnP problem.
      International Journal of Computer Vision.
      https://www.epfl.ch/labs/cvlab/software/multi-view-stereo/epnp/
      """
      # define control points in a world coordinate system (centered on the 3d
      # points centroid); 4 x 3
      # TODO: more stable when initialised with the center and eigenvectors!
      c_world = _define_control_points(
          x.detach(),
          weights,
          storage_opts={"dtype": x.dtype, "device": x.device},
      )
  
      # find the linear combination of the control points to represent the 3d points
      alphas = _compute_alphas(x, c_world)
  
      M = _build_M(y, alphas, weights)
  
      # Compute kernel M
      kernel, spectrum = _null_space(M, 4)
  
      c_world_distances = _gen_pairs(c_world)
      kernel_dsts = _kernel_vec_distances(kernel)
  
      betas = (
          []
          if skip_quadratic_eq
          else [
              fnsc(kernel_dsts, c_world_distances)
              for fnsc in [
                  _find_null_space_coords_1,
                  _find_null_space_coords_2,
                  _find_null_space_coords_3,
              ]
          ]
      )
  
      c_cam_variants = [kernel] + [
          torch.matmul(kernel, beta[:, None, :, :]) for beta in betas
      ]
  
      solutions = [
          _compute_norm_sign_scaling_factor(
              c_cam[..., 0], alphas, x, y, weights
          )
          for c_cam in c_cam_variants
      ]
  
      sol_zipped = EpnpSolution(
          *(torch.stack(list(col)) for col in zip(*solutions))
      )
      best = torch.argmin(sol_zipped.err_2d, dim=0)
  
      def gather1d(source, idx):
          # reduces the dim=1 by picking the slices in a 1D tensor idx
          # in other words, it is batched index_select.
          return source.gather(
              0,
              idx.reshape(
                  1, -1, *([1] * (len(source.shape) - 2))
              ).expand_as(source[:1]),
          )[0]
  
      return EpnpSolution(
          *[gather1d(sol_col, best) for sol_col in sol_zipped]
      )
  
imports: import warnings
  from typing import NamedTuple, Optional
  import torch
  import torch.nn.functional
  from pytorch3d.ops import points_alignment, utils
label_desc: Use image node_id 15 for calling a global function with example usage: efficient_pnp(x, y, weights, skip_quadratic_eq) and returns: EpnpSolution, source