#!/usr/bin/env python3
"""PID versus finite-horizon linear MPC: deterministic 1D teaching simulation.

Python 3.9+, standard library only. No robot interface or real-time guarantee.
Run --self-test, then --output-dir demo-output. See README.txt for the model,
fixed tuning, sample convention and limits. Both controllers receive only
current position, velocity and reference; neither sees future input rows.
"""

import argparse
import csv
import itertools
import json
import math
from pathlib import Path
import tempfile
import unittest

DT = 0.1
LIMIT = 1.0
KP, KI, KD = 4.0, 0.5, 3.0
HORIZON = 20
QP, QV, RU = 8.0, 1.0, 0.2
TOL = 1e-8
MAX_SWEEPS = 3000


def clip(value, limit=LIMIT):
    return max(-limit, min(limit, value))


def plant(position, velocity, command, disturbance=0.0, dt=DT):
    """Exact zero-order-hold double-integrator step for constant acceleration."""
    acceleration = command + disturbance
    return (position + dt * velocity + 0.5 * dt * dt * acceleration,
            velocity + dt * acceleration)


class PID:
    """Derivative on measured velocity; integral state is an output contribution."""
    def __init__(self):
        self.integral = 0.0

    def command(self, position, velocity, reference):
        error = reference - position
        candidate = self.integral + KI * DT * error
        raw = KP * error + candidate - KD * velocity
        # Freeze only if this integral change would push farther into saturation.
        if not ((raw > LIMIT and error > 0) or (raw < -LIMIT and error < 0)):
            self.integral = candidate
        return clip(KP * error + self.integral - KD * velocity)


def gradient(hessian, linear, sequence):
    return [sum(a*b for a, b in zip(row, sequence)) + f
            for row, f in zip(hessian, linear)]


def kkt_residual(sequence, grad, limit=LIMIT):
    """Infinity norm of u - projection(u - grad), zero at a box-QP optimum."""
    return max(abs(u - clip(u - g, limit)) for u, g in zip(sequence, grad))


def solve_box_qp(hessian, linear, initial=None, limit=LIMIT, tolerance=TOL):
    """Minimize 0.5*u'H*u + f'u with symmetric positive-definite H and box bounds.

    Cyclic coordinate descent performs the exact minimization along each
    coordinate, then checks the projected-gradient/KKT residual. The MPC
    construction below guarantees positive definiteness through RU > 0.
    This small solver is educational, not a general-purpose QP package.
    """
    n = len(linear)
    u = [clip(v, limit) for v in (initial if initial is not None else [0.0]*n)]
    grad = gradient(hessian, linear, u)
    for sweep in range(1, MAX_SWEEPS + 1):
        for j in range(n):
            updated = clip(u[j] - grad[j] / hessian[j][j], limit)
            change = updated - u[j]
            u[j] = updated
            if change:
                for i in range(n):
                    grad[i] += hessian[i][j] * change
        # Recompute to avoid accepting convergence from accumulated roundoff.
        grad = gradient(hessian, linear, u)
        residual = kkt_residual(u, grad, limit)
        if residual <= tolerance:
            return u, sweep, residual
    raise RuntimeError(f"QP failed convergence check: residual={residual:.3g}")


class MPC:
    """Linear, input-constrained MPC; fixed current reference, no disturbance preview.

    Sum i=1..N of QP*(p_i-r)^2 + QV*v_i^2 + RU*u_(i-1)^2.
    No extra terminal cost, terminal set, state constraint or integral estimator.
    Condensed QP is J=0.5*u'H*u+f'u+constant.
    """
    def __init__(self, horizon=HORIZON):
        self.n = horizon
        self.sp = [[DT*DT*(i-j-0.5) if j < i else 0.0
                    for j in range(horizon)] for i in range(1, horizon+1)]
        self.sv = [[DT if j < i else 0.0 for j in range(horizon)]
                   for i in range(1, horizon+1)]
        self.hessian = [[2*(sum(QP*self.sp[i][a]*self.sp[i][b]
                               + QV*self.sv[i][a]*self.sv[i][b]
                               for i in range(horizon)) + (RU if a == b else 0))
                         for b in range(horizon)] for a in range(horizon)]
        self.warm = [0.0] * horizon
        self.last = (0, 0.0)

    def problem(self, position, velocity, reference):
        free_p = [position + (i+1)*DT*velocity - reference for i in range(self.n)]
        linear = [2*sum(QP*self.sp[i][j]*free_p[i] + QV*self.sv[i][j]*velocity
                        for i in range(self.n)) for j in range(self.n)]
        constant = sum(QP*p*p + QV*velocity*velocity for p in free_p)
        return linear, constant

    def command(self, position, velocity, reference):
        linear, _ = self.problem(position, velocity, reference)
        sequence, sweeps, residual = solve_box_qp(self.hessian, linear, self.warm)
        self.warm = sequence[1:] + [sequence[-1]]
        self.last = sweeps, residual
        return sequence[0]


def scenario():
    rows = []
    for k in range(180):
        t = round(k*DT, 8)
        reference = 0.0 if t < 1 else (1.0 if t < 7 else (-0.5 if t < 13 else 0.5))
        rows.append({"time_s": t, "reference_m": reference,
                     "disturbance_m_s2": 0.25 if 9 <= t < 11 else 0.0})
    return rows


def validate_inputs(rows):
    if not rows:
        raise ValueError("An input scenario cannot be empty")
    for k, row in enumerate(rows):
        if set(row) != {"time_s", "reference_m", "disturbance_m_s2"}:
            raise ValueError("Expected time_s, reference_m, disturbance_m_s2 columns")
        if any(not math.isfinite(value) for value in row.values()):
            raise ValueError("Scenario values must be finite")
        if not math.isclose(row["time_s"], k*DT, rel_tol=0, abs_tol=1e-8):
            raise ValueError("Scenario must start at zero on the fixed 0.1 s grid")


def simulate(inputs):
    validate_inputs(inputs)
    pid, mpc = PID(), MPC()
    states = {"pid": (0.0, 0.0), "mpc": (0.0, 0.0)}
    rows = []
    for sample in inputs:
        r, disturbance = sample["reference_m"], sample["disturbance_m_s2"]
        row = dict(sample, end_time_s=round(sample["time_s"] + DT, 8))
        for name, controller in (("pid", pid), ("mpc", mpc)):
            # Only the plant receives the disturbance, after the control choice.
            command = controller.command(*states[name], r)
            p, v = plant(*states[name], command, disturbance)
            states[name] = p, v
            row.update({name+"_position_m": p, name+"_velocity_m_s": v,
                        name+"_command_m_s2": command, name+"_error_m": p-r})
        row["mpc_qp_sweeps"], row["mpc_kkt_residual"] = mpc.last
        rows.append(row)
    return rows


def metrics(rows):
    result = {}
    for name in ("pid", "mpc"):
        errors = [r[name+"_error_m"] for r in rows]
        commands = [r[name+"_command_m_s2"] for r in rows]
        result[name] = {
            "position_rmse_m": math.sqrt(sum(e*e for e in errors)/len(rows)),
            "integral_absolute_error_m_s": DT*sum(abs(e) for e in errors),
            "final_signed_error_m": errors[-1],
            "command_rms_m_s2": math.sqrt(sum(u*u for u in commands)/len(rows)),
            "maximum_absolute_command_m_s2": max(abs(u) for u in commands),
            "saturated_intervals": sum(abs(u) >= LIMIT-1e-9 for u in commands),
        }
    result["solver"] = {"maximum_kkt_residual": max(r["mpc_kkt_residual"] for r in rows),
                        "maximum_sweeps": max(r["mpc_qp_sweeps"] for r in rows),
                        "all_qps_converged": True}
    return result


def write_csv(path, rows):
    with path.open("w", encoding="utf-8", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames=list(rows[0]), lineterminator="\n")
        writer.writeheader()
        writer.writerows({k: format(v, ".17g") for k, v in row.items()} for row in rows)


def read_csv(path):
    with path.open(encoding="utf-8", newline="") as stream:
        return [{k: float(v) for k, v in row.items()} for row in csv.DictReader(stream)]


def check_output_collision(input_path, output_dir):
    """Never overwrite a replay input, including a symlink to an output file."""
    outputs = {(output_dir/name).resolve() for name in ("results.csv", "metrics.json", "response.svg")}
    if input_path is not None and input_path.resolve() in outputs:
        raise ValueError("Replay input must not coincide with results.csv, metrics.json or response.svg in the output directory")


def svg(rows):
    """Original scalable plot; table and CSV provide equivalent numerical output."""
    end = rows[-1]["end_time_s"]
    out = ['<svg xmlns="http://www.w3.org/2000/svg" width="760" height="760" viewBox="0 0 760 760" role="img" aria-labelledby="title desc">',
           '<title id="title">PID and finite-horizon MPC on the same simulated axis</title>',
           '<desc id="desc">Top: position and stepped reference. Bottom: acceleration command bounded between minus one and plus one metres per second squared. Shading marks intervals with a nonzero unmeasured acceleration disturbance, as specified by the input CSV. The accompanying CSV and table give the numerical results. This is not hardware performance.</desc>',
           '<rect width="760" height="760" fill="#f8fafc"/>',
           '<g font-family="Arial,sans-serif" fill="#172a3a">',
           '<text x="38" y="38" font-size="27" font-weight="bold">PID and MPC: identical simulated plant</text>',
           '<text x="38" y="72" font-size="22">Current setpoint only · command limit ±1 m/s²</text>']
    colors = {"pid": "#ad341b", "mpc": "#075da8", "reference": "#4e5968"}
    for j, (name, label) in enumerate((("pid","PID"),("mpc","Linear MPC"),("reference","Reference"))):
        x = 70 + 210*j
        out.append(f'<path d="M{x} 107h34" stroke="{colors[name]}" stroke-width="3" stroke-dasharray="{("7 4" if name=="pid" else "2 4" if name=="reference" else "none")}"/>')
        out.append(f'<text x="{x+42}" y="115" font-size="22">{label}</text>')
    for panel, (top, low, high, label, ticks) in enumerate(((160,-0.75,1.5,"Position (m)",[-.5,0,.5,1,1.5]),(455,-1.2,1.2,"Command (m/s²)",[-1,0,1]))):
        left, width, height = 88, 630, 195
        xy = lambda t, value: (left+width*t/end, top+height*(high-value)/(high-low))
        out.append(f'<text x="38" y="{top-16}" font-size="23" font-weight="bold">{label}</text>')
        # Shade actual nonzero disturbance intervals, rather than a hardcoded region.
        for row in rows:
            if row["disturbance_m_s2"]:
                x, _ = xy(row["time_s"], 0)
                out.append(f'<rect x="{x:.3f}" y="{top}" width="{width*DT/end+.01:.3f}" height="{height}" fill="#faedcb"/>')
        for value in ticks:
            _, y = xy(0, value)
            out.append(f'<path d="M{left} {y:.2f}h{width}" stroke="#d5dde3"/><text x="76" y="{y+7:.2f}" text-anchor="end" font-size="22">{value:g}</text>')
        for t in (0,3,6,9,12,15,18):
            if t <= end:
                x, _ = xy(t, 0)
                out.append(f'<text x="{x:.2f}" y="{top+height+28}" text-anchor="middle" font-size="22">{t}</text>')
        names = ("reference", "pid", "mpc") if panel == 0 else ("pid", "mpc")
        for name in names:
            points = []
            if name == "reference" or panel == 1:
                key = "reference_m" if name == "reference" else name+"_command_m_s2"
                for row in rows:
                    points.extend((xy(row["time_s"], row[key]),xy(row["end_time_s"], row[key])))
            else:
                points = [xy(0,0)] + [xy(row["end_time_s"],row[name+"_position_m"]) for row in rows]
            coords = " ".join(f"{x:.2f},{y:.2f}" for x,y in points)
            dash = "7 4" if name=="pid" else "2 4" if name=="reference" else "none"
            out.append(f'<polyline points="{coords}" fill="none" stroke="{colors[name]}" stroke-width="3" stroke-dasharray="{dash}"/>')
    out += ['<text x="400" y="706" text-anchor="middle" font-size="22">Time (s)</text>',
            '<text x="38" y="741" font-size="22">Shaded: unknown disturbance (see input CSV) · simulation</text>','</g></svg>']
    return "\n".join(out)+"\n"


class Checks(unittest.TestCase):
    def test_exact_plant_under_constant_acceleration(self):
        p,v=0.3,-0.2
        for _ in range(10):
            p,v=plant(p,v,.4,.1)
        self.assertAlmostEqual(p,.3-.2+.5*.5)
        self.assertAlmostEqual(v,-.2+.5)

    def test_condensed_cost_equals_independent_rollout(self):
        m=MPC(5); p,v,r=.2,-.3,.7; u=[-.4,.1,.7,-.2,.3]
        f,c=m.problem(p,v,r)
        condensed=.5*sum(u[i]*sum(m.hessian[i][j]*u[j] for j in range(5)) for i in range(5))+sum(a*b for a,b in zip(f,u))+c
        direct=0
        for command in u:
            p,v=plant(p,v,command)
            direct+=QP*(p-r)**2+QV*v*v+RU*command*command
        self.assertAlmostEqual(condensed,direct,places=11)

    def test_gradient_by_finite_difference(self):
        m=MPC(4); f,c=m.problem(.3,-.2,.8); u=[.1,-.2,.3,-.4]
        def cost(a):
            return .5*sum(a[i]*sum(m.hessian[i][j]*a[j] for j in range(4)) for i in range(4))+sum(x*y for x,y in zip(f,a))+c
        g=gradient(m.hessian,f,u)
        for j in range(4):
            plus,minus=u[:],u[:];plus[j]+=1e-5;minus[j]-=1e-5
            self.assertAlmostEqual(g[j],(cost(plus)-cost(minus))/2e-5,places=8)

    def test_box_qp_against_two_variable_active_set_oracle(self):
        h=[[4.0,1.0],[1.0,2.0]]
        for f in ([-8.0,3.0],[.2,-.4],[2.0,2.0]):
            candidates=[]
            # Enumerate both coordinates free, each edge optimum and all corners.
            candidates.append(((-2*f[0]+f[1])/7,(f[0]-4*f[1])/7))
            for a in (-1.0,1.0):
                candidates.extend(((a,clip(-(f[1]+a)/2)),(clip(-(f[0]+a)/4),a)))
            candidates.extend(itertools.product((-1.0,1.0),repeat=2))
            cost=lambda u:.5*(4*u[0]**2+2*u[0]*u[1]+2*u[1]**2)+f[0]*u[0]+f[1]*u[1]
            expected=min((u for u in candidates if max(map(abs,u))<=1),key=cost)
            actual,_,residual=solve_box_qp(h,f)
            self.assertLessEqual(residual,TOL)
            for a,b in zip(actual,expected):self.assertAlmostEqual(a,b,places=7)

    def test_pid_anti_windup_and_no_setpoint_derivative_kick(self):
        pid=PID()
        for _ in range(50):self.assertEqual(pid.command(0,0,10),1)
        self.assertEqual(pid.integral,0)
        self.assertAlmostEqual(pid.command(0,0,.1),KP*.1+KI*DT*.1)
        self.assertAlmostEqual(pid.integral,.005)

    def test_replay_metrics_constraints_and_causality(self):
        inputs=scenario()[:35]
        with tempfile.TemporaryDirectory() as temp:
            file=Path(temp)/"scenario.csv";write_csv(file,inputs)
            first,second=simulate(inputs),simulate(read_csv(file))
        self.assertEqual(first,second)
        altered=[dict(r,reference_m=-1 if k>=30 else r["reference_m"]) for k,r in enumerate(inputs)]
        self.assertEqual(first[:30],simulate(altered)[:30])
        for row in first:
            self.assertLessEqual(abs(row["pid_command_m_s2"]),LIMIT)
            self.assertLessEqual(abs(row["mpc_command_m_s2"]),LIMIT)
            self.assertLessEqual(row["mpc_kkt_residual"],TOL)
        report=metrics(first)
        for name in ("pid","mpc"):
            errors=[r[name+"_error_m"] for r in first]
            self.assertAlmostEqual(report[name]["position_rmse_m"],math.hypot(*errors)/math.sqrt(len(errors)),places=12)

    def test_zero_equilibrium(self):
        self.assertEqual(PID().command(0,0,0),0)
        self.assertEqual(MPC().command(0,0,0),0)

    def test_invalid_scenario(self):
        for rows in ([],[{"time_s":.03,"reference_m":0,"disturbance_m_s2":0}],
                     [{"time_s":0,"reference_m":float("nan"),"disturbance_m_s2":0}]):
            with self.assertRaises(ValueError):validate_inputs(rows)

    def test_replay_output_path_collision(self):
        with tempfile.TemporaryDirectory() as temp:
            directory=Path(temp)
            for name in ("results.csv", "metrics.json", "response.svg"):
                with self.assertRaises(ValueError):
                    check_output_collision(directory/name,directory)
            check_output_collision(directory/"scenario.csv",directory)
            check_output_collision(directory/"input"/"results.csv",directory/"output")
            (directory/"alias.csv").symlink_to(directory/"results.csv")
            with self.assertRaises(ValueError):
                check_output_collision(directory/"alias.csv",directory)


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--self-test",action="store_true")
    parser.add_argument("--input",type=Path,help="Replay a scenario CSV; otherwise generate the published scenario")
    parser.add_argument("--output-dir",type=Path,default=Path("demo-output"))
    args=parser.parse_args()
    if args.self_test:
        result=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(Checks))
        raise SystemExit(0 if result.wasSuccessful() else 1)
    try:
        check_output_collision(args.input,args.output_dir)
    except ValueError as exc:
        parser.error(str(exc))
    inputs=read_csv(args.input) if args.input else scenario()
    rows=simulate(inputs)
    args.output_dir.mkdir(parents=True,exist_ok=True)
    if not args.input:write_csv(args.output_dir/"scenario.csv",inputs)
    write_csv(args.output_dir/"results.csv",rows)
    report={"model":"synthetic zero-order-hold double integrator; full-state observation", "sample_dt_s":DT,
            "duration_s":rows[-1]["end_time_s"],"intervals":len(rows),"command_limit_m_s2":LIMIT,
            "pid":{"kp":KP,"ki":KI,"kd":KD,"anti_windup":"conditional integration","derivative":"on measured velocity"},
            "mpc":{"horizon_steps":HORIZON,"position_weight":QP,"velocity_weight":QV,"command_weight":RU,
                   "solver":"cyclic coordinate descent on strictly convex box QP","kkt_tolerance":TOL,
                   "max_sweeps":MAX_SWEEPS,"preview":False,"disturbance_estimator":False},"metrics":metrics(rows)}
    (args.output_dir/"metrics.json").write_text(json.dumps(report,indent=2,sort_keys=True)+"\n",encoding="utf-8")
    (args.output_dir/"response.svg").write_text(svg(rows),encoding="utf-8")
    print(json.dumps(report["metrics"],indent=2))


if __name__ == "__main__":
    main()
