"""Four-point regression: reproduce vertical OLS, horizontal OLS and TLS losses.

Run: python regression_demo.py
Requires: pip install numpy
"""
import numpy as np

P = np.array([[1, 0], [0, 1], [-1, 0], [0, -1]], dtype=float)
x, y = P[:, 0], P[:, 1]

# OLS that predicts y: vertical residuals.
m, c = np.linalg.lstsq(np.column_stack((x, np.ones(len(x)))), y, rcond=None)[0]
vertical_sse = np.sum((y - (m * x + c)) ** 2)

# OLS that predicts x: horizontal residuals.
a, b = np.linalg.lstsq(np.column_stack((y, np.ones(len(y)))), x, rcond=None)[0]
horizontal_sse = np.sum((x - (a * y + b)) ** 2)

print(f"Vertical OLS:   y = {m:.1f}x + {c:.1f}; SSE = {vertical_sse:.1f}")
print(f"Horizontal OLS: x = {a:.1f}y + {b:.1f}; SSE = {horizontal_sse:.1f}")

for degrees in [0, 30, 45, 60, 90]:
    theta = np.deg2rad(degrees)
    normal = np.array([-np.sin(theta), np.cos(theta)])
    tls_sse = np.sum((P @ normal) ** 2)
    print(f"Orthogonal: angle = {degrees:>2}°, SSE = {tls_sse:.1f}")
    assert np.isclose(tls_sse, 2)

print("P^T P =")
print(P.T @ P)
assert np.allclose(P.T @ P, 2 * np.eye(2))
