r"""
.. _example_triangulation:

Triangulation of world points from two images
=============================================

.. contents:: Table of Contents
   :local:
   :depth: 1
   :backlinks: top

The world points seen by two cameras are estimated from their projections in the two
images (stereo triangulation), with two methods:

- the minimization of the reprojection errors with
  :func:`pysdic.optimize_chains_transformation_input_points`;
- the intersection of the rays of the two cameras with :func:`pysdic.intersect_rays`.

"""

# %%
# Stereo setup
# ------------
#
# 100 random world points are seen by two cameras placed at :math:`Y = \pm 4`, looking at
# the point :math:`(0, 0, 75)`. The rows of the rotation of a camera are its axes, with
# :math:`\vec{z}_c` toward the target, and :math:`\vec{t} = -R \, \vec{C}`.

import numpy
from scipy.spatial.transform import Rotation
from pysdic import PerspectiveExtrinsic, PinholeIntrinsic, ZernikeDistortion, project_points

rng = numpy.random.default_rng(0)
world_points = numpy.stack((rng.uniform(-5.0, 5.0, 100), rng.uniform(-5.0, 5.0, 100), rng.uniform(50.0, 100.0, 100)), axis=-1)


def looking_at(center: numpy.ndarray, target: numpy.ndarray) -> PerspectiveExtrinsic:
    # Extrinsic of a camera at 'center' looking at 'target'
    z_axis = (target - center) / numpy.linalg.norm(target - center)
    x_axis = numpy.cross([0.0, 1.0, 0.0], z_axis)
    x_axis /= numpy.linalg.norm(x_axis)
    rotation = numpy.stack((x_axis, numpy.cross(z_axis, x_axis), z_axis))  # World -> camera
    return PerspectiveExtrinsic.from_rt(rvec=Rotation.from_matrix(rotation).as_rotvec(), tvec=-rotation @ center)


target = numpy.array([0.0, 0.0, 75.0])
extrinsic_1 = looking_at(numpy.array([0.0, -4.0, 0.0]), target)
extrinsic_2 = looking_at(numpy.array([0.0, 4.0, 0.0]), target)

height, width = 2000, 3000
intrinsic = PinholeIntrinsic.from_matrix([[1000.0, 0.0, (width - 1) / 2], [0.0, 1000.0, (height - 1) / 2], [0.0, 0.0, 1.0]])

# %%
# The cameras share a Zernike distortion given in pixels on the disk circumscribed to the
# image. It is applied to the normalized points, so the coefficients, the radius and the
# center are divided by the focal lengths.

center_pixels = numpy.array([(width - 1) / 2, (height - 1) / 2])
radius_pixels = numpy.linalg.norm(center_pixels)
distortion = ZernikeDistortion(
    [
        0.8541972545746392, -5.468596289790535, -5.974287819021697, 14.292956075116104,
        2.1403205479372627, 4.544169430137205, -0.10099732464199339, 0.4363509204067417,
        -0.5106374355681896, -5.770087687650705, -0.39147505788710696, 11.699411273002498,
    ],  # In pixels
    radius_x=radius_pixels / intrinsic.fx,
    radius_y=radius_pixels / intrinsic.fy,
    center=((center_pixels[0] - intrinsic.cx) / intrinsic.fx, (center_pixels[1] - intrinsic.cy) / intrinsic.fy),
)
distortion.parameters_x = distortion.parameters_x / intrinsic.fx
distortion.parameters_y = distortion.parameters_y / intrinsic.fy

image_points_1 = project_points(world_points, intrinsic, distortion, extrinsic_1).image_points
image_points_2 = project_points(world_points, intrinsic, distortion, extrinsic_2).image_points
noisy_points_1 = image_points_1 + rng.normal(scale=0.5, size=image_points_1.shape)  # 0.5 pixel of noise
noisy_points_2 = image_points_2 + rng.normal(scale=0.5, size=image_points_2.shape)
inside = all(numpy.all((points >= 0) & (points < [width, height])) for points in (image_points_1, image_points_2))
print(f"All the points are in both images: {inside}")


def rms_error(points: numpy.ndarray) -> float:
    # RMS distance to the true world points
    return float(numpy.sqrt(numpy.mean(numpy.sum((points - world_points) ** 2, axis=1))))


# %%
# Minimization of the reprojection errors
# ---------------------------------------
#
# Each image gives a chain of transformations:
#
# .. code-block:: text
#
#    Chain 1: world points -> extrinsic_1 -> distortion -> intrinsic -> image points 1
#    Chain 2: world points -> extrinsic_2 -> distortion -> intrinsic -> image points 2
#
# Each world point minimizes the sum of its squared reprojection errors in both images.
# The points are independent problems solved together with ``pysolvegn.solve_batch``: a
# point leaves the optimization as soon as it converges. With noise, ``atol`` stops the
# points whose cost is small enough (here a reprojection error of about 0.01 pixel).

from pysdic import optimize_chains_transformation_input_points

transformations = [extrinsic_1, extrinsic_2, distortion, intrinsic]
chains = [(0, 2, 3), (1, 2, 3)]
guess = world_points + rng.normal(scale=0.1, size=world_points.shape)

optimized, result = optimize_chains_transformation_input_points(
    transformations, chains, [image_points_1, image_points_2], guess, max_iteration=20, ftol=1e-8, gtol=1e-8, xtol=1e-8
)
print(result.message)  # Converged points and stopping criteria

optimized_noisy, result = optimize_chains_transformation_input_points(
    transformations, chains, [noisy_points_1, noisy_points_2], guess,
    max_iteration=100, ftol=1e-8, gtol=1e-8, xtol=1e-8, atol=1e-4,
)

# %%
# Intersection of the rays
# ------------------------
#
# :func:`pysdic.compute_rays` gives the rays of the cameras through the image points (with
# the inverse of the distortion, computed by a Newton method set with
# ``distortion_kwargs``), and :func:`pysdic.intersect_rays` the point closest to the two
# rays of each pair.

from pysdic import compute_rays, intersect_rays

distortion_kwargs = {"max_iteration": 20, "tolerance": 1e-12}


def triangulate(points_1: numpy.ndarray, points_2: numpy.ndarray) -> numpy.ndarray:
    rays_1 = compute_rays(points_1, intrinsic, distortion, extrinsic_1, distortion_kwargs=distortion_kwargs)
    rays_2 = compute_rays(points_2, intrinsic, distortion, extrinsic_2, distortion_kwargs=distortion_kwargs)
    return intersect_rays([rays_1, rays_2])


intersected = triangulate(image_points_1, image_points_2)
intersected_noisy = triangulate(noisy_points_1, noisy_points_2)

# %%
# Comparison
# ----------
#
# - The minimization of the reprojection errors is the optimal estimate when the noise is
#   in the images, and does not need the inverse of the transformations, but it needs an
#   initial guess and iterations.
# - The intersection of the rays is direct (no initial guess), but it needs the inverse of
#   the distortion and minimizes distances in the world instead of errors in the images.
#
# A common strategy is to use the intersection of the rays as the initial guess of the
# minimization.

print(f"{'RMS error (world units)':<26} {'without noise':>14} {'with noise':>12}")
print(f"{'reprojection errors':<26} {rms_error(optimized):>14.2e} {rms_error(optimized_noisy):>12.2e}")
print(f"{'intersection of the rays':<26} {rms_error(intersected):>14.2e} {rms_error(intersected_noisy):>12.2e}")