"""Réglage par autocollimation : lentille mince et miroir plan inclinable.

Lancer avec : python3 autocollimation.py
Dépendances : numpy, matplotlib (versions compatibles avec Python 3.4)
Compatible avec Python 3.4.1 : sans f-strings ni option Slider(valstep).

Les rayons suivent la géométrie exacte de la réflexion sur le miroir ;
la lentille est modélisée dans l'approximation paraxiale.
"""
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button

X_OBJ = 0.5
F = 3.0
Y_OBJ = 0.75
ANGLES = np.linspace(-0.12, 0.12, 7)  # pentes des rayons issus de l'objet
MIRROR_HALF_HEIGHT = 2.6
MIRROR_CLEARANCE = 0.12  # espace entre la lentille et le miroir (au plus près)

fig, ax = plt.subplots(figsize=(11, 7))
plt.subplots_adjust(bottom=0.35)
ax.set_xlim(-2.5, 11)
ax.set_ylim(-3.2, 3.2)
ax.set_aspect('equal', adjustable='box')
ax.set_xlabel('Position sur l’axe optique (unités arbitraires)')
ax.set_ylabel('Hauteur (unités arbitraires)')
ax.set_title('Réglage par autocollimation — miroir plan inclinable')
ax.axhline(0, color='0.6', lw=1, ls='--')
ax.grid(alpha=0.15)

ax_lens = plt.axes((0.19, 0.19, 0.67, 0.032))
ax_mirror = plt.axes((0.19, 0.13, 0.67, 0.032))
ax_tilt = plt.axes((0.19, 0.07, 0.67, 0.032))
ax_reset = plt.axes((0.40, 0.012, 0.24, 0.043))
s_lens = Slider(ax_lens, 'Lentille', 2.0, 5.0, valinit=X_OBJ + F)
s_mirror = Slider(ax_mirror, 'Miroir', 2.0, 10.0, valinit=X_OBJ + F + 0.35)
s_tilt = Slider(ax_tilt, 'Inclinaison (°)', -15.0, 15.0, valinit=0.0)
b_reset = Button(ax_reset, 'Réglage pratique')

# Éléments graphiques recréés à chaque mouvement d’un curseur.
dynamic = []

def line(x, y, **kwargs):
    artist, = ax.plot(x, y, **kwargs)
    dynamic.append(artist)

def label(*args, **kwargs):
    artist = ax.text(*args, **kwargs)
    dynamic.append(artist)

def render(_=None):
    # Compatibilite avec Matplotlib ancien : Slider n'a pas valstep.
    # On reproduit les pas en arrondissant la valeur des curseurs.
    for slider, step in ((s_lens, 0.05), (s_mirror, 0.05),
                         (s_tilt, 0.25)):
        snapped = round(slider.val / step) * step
        snapped = max(slider.valmin, min(slider.valmax, snapped))
        if abs(slider.val - snapped) > 1e-8:
            slider.set_val(snapped)
            return  # set_val rappelle render par on_changed

    # L'intégralité du miroir doit rester derrière la lentille. Pour un miroir
    # incliné, son extrémité gauche peut être à gauche de son centre.
    # Le curseur "Miroir" peut donc aller jusqu'à la lentille, à un léger
    # espace de sécurité près. Si la lentille avance, le miroir suit si besoin.
    min_x_mirror = (s_lens.val + MIRROR_CLEARANCE
                    + MIRROR_HALF_HEIGHT * abs(np.sin(np.deg2rad(s_tilt.val))))
    if s_mirror.val < min_x_mirror - 1e-9:
        # Arrondir au pas superieur pour ne pas osciller avec le snap.
        next_x = math.ceil((min_x_mirror - 1e-10) / 0.05) * 0.05
        s_mirror.set_val(min(s_mirror.valmax, next_x))
        return  # set_val déclenche déjà un nouveau tracé

    for artist in dynamic:
        artist.remove()
    del dynamic[:]

    xl, xm = s_lens.val, s_mirror.val
    theta = np.deg2rad(s_tilt.val)
    # Vecteur tangent au miroir : (sin(theta), cos(theta)).
    tangent = np.array([np.sin(theta), np.cos(theta)])
    normal = np.array([np.cos(theta), -np.sin(theta)])

    obj = ax.annotate('', xy=(X_OBJ, Y_OBJ), xytext=(X_OBJ, 0),
                      arrowprops=dict(arrowstyle='-|>', color='black', lw=2.5))
    dynamic.append(obj)
    label(X_OBJ + 0.1, Y_OBJ + 0.12, 'Objet', fontsize=10)

    # Lentille et foyers.
    line([xl, xl], [-2.5, 2.5], color='royalblue', lw=3)
    for sign in (-1, 1):
        line([xl - 0.12, xl, xl + 0.12],
             [sign * 2.32, sign * 2.5, sign * 2.32],
             color='royalblue', lw=2)
    label(xl - 0.35, 2.78, 'L', color='royalblue')
    for xx, name in ((xl - F, 'F'), (xl + F, 'F′')):
        line([xx], [0], marker='o', color='royalblue', ms=4)
        label(xx + 0.08, -0.3, name, color='royalblue')

    # Miroir véritablement incliné, centré sur (xm, 0).
    ends = np.array([xm, 0.0])[:, None] + tangent[:, None] * np.array([-MIRROR_HALF_HEIGHT, MIRROR_HALF_HEIGHT])[None, :]
    line(ends[0], ends[1], color='dimgray', lw=4)
    for h in np.linspace(-2.4, 2.4, 15):
        pt = np.array([xm, 0.0]) + h*tangent
        hatch_end = pt + 0.18*normal + 0.12*tangent
        line([pt[0], hatch_end[0]], [pt[1], hatch_end[1]],
             color='dimgray', lw=0.8)
    label(ends[0, 1] - 0.55, ends[1, 1] + 0.22, 'Miroir', color='dimgray')

    y_back_obj = []
    ray_returns = []  # (hauteur à la lentille, pente du rayon au retour)
    visible = 0
    for slope in ANGLES:
        y_l = Y_OBJ + slope*(xl - X_OBJ)
        slope_forward = slope - y_l/F
        # Trajectoire entre lentille et miroir : (xl, y_l) + t*(1, slope_forward).
        # Intersection avec le plan : normal . ((x,y) - (xm,0)) = 0.
        v = np.array([1.0, slope_forward])
        origin = np.array([xl, y_l])
        denom = np.dot(normal, v)
        if abs(denom) < 1e-10:
            continue
        t = np.dot(normal, np.array([xm, 0.0]) - origin)/denom
        hit = origin + t*v
        h_hit = np.dot(hit - np.array([xm, 0.0]), tangent)

        line([X_OBJ, xl], [Y_OBJ, y_l], color='darkorange', lw=1.35, alpha=0.88)
        if t <= 0 or abs(h_hit) > MIRROR_HALF_HEIGHT:
            # Le rayon manque le miroir : sa trajectoire n'est plus réfléchie.
            continue
        line([xl, hit[0]], [y_l, hit[1]], color='darkorange', lw=1.35, alpha=0.88)

        # Réflexion spéculaire exacte : v_r = v - 2(v.n)n.
        vr = v - 2*np.dot(v, normal)*normal
        if vr[0] >= -1e-10:
            continue  # Pas de retour vers la lentille pour cette configuration.
        t_back = (xl - hit[0])/vr[0]
        if t_back <= 0:
            continue
        y_l_ret = hit[1] + t_back*vr[1]
        slope_return_before = vr[1]/vr[0]  # pente dy/dx sur le trajet retour
        slope_return_after = slope_return_before + y_l_ret/F
        y_o_ret = y_l_ret + slope_return_after*(X_OBJ - xl)
        y_back_obj.append(y_o_ret)
        ray_returns.append((y_l_ret, slope_return_after))
        visible += 1

        line([hit[0], xl], [hit[1], y_l_ret], color='forestgreen', lw=1.35, alpha=0.88)
        # Après la lentille, le rayon se propage réellement vers la gauche.
        # Ne pas l'arrêter dans le plan de l'objet : il peut le dépasser.
        x_left = ax.get_xlim()[0]
        y_left = y_l_ret + slope_return_after * (x_left - xl)
        line([xl, x_left], [y_l_ret, y_left],
             color='forestgreen', lw=1.35, alpha=0.88)

    delta = xl - X_OBJ - F
    if len(ray_returns) >= 2:
        # Chaque rayon émergent est décrit par :
        # y(x) = y_l_ret + pente_retour * (x - xl).
        # À l'intersection commune : y_l_ret = y_image - pente_retour*(x_image-xl).
        # Une régression linéaire donne l'image même si elle est virtuelle
        # ou si le miroir est légèrement incliné (aberrations éventuelles).
        data = np.asarray(ray_returns)
        slopes = data[:, 1]
        heights = data[:, 0]
        if np.ptp(slopes) > 1e-9:
            distance_image = -np.cov(slopes, heights, bias=True)[0, 1] / np.var(slopes)
            x_image = xl + distance_image
            y_image = float(np.mean(heights) + distance_image*np.mean(slopes))
            # Afficher l'image dès qu'elle appartient au champ de la figure.
            x_min, x_max = ax.get_xlim()
            y_min, y_max = ax.get_ylim()
            if x_min <= x_image <= x_max and y_min <= y_image <= y_max:
                image_artist = ax.annotate('', xy=(x_image, y_image),
                    xytext=(x_image, 0),
                    arrowprops=dict(arrowstyle='-|>', color='crimson', lw=2.3))
                dynamic.append(image_artist)
                label(x_image + 0.12, y_image - 0.15 if y_image < 0 else y_image + 0.12,
                      'Image de retour', fontsize=10, color='crimson')
                image_note = 'Image : x = {:.2f}, y = {:+.2f}'.format(x_image, y_image)
            else:
                image_note = ('Image hors du champ : '
                              'x = {:.2f}, y = {:+.2f}'.format(x_image, y_image))
        else:
            image_note = 'Image à l’infini (rayons de retour parallèles)'
        if abs(delta) < 1e-8:
            status = 'AUTOCOLLIMATION : objet au foyer.  ' + image_note
        else:
            status = 'Décalage objet–foyer : {:+.2f}  |  '.format(delta) + image_note
    else:
        status = 'Pas assez de rayons réfléchis pour localiser l’image.'

    if visible < len(ANGLES):
        status += '  ({}/{}) rayons réfléchis tracés'.format(visible, len(ANGLES))
    label(0.02, 0.02, status, transform=ax.transAxes, fontsize=9.5,
          bbox=dict(boxstyle='round,pad=.4', facecolor='white', alpha=.95))
    fig.canvas.draw_idle()

for slider in (s_lens, s_mirror, s_tilt):
    slider.on_changed(render)

def reset_ideal(_event):
    """Objet au foyer, miroir droit et placé juste derrière la lentille.

    Seule la position de la lentille conditionne l'autocollimation ; la
    position du miroir choisie ici est simplement commode en pratique.
    """
    s_tilt.set_val(0.0)
    s_lens.set_val(X_OBJ + F)
    s_mirror.set_val(X_OBJ + F + 0.35)
    render()

b_reset.on_clicked(reset_ideal)
render()
plt.show()
