# Tactiverge Academy — companion code for "Fitting lines with least squares"
# Lesson: https://tactiverge.win/academy/computational-engineering/data-analysis/fitting-lines/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
import statistics

# Made-up data for illustration: a spring stretched by hanging loads
load = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]        # newtons
extension = [0.1, 2.1, 3.9, 6.2, 7.9, 10.1]  # millimetres

def fit_line(xs, ys):
    """Least-squares slope and intercept for y = a + b·x."""
    x_bar = statistics.mean(xs)
    y_bar = statistics.mean(ys)
    sxy = sum((x - x_bar) * (y - y_bar) for x, y in zip(xs, ys))
    sxx = sum((x - x_bar) ** 2 for x in xs)
    b = sxy / sxx
    a = y_bar - b * x_bar
    return a, b

a, b = fit_line(load, extension)
print(f"extension ≈ {a:.3f} + {b:.3f} × load")

print("load  measured  predicted  residual")
for x, y in zip(load, extension):
    predicted = a + b * x
    print(f"{x:4.1f}  {y:8.2f}  {predicted:9.3f}  {y - predicted:8.3f}")


# ── Example 2 ────────────────────────────────────────
import statistics

# Made-up data for illustration: a sensor whose output curves upward
x = [0, 1, 2, 3, 4, 5]
y = [0.0, 1.0, 4.0, 9.0, 16.0, 25.0]

fit = statistics.linear_regression(x, y)
residuals = [yi - (fit.intercept + fit.slope * xi) for xi, yi in zip(x, y)]
print(f"slope {fit.slope:.2f}, intercept {fit.intercept:.2f}")
print([round(r, 2) for r in residuals])
