"""Run the numerical examples in chapters 7, 8, 10 and 11

python experiments.py --output results --figures figures
"""
import argparse
import itertools
import json
import math
import platform
import time
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import scipy
from scipy.linalg import solve_discrete_are
from scipy.optimize import brentq, least_squares


H = 0.1
A = math.exp(-H)
B = 1 - A
COLORS = ["#175D76", "#BE501E", "#31724D", "#795496", "#545D70"]
plt.rcParams.update({
    "axes.prop_cycle": plt.cycler(color=COLORS), "axes.spines.top": False,
    "axes.spines.right": False, "axes.grid": True, "grid.alpha": 0.18,
    "svg.fonttype": "none", "svg.hashsalt": "electrical-control", "font.size": 11,
    "axes.labelsize": 12, "axes.unicode_minus": False,
})


def save(fig, root, name):
    fig.savefig(root / name, format="svg", bbox_inches="tight", metadata={"Date": None})
    plt.close(fig)


def thermal_model(figures):
    """Fit a step response and test its predictions on an independent pulse"""
    rng = np.random.default_rng(73)
    t = np.arange(0, 12.1, H)
    gain, tau = 1.8, 2.4
    measured = gain * (1 - np.exp(-t / tau)) + rng.normal(0, 0.015, len(t))
    fit = least_squares(lambda pars: pars[0] * (1 - np.exp(-t / pars[1])) - measured,
                        x0=[1, 1], bounds=([0, 0.01], [10, 20])).x
    command = np.where((t >= 1) & (t < 6), 0.7, 0.)

    def run(k, time_constant):
        x = np.zeros(len(t))
        pole = math.exp(-H / time_constant)
        for i, u in enumerate(command[:-1]):
            x[i + 1] = pole * x[i] + (1 - pole) * k * u
        return x

    validation = run(gain, tau) + rng.normal(0, 0.015, len(t))
    predicted = run(*fit)
    residual = validation - predicted
    fig, ax = plt.subplots(2, 1, figsize=(4.35, 4.5), sharex=True, layout="constrained")
    ax[0].scatter(t, validation, s=7, label="measurement")
    ax[0].plot(t, predicted, label="model")
    ax[0].set_ylabel("Temperature rise (K)")
    ax[0].legend()
    ax[1].plot(t, residual)
    ax[1].axhline(0, color="black", lw=.7)
    ax[1].set(xlabel="Time (s)", ylabel="Residual (K)")
    save(fig, figures, "model-validation.svg")
    return dict(gain_K_W=fit[0], tau_s=fit[1], holdout_mean_K=np.mean(residual),
                holdout_rmse_K=np.sqrt(np.mean(residual**2)))


def estimation(figures):
    """A cart with measured acceleration and occasional position fixes"""
    rng = np.random.default_rng(81)
    steps = 160
    transition = np.array([[1, H], [0, 1.]])
    g = np.array([0.5 * H**2, H])
    process_cov = 0.2**2 * np.outer(g, g)
    obs_var = 0.06**2
    truth = np.zeros((steps + 1, 2))
    estimate = truth.copy()
    dead = truth.copy()
    uncertainty = np.diag([0.1**2, 0.2**2])
    samples, sigma = [], [math.sqrt(uncertainty[0, 0])]
    for k in range(steps):
        acceleration = 0.2 * math.sin(k * H)
        truth[k + 1] = transition @ truth[k] + g * (acceleration + rng.normal(0, 0.2))
        dead[k + 1] = transition @ dead[k] + g * acceleration
        prediction = transition @ estimate[k] + g * acceleration
        uncertainty = transition @ uncertainty @ transition.T + process_cov
        if (k + 1) % 4 == 0 and not 60 < k + 1 <= 95:
            z = truth[k + 1, 0] + rng.normal(0, 0.06)
            samples.append(((k + 1) * H, z))
            gain = uncertainty[:, 0] / (uncertainty[0, 0] + obs_var)
            prediction += gain * (z - prediction[0])
            correction = np.eye(2) - np.outer(gain, [1, 0])
            uncertainty = correction @ uncertainty @ correction.T + obs_var * np.outer(gain, gain)
        estimate[k + 1] = prediction
        sigma.append(math.sqrt(uncertainty[0, 0]))
    t = np.arange(steps + 1) * H
    fig, ax = plt.subplots(2, 1, figsize=(4.35, 5.0), sharex=True, layout="constrained")
    ax[0].plot(t, truth[:, 0], label="true")
    ax[0].plot(t, estimate[:, 0], ls="--", label="estimate")
    ax[0].scatter(*np.array(samples).T, s=12, color=COLORS[2], label="position fix")
    ax[0].set_ylabel("Position (m)")
    ax[0].legend(ncol=2, fontsize=10)
    error = estimate[:, 0] - truth[:, 0]
    ax[1].plot(t, error, label="error")
    band = 2 * np.array(sigma)
    ax[1].fill_between(t, -band, band, color=COLORS[0], alpha=.15, label="model ±2 SD")
    ax[1].axvspan(6, 9.5, color=COLORS[1], alpha=.12, label="no position fixes")
    ax[1].set(xlabel="Time (s)", ylabel="Position error (m)")
    ax[1].legend(fontsize=10, ncol=2, loc="upper center", bbox_to_anchor=(.5, -.31))
    save(fig, figures, "model-estimation.svg")
    low_pass = 0
    filtered = []
    for sample in [0, 1, 1, 1, 1]:
        low_pass += 0.25 * (sample - low_pass)
        filtered.append(low_pass)
    return dict(fixes=len(samples), dead_rmse_m=np.sqrt(np.mean((dead[:, 0] - truth[:, 0])**2)),
                filter_rmse_m=np.sqrt(np.mean(error**2)), sigma_6_m=sigma[60],
                sigma_9_5_m=sigma[95], low_pass_step=filtered)


MPC_GRID = np.array(list(itertools.product(np.arange(0., 1.51, 0.25), repeat=3)))


def mpc(measurement, reference=1.0, upper_limit=1.10):
    x = np.full(len(MPC_GRID), measurement)
    cost = np.zeros(len(x))
    feasible = np.full(len(x), True)
    for u in MPC_GRID.T:
        x = A * x + B * u
        feasible &= x <= upper_limit
        cost += 4 * (x - reference)**2 + 0.1 * (u - reference)**2
    cost[~feasible] = np.inf
    if not feasible.any():
        raise ValueError("No admissible prediction for this measurement")
    return MPC_GRID[cost.argmin()]


def control(figures):
    riccati = solve_discrete_are([[A]], [[B]], [[4.]], [[0.1]]).item()
    lqr = B * riccati * A / (0.1 + B**2 * riccati)
    t = np.arange(120) * H
    noise = np.random.default_rng(10).normal(0, .015, len(t))
    models = ["P + FF", "PI + FF", "LQR + FF", "ESO + FF", "MPC"]
    records, responses, powers, mpc_time = {}, {}, {}, []

    def run(method, sensor_noise, bandwidth=3):
        x = integral = z1 = z2 = 0.
        trace, applied, estimates = [], [], []
        for k, tk in enumerate(t):
            y = x + sensor_noise[k]
            error = 1 - y
            request = 1 + 2 * error
            if method == "PI + FF":
                request += integral
            elif method == "LQR + FF":
                request = 1 + lqr * error
            elif method == "ESO + FF":
                request -= z2
            elif method == "MPC":
                start = time.perf_counter_ns()
                request = mpc(y)[0]
                mpc_time.append((time.perf_counter_ns() - start) / 1000)
            u = float(np.clip(request, 0, 1.5))
            integral += H * (error + (u - request) / .4)
            innovation = y - z1
            z1 += H * (-z1 + u + z2 + (2 * bandwidth - 1) * innovation)
            trace.append(x)
            applied.append(u)
            estimates.append(z2)
            z2 += H * bandwidth**2 * innovation
            d = -0.3 if tk >= 4 else 0.
            x = A * x + B * (u + d)
        return np.array(trace), np.array(applied), np.array(estimates)

    for method in models:
        trace, power, _ = run(method, noise)
        responses[method], powers[method] = trace, power
        records[method] = dict(iae_Ks=H * np.sum(np.abs(1 - trace)),
                               final_bias_K=np.mean(1 - trace[t >= 10]),
                               peak_W=power.max(), max_temperature_K=trace.max(),
                               final_power_sd_W=np.std(power[t >= 10]))
    fig, ax = plt.subplots(2, 1, figsize=(4.35, 5.5), sharex=True, layout="constrained")
    for i, method in enumerate(models):
        style = ["-", "--", ":", "-.", "-"][i]
        ax[0].plot(t, responses[method], label=method, ls=style, lw=1.7)
        ax[1].step(t, powers[method], where="post", ls=style, lw=1.2)
    ax[0].axhline(1, color="black", lw=.7)
    for a in ax:
        a.axvline(4, color="gray", ls="--", lw=.8)
    ax[0].set_ylabel("Temperature rise (K)")
    ax[0].legend(fontsize=10, ncol=2)
    ax[1].set(xlabel="Time (s)", ylabel="Accepted power (W)")
    save(fig, figures, "control-response.svg")

    fig, ax = plt.subplots(figsize=(4.35, 3.4), layout="constrained")
    estimates = {}
    for source, w, label in [(0 * noise, 3, "clean, w = 3"), (noise, 3, "noisy, w = 3"),
                              (noise, 7, "noisy, w = 7")]:
        _, _, est = run("ESO + FF", source, w)
        ax.plot(t, est, label=label)
        estimates[label] = np.sqrt(np.mean((est[t >= 8] + 0.3)**2))
    ax.step(t, np.where(t >= 4, -.3, 0), where="post", color="black", lw=1, ls="--", label="true")
    ax.set(xlabel="Time (s)", ylabel="Heat disturbance (W)")
    ax.legend(ncol=2, fontsize=10)
    save(fig, figures, "control-observer.svg")

    fig, ax = plt.subplots(figsize=(4.35, 3.4), layout="constrained")
    first_states = []
    for k in [7, 8, 9]:
        x = responses["MPC"][k] + noise[k]
        seq = mpc(x)
        forecast = [x]
        for u in seq:
            forecast.append(A * forecast[-1] + B * u)
        ax.plot(t[k] + H*np.arange(4), forecast, "o--", label=f"plan {k}")
        first_states.append(dict(k=k, x_K=x, planned_W=seq.tolist(), predicted_K=forecast))
    ax.plot(t[7:13], responses["MPC"][7:13], "k.-", label="plant")
    ax.set(xlabel="Time (s)", ylabel="Temperature rise (K)")
    ax.legend(ncol=2, fontsize=10)
    save(fig, figures, "control-mpc.svg")
    return dict(plant_A=A, plant_B=B, riccati=riccati, lqr_gain=lqr, lqr_pole=A-B*lqr,
                methods=records, eso_rmse_W=estimates, mpc_excerpt=first_states,
                mpc_limit_demo=dict(x0_K=1.08, r_K=1.3, limit_K=1.1,
                                    constrained_W=mpc(1.08, 1.3).tolist(),
                                    relaxed_W=mpc(1.08, 1.3, np.inf).tolist()),
                mpc_us=dict(n=len(mpc_time), median=np.median(mpc_time), maximum=max(mpc_time)))


def frequency(figures):
    w = np.geomspace(.1, 100, 600)
    fig, ax = plt.subplots(2, 1, figsize=(4.35, 4.7), sharex=True, layout="constrained")
    result = {}
    for name, lead in [("P", False), ("P + lead", True)]:
        def loop(freq):
            s = 1j * freq
            c = 2 * (1 + s/2) / (1 + s/8) if lead else 2
            return c * np.exp(-s*.06) / (1 + s)
        response = loop(w)
        cross = brentq(lambda f: abs(loop(f)) - 1, .1, 30)
        closed = lambda f: abs(loop(f) / (1 + loop(f)))
        bw = brentq(lambda f: closed(f) - closed(0) / math.sqrt(2), cross, 60)
        result[name] = dict(crossover_rad_s=cross, phase_margin_deg=180+np.angle(loop(cross), deg=True),
                            closed_bandwidth_rad_s=bw, noise_gain_20=closed(20))
        ax[0].semilogx(w, 20*np.log10(abs(response)), label=name)
        ax[1].semilogx(w, np.rad2deg(np.unwrap(np.angle(response))))
    ax[0].axhline(0, color="gray", lw=.8)
    ax[1].axhline(-180, color="gray", lw=.8)
    ax[0].set_ylabel("Loop gain (dB)")
    ax[1].set(xlabel="Angular frequency (rad/s)", ylabel="Phase (deg)")
    ax[0].legend()
    save(fig, figures, "control-frequency.svg")
    return result


def planning(figures):
    z = np.linspace(0, 1, 1001)
    def quintic(x):
        return 10*x**3 - 15*x**4 + 6*x**5
    def velocity(x):
        return 30*x**2 * (1-x)**2
    def acceleration(x):
        return 60*x * (1-x) * (1-2*x)
    travel = .6
    v_max, a_max, j_max = .5, .8, 6.
    limits = [1.875*travel/v_max, np.sqrt(10*travel/(np.sqrt(3)*a_max)),
              np.cbrt(60*travel/j_max)]
    T = math.ceil(max(limits)/.01)*.01
    fig, ax = plt.subplots(3, 1, figsize=(4.35, 5.5), sharex=True, layout="constrained")
    for panel, values, label in zip(ax, [travel*quintic(z), travel*velocity(z)/T,
                                         travel*acceleration(z)/T**2],
                                    ["Position (m)", "Velocity (m/s)", "Accel. (m/s²)"]):
        panel.plot(z*T, values)
        panel.set_ylabel(label)
    ax[-1].set_xlabel("Time (s)")
    save(fig, figures, "planning-quintic.svg")

    fig, ax = plt.subplots(2, 1, figsize=(4.35, 6.0), layout="constrained")
    ax[0].plot(z, quintic(z), label="axis X")
    ax[0].plot(z, 3*z**2 - 2*z**3, "--", label="axis Y, time sync")
    ax[0].plot(z, quintic(z), ":", lw=2.2, label="axis Y, phase sync")
    ax[0].set(xlabel="Time / duration", ylabel="Fraction of travel")
    ax[0].legend(fontsize=10)
    x = .8*(1-z)**2 + 2*(1-z)*z + z**2
    y = .2*z**2
    ax[1].plot([.8, 1, 1], [0, 0, .2], "k--", label="polyline")
    ax[1].plot(x, y, label="Bezier")
    ax[1].plot([.95], [.05], "o", ms=4)
    ax[1].set(xlabel="X (m)", ylabel="Y (m)", aspect="equal")
    ax[1].legend(fontsize=10)
    save(fig, figures, "planning-sync-corner.svg")
    stop_duration, initial_v = .6, .3
    stop_s = initial_v*stop_duration*(z - z**3 + .5*z**4)
    stop_v = initial_v*(1 - 3*z**2 + 2*z**3)
    hold_t = np.linspace(stop_duration, 1, 12)
    restart_t = np.linspace(1, 1+T, len(z))
    fig, ax = plt.subplots(2, 1, figsize=(4.35, 4.3), sharex=True, layout="constrained")
    for panel, braking, hold, resume, label in [
        (ax[0], stop_s, stop_s[-1], stop_s[-1] + travel*quintic(z), "Position (m)"),
        (ax[1], stop_v, 0, travel*velocity(z)/T, "Velocity (m/s)"),
    ]:
        panel.plot(z*stop_duration, braking, label="brake")
        panel.plot(hold_t, np.full_like(hold_t, hold), label="hold")
        panel.plot(restart_t, resume, label="resume")
        panel.set_ylabel(label)
    ax[0].legend(ncol=3)
    ax[1].set_xlabel("Time (s)")
    save(fig, figures, "planning-handover.svg")
    return dict(time_bounds_s=limits, duration_s=T, mid_q_m=travel*quintic(.5),
                peak_v_m_s=travel*1.875/T, peak_a_m_s2=travel*10/(np.sqrt(3)*T**2),
                peak_j_m_s3=60*travel/T**3, brake_distance_m=stop_s[-1],
                brake_peak_a_m_s2=1.5*initial_v/stop_duration,
                brake_peak_j_m_s3=6*initial_v/stop_duration**2,
                path_corner_mid_m=[x[len(z)//2], y[len(z)//2]],
                short_triangle_s=2*math.sqrt(.12/.8),
                long_trapezoid_s=2*.5/.8+(.6-.5**2/.8)/.5)


def speed_profiles(figures):
    distance, max_speed, accel, jerk = .6, .5, .8, 6.
    ramp = accel / jerk
    constant_accel = max_speed / accel - ramp
    accel_phase = 2*ramp + constant_accel
    cruise = distance / max_speed - accel_phase
    durations = [ramp, constant_accel, ramp, cruise, ramp, constant_accel, ramp]
    jerks = [jerk, 0., -jerk, 0., -jerk, 0., jerk]
    q = speed = a = elapsed = 0.
    times, speeds, accelerations = [], [], []
    for dt, j in zip(durations, jerks):
        local = np.linspace(0., dt, 35)
        times.extend(elapsed + local)
        speeds.extend(speed + a*local + j*local**2/2)
        accelerations.extend(a + j*local)
        q += speed*dt + a*dt**2/2 + j*dt**3/6
        speed += a*dt + j*dt**2/2
        a += j*dt
        elapsed += dt
    assert abs(q - distance) < 1e-12 and abs(speed) < 1e-12 and abs(a) < 1e-12
    fig, ax = plt.subplots(2, 1, figsize=(4.35, 4.5), sharex=True, layout="constrained")
    ax[0].plot(times, speeds, label="S curve")
    ax[1].plot(times, accelerations)
    for length, label in [(distance, "trapezoid"), (.12, "triangle")]:
        peak = min(max_speed, math.sqrt(length*accel))
        t_acc = peak/accel
        t_flat = max(0., (length - peak**2/accel)/peak)
        end = 2*t_acc + t_flat
        t = [0, t_acc, t_acc+t_flat, end]
        ax[0].plot(t, [0, peak, peak, 0], "--", label=label)
        ax[1].step(t, [accel, 0, -accel, 0], where="post", ls="--")
        assert math.isclose(peak * (t_acc + t_flat), length)
    ax[0].set_ylabel("Velocity (m/s)")
    ax[0].legend(ncol=2, fontsize=10)
    ax[1].set(xlabel="Time (s)", ylabel="Accel. (m/s²)")
    save(fig, figures, "planning-speed.svg")
    return dict(s_curve_duration_s=elapsed, s_curve_segment_durations_s=durations,
                s_curve_final_position_m=q, s_curve_peak_velocity_m_s=max(speeds))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path("results"))
    parser.add_argument("--figures", type=Path, default=Path("figures"))
    args = parser.parse_args()
    for path in [args.figures, args.output]:
        path.mkdir(parents=True, exist_ok=True)
    angle = math.pi/2
    rotation = np.array([[math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)]])
    marker = np.array([1, 2]) + rotation @ np.array([.2 + .8, 0.])
    checks = dict(wheel_speed_m_s=.05 * (600*2*math.pi/60) / 5,
                  marker_field_m=marker.tolist(), adc_code_width_mV=3.3*1000/4096,
                  power_duty=1.2/2, lqr_first_limited_step_K=B*1.5,
                  vertical_forces_N=[2*(9.81+3), 2*(9.81+3/4), 3*9.81],
                  scaled_acceleration_m_s2=2*.5**2 - .2*2)
    results = dict(environment=dict(python=platform.python_version(), system=platform.system(),
                                    machine=platform.machine(), numpy=np.__version__,
                                    scipy=scipy.__version__, matplotlib=matplotlib.__version__),
                   unit_examples=checks,
                   identification=thermal_model(args.figures), estimation=estimation(args.figures),
                   control=control(args.figures), frequency=frequency(args.figures),
                   planning=planning(args.figures), speed_profiles=speed_profiles(args.figures))
    assert results["control"]["lqr_pole"] < 1
    assert results["estimation"]["filter_rmse_m"] < results["estimation"]["dead_rmse_m"]
    assert results["planning"]["peak_v_m_s"] <= .5
    assert results["planning"]["peak_a_m_s2"] <= .8
    assert results["planning"]["peak_j_m_s3"] <= 6
    path = args.output / "results.json"
    path.write_text(json.dumps(results, indent=2) + "\n", encoding="utf-8")
    print(path)


if __name__ == "__main__":
    main()
