#!/usr/bin/env python3
"""Deterministic yaw-fusion teaching experiment. Python 3.9+, standard library.

No ROS, hardware driver, camera, position estimate or actuator command.
Run --self-test, then --output-dir demo-output. See README.txt for assumptions.
"""

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

DT = 0.01
DURATION = 12.0
TRACK = 0.4
DELAY = 0.2
GAIN = 0.15  # Per encoder update at 20 Hz; illustrative, not tuned to hardware.
RAD = math.pi / 180.0


def true_yaw(t):
    """Piecewise constant turn rates: +60 deg/s at 2-5 s, -45 at 7-10 s."""
    return RAD * (60 * min(max(t - 2, 0), 3) - 45 * min(max(t - 7, 0), 3))


def generate():
    imu, encoders, truth = [], [], []
    for k in range(round(DURATION / DT) + 1):
        t = round(k * DT, 8)
        yaw = true_yaw(t)
        rate = (yaw - true_yaw(t - DT)) / DT if k else 0.0
        # Rates represent the preceding 10 ms interval, so integration is exact
        # for the ideal component even at the intentionally abrupt turn changes.
        gyro = rate + RAD * (0.8 + 0.1 * math.sin(2 * math.pi * 0.9 * t))
        imu.append({"time_s": t, "gyro_z_rad_s": gyro})
        truth.append({"time_s": t, "yaw_rad": yaw})
        if k % 5 == 0:
            # Cumulative encoder distances. A bounded differential error is
            # deliberately favorable to wheel odometry; no slip or scale drift.
            error = RAD * (0.6 * math.sin(2 * math.pi * 1.3 * t)
                           + 0.25 * math.sin(2 * math.pi * 0.7 * t))
            wheel_yaw = yaw + error
            distance = 0.5 * t
            encoders.append({"capture_s": t, "arrival_s": round(t + DELAY, 8),
                             "left_m": distance - TRACK * wheel_yaw / 2,
                             "right_m": distance + TRACK * wheel_yaw / 2})
    return imu, encoders, truth


def require_finite(rows):
    if not rows or any(not math.isfinite(float(v)) for row in rows for v in row.values()):
        raise ValueError("Inputs must contain finite numeric samples")


def estimate(imu, encoders, track=TRACK, gain=GAIN, align_timestamps=True):
    """Fuse measured gyro and wheel distances only; never reads truth.

    This additive, unwrapped-yaw model compensates an encoder packet's age with
    stored gyro increments. It is not a general delayed-measurement EKF.
    """
    require_finite(imu)
    require_finite(encoders)
    if not math.isfinite(track) or track <= 0 or not 0 <= gain <= 1:
        raise ValueError("Require positive track and gain between zero and one")
    times = [r["time_s"] for r in imu]
    if times[0] != 0 or any(b <= a for a, b in zip(times, times[1:])):
        raise ValueError("IMU times must start at zero and strictly increase")
    by_time = {round(t, 8): k for k, t in enumerate(times)}
    events = {}
    previous_capture = -1.0
    for r in encoders:
        capture, arrival = r["capture_s"], r["arrival_s"]
        if capture <= previous_capture or arrival < capture:
            raise ValueError("Encoder captures must increase and arrival cannot precede capture")
        previous_capture = capture
        capture_key, arrival_key = round(capture, 8), round(arrival, 8)
        if capture_key not in by_time:
            raise ValueError("Encoder captures must coincide with an IMU timestamp")
        if arrival > times[-1]:
            continue  # These packets have not arrived by the evaluation horizon.
        if arrival_key not in by_time:
            raise ValueError("This teaching model requires grid-aligned arrival times")
        events.setdefault(by_time[arrival_key], []).append((by_time[capture_key], r))

    integral = [0.0] * len(imu)
    yaw, output = 0.0, []
    for k, sample in enumerate(imu):
        if k:
            increment = sample["gyro_z_rad_s"] * (times[k] - times[k - 1])
            integral[k] = integral[k - 1] + increment
            yaw += increment
        for captured_k, packet in events.get(k, []):
            wheel_yaw = (packet["right_m"] - packet["left_m"]) / track
            reference = wheel_yaw
            if align_timestamps:
                reference += integral[k] - integral[captured_k]
            # Fault mode skips propagation and treats the old heading as current.
            yaw += gain * (reference - yaw)
        output.append(yaw)
    return output


def evaluate(imu, encoders, truth):
    require_finite(truth)
    if [r["time_s"] for r in truth] != [r["time_s"] for r in imu]:
        raise ValueError("Truth and IMU timestamps must match for evaluation")
    series = {
        "gyro_only": estimate(imu, encoders, gain=0.0),
        "aligned_fusion": estimate(imu, encoders),
        "wrong_time_fusion": estimate(imu, encoders, align_timestamps=False),
    }
    results, metrics = [], {}
    for k, row in enumerate(truth):
        item = {"time_s": row["time_s"], "truth_yaw_deg": row["yaw_rad"] / RAD}
        for name, values in series.items():
            item[name + "_error_deg"] = (values[k] - row["yaw_rad"]) / RAD
        results.append(item)
    for name in series:
        errors = [r[name + "_error_deg"] for r in results]
        metrics[name] = {"rmse_deg": math.sqrt(sum(x * x for x in errors) / len(errors)),
                         "max_abs_error_deg": max(abs(x) for x in errors),
                         "final_error_deg": errors[-1]}
    return results, metrics


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


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


def svg(results):
    """Accessible, fixed-scale chart; numerical table is also in the article."""
    x0, y0, width, height = 88, 125, 820, 280
    xmin, xmax, ymin, ymax = 0, 12, -15, 12
    def point(t, e):
        return x0 + (t - xmin) / (xmax - xmin) * width, y0 + (ymax - e) / (ymax - ymin) * height
    lines = ['<svg xmlns="http://www.w3.org/2000/svg" width="960" height="500" viewBox="0 0 960 500" role="img" aria-labelledby="title desc">',
             '<title id="title">Yaw error with correct and incorrect sensor timestamps</title>',
             '<desc id="desc">Deterministic 12-second simulation. Incorrectly applying a 200-millisecond-old encoder heading produces a large error during turns. Blue is aligned fusion, red dashed is the timing fault, grey dotted is gyro only. Exact metrics and CSV data accompany this figure.</desc>',
             '<rect width="960" height="500" fill="#ffffff"/>',
             '<g font-family="Arial, sans-serif" fill="#172a3a">',
             '<text x="88" y="32" font-size="23" font-weight="bold">A stale measurement can make fusion worse</text>',
             '<text x="88" y="59" font-size="17">Simulated yaw error; the two fusion runs differ only in timestamp handling</text>']
    specs = [("gyro_only", "Gyro only", "#616a75", "3 5"),
             ("aligned_fusion", "Time-aligned fusion", "#075da8", ""),
             ("wrong_time_fusion", "200 ms timing fault", "#b32332", "10 5")]
    for j, (_, label, color, dash) in enumerate(specs):
        x = 88 + j * 280
        lines += [f'<path d="M{x} 91h34" stroke="{color}" stroke-width="3" stroke-dasharray="{dash}"/>',
                  f'<text x="{x+42}" y="97" font-size="17">{label}</text>']
    for e in [-15, -10, -5, 0, 5, 10]:
        _, y = point(0, e)
        lines += [f'<path d="M{x0} {y:.2f}h{width}" stroke="#d5dde3"/>',
                  f'<text x="76" y="{y+6:.2f}" text-anchor="end" font-size="17">{e}</text>']
    for t in range(0, 13, 2):
        x, _ = point(t, 0)
        lines += [f'<path d="M{x:.2f} {y0}v{height}" stroke="#edf0f3"/>',
                  f'<text x="{x:.2f}" y="433" text-anchor="middle" font-size="17">{t}</text>']
    for name, _, color, dash in specs:
        points = " ".join(f"{x:.2f},{y:.2f}" for x, y in
                          (point(r["time_s"], r[name + "_error_deg"]) for r in results))
        lines.append(f'<polyline points="{points}" fill="none" stroke="{color}" stroke-width="2.5" stroke-dasharray="{dash}"/>')
    lines += ['<text x="498" y="465" text-anchor="middle" font-size="18">Time (s)</text>',
              '<text x="24" y="275" transform="rotate(-90 24 275)" text-anchor="middle" font-size="18">Yaw error (degrees)</text>',
              '<text x="88" y="490" font-size="15">Illustrative model only: no wheel slip, no absolute heading reference, no hardware test.</text>',
              '</g></svg>']
    return "\n".join(lines) + "\n"


class Checks(unittest.TestCase):
    def setUp(self):
        self.imu, self.enc, self.truth = generate()

    def test_exact_ideal_kinematics_and_fusion(self):
        ideal_imu = [{"time_s": r["time_s"], "gyro_z_rad_s":
                      (r["yaw_rad"] - self.truth[k-1]["yaw_rad"]) / DT if k else 0}
                     for k, r in enumerate(self.truth)]
        ideal_enc = [{"capture_s": p["capture_s"], "arrival_s": p["arrival_s"],
                      "left_m": -TRACK * true_yaw(p["capture_s"]) / 2,
                      "right_m": TRACK * true_yaw(p["capture_s"]) / 2} for p in self.enc]
        values = estimate(ideal_imu, ideal_enc)
        self.assertLess(max(abs(v-r["yaw_rad"]) for v, r in zip(values, self.truth)), 1e-10)

    def test_same_results_when_delay_is_zero(self):
        enc = [dict(p, arrival_s=p["capture_s"]) for p in self.enc]
        self.assertEqual(estimate(self.imu, enc), estimate(self.imu, enc, align_timestamps=False))

    def test_timing_fault_has_large_cost(self):
        _, m = evaluate(self.imu, self.enc, self.truth)
        self.assertLess(m["aligned_fusion"]["rmse_deg"], 0.6)
        self.assertGreater(m["wrong_time_fusion"]["rmse_deg"], 5.0)
        self.assertGreater(m["wrong_time_fusion"]["rmse_deg"], 10*m["aligned_fusion"]["rmse_deg"])

    def test_fault_disappears_when_robot_does_not_turn(self):
        imu = [{"time_s": r["time_s"], "gyro_z_rad_s": 0} for r in self.imu]
        enc = [dict(p, left_m=p["capture_s"], right_m=p["capture_s"]) for p in self.enc]
        self.assertEqual(estimate(imu, enc), estimate(imu, enc, align_timestamps=False))

    def test_future_packets_do_not_change_past_estimates(self):
        changed = [dict(p, right_m=p["right_m"] + (1 if p["capture_s"] >= 6 else 0))
                   for p in self.enc]
        before, after = estimate(self.imu, self.enc), estimate(self.imu, changed)
        self.assertEqual(before[:620], after[:620])  # First changed arrival: 6.2 s.
        self.assertNotEqual(before[620], after[620])

    def test_constant_turn_matches_analytic_timing_error(self):
        rate = 60 * RAD
        imu = [dict(p, gyro_z_rad_s=rate) for p in self.imu]
        enc = [dict(p, left_m=-TRACK * rate * p["capture_s"] / 2,
                    right_m=TRACK * rate * p["capture_s"] / 2) for p in self.enc]
        aligned = estimate(imu, enc, gain=1)
        stale = estimate(imu, enc, gain=1, align_timestamps=False)
        self.assertAlmostEqual(aligned[400], rate * 4, places=10)
        self.assertAlmostEqual((stale[400] - aligned[400]) / RAD, -12, places=10)

    def test_invalid_timestamps_and_nonfinite_data_rejected(self):
        for enc in ([dict(self.enc[0], arrival_s=-1)] + self.enc[1:],
                    [dict(self.enc[0], capture_s=0.003)] + self.enc[1:]):
            with self.assertRaises(ValueError):
                estimate(self.imu, enc)
        with self.assertRaises(ValueError):
            estimate([dict(self.imu[0], gyro_z_rad_s=float("nan"))], self.enc)

    def test_independent_metric_calculation(self):
        rows, metrics = evaluate(self.imu, self.enc, self.truth)
        for name, m in metrics.items():
            errors = [r[name + "_error_deg"] for r in rows]
            self.assertAlmostEqual(m["rmse_deg"], math.hypot(*errors)/math.sqrt(len(errors)), places=12)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input-dir", type=Path, help="Read imu.csv, encoders.csv and truth.csv instead of generating them")
    parser.add_argument("--output-dir", type=Path, default=Path("demo-output"))
    parser.add_argument("--self-test", action="store_true")
    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)
    args.output_dir.mkdir(parents=True, exist_ok=True)
    names = ("imu.csv", "encoders.csv", "truth.csv")
    if args.input_dir:
        data = [read_csv(args.input_dir / name) for name in names]
    else:
        data = generate()
        for name, rows in zip(names, data):
            write_csv(args.output_dir / name, rows)
        # Published metrics use precisely the rounded CSV samples readers receive.
        data = [read_csv(args.output_dir / name) for name in names]
    results, metrics = evaluate(*data)
    write_csv(args.output_dir / "results.csv", results)
    payload = {"model": "synthetic differential-drive yaw only", "duration_s": DURATION,
               "imu_hz": 100, "encoders_hz": 20, "delay_s": DELAY, "track_m": TRACK,
               "gain_per_encoder_update": GAIN, "evaluated_samples": len(results), "metrics": metrics}
    (args.output_dir / "metrics.json").write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    (args.output_dir / "yaw-error.svg").write_text(svg(results), encoding="utf-8")
    for name, m in metrics.items():
        print(f'{name:20s} RMSE={m["rmse_deg"]:.3f} deg  max={m["max_abs_error_deg"]:.3f} deg  final={m["final_error_deg"]:+.3f} deg')


if __name__ == "__main__":
    main()
