#!/usr/bin/env python3
"""
Generate the register-level figures for the paper.

Every figure here is produced by running the gate in `armulator_bridge.py`, not by
plotting numbers copied out of it. Rerunning this script regenerates the figures from
the models, so a change in the motor or protocol model shows up in the paper rather
than silently disagreeing with it.

    python3 tools/generate_paper_figures.py [--outdir figures]

Needs armulator cloned beside robotsim and matplotlib. Needs no Blender: the point of
the offline gate is that it runs on a build machine without one.
"""

import argparse
import math
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
if ROOT not in sys.path:
    sys.path.insert(0, ROOT)

import matplotlib                                        # noqa: E402
matplotlib.use('Agg')
import matplotlib.pyplot as plt                          # noqa: E402

import armulator_bridge as bridge                        # noqa: E402

DT = 1.0 / 60.0

## Small type: these land at half or full text width in a two-column-ish layout, and
## default matplotlib sizing is unreadable once scaled down.
plt.rcParams.update({
    'font.size': 8,
    'axes.titlesize': 9,
    'axes.labelsize': 8,
    'legend.fontsize': 7,
    'xtick.labelsize': 7,
    'ytick.labelsize': 7,
    'axes.grid': True,
    'grid.alpha': 0.25,
    'figure.dpi': 200,
})

REFERENCE_COLOUR = '#555555'
REGISTER_COLOUR = '#c81e3c'


def require():
    if not bridge.available():
        print('cannot generate figures: %s' % bridge.why_unavailable())
        raise SystemExit(1)


# ---------------------------------------------------------------------------
# figure 1: what the register layer actually does to a motor
# ---------------------------------------------------------------------------

def figure_motor(path):
    """
    One motor driven through a profile, recorded at the bridge and at the shaft.

    This is the figure that makes the register layer concrete: firmware writes a duty
    cycle and a direction, and the shaft responds with a lag, a sign and a deadband
    that no value-level seam represents.
    """
    from armulator.peripherals.motor_hat import MotorHat
    from armulator.peripherals.pca9685 import LED0_ON_L, MODE1, MODE1_AI
    from armulator.telemetry import MotorTelemetry

    hat = MotorHat()
    hat.controller.write([MODE1, MODE1_AI])
    hat.attach_dc_motor(1, free_speed=2.0, spin_up=0.15)

    def channel(index, duty):
        count = int(duty * 4095)
        hat.controller.write([LED0_ON_L + 4 * index, 0, 0, count & 0xFF, count >> 8])

    def command(drive):
        pwm, in2, in1 = hat.channels[1].channels
        if drive is None:                       # both pins high: brake
            channel(in1, 1.0)
            channel(in2, 1.0)
            return
        channel(in1, 1.0 if drive > 0 else 0.0)
        channel(in2, 1.0 if drive < 0 else 0.0)
        channel(pwm, abs(drive))

    telemetry = MotorTelemetry(hat, interval=0.002)

    ## A profile chosen so each panel shows something a value seam cannot: a ramp, a
    ## reversal, a duty below the stall threshold, and a brake that is not a coast.
    ## Brake is placed after a run at full speed, not after the shaft has already
    ## coasted to rest, or the panel shows nothing distinguishable from a coast.
    for drive, seconds in ((0.4, 0.4), (1.0, 0.4), (-0.8, 0.4),
                           (0.05, 0.35), (1.0, 0.4), (None, 0.35)):
        command(drive)
        hat.advance(seconds)

    fields = ('mode_code', 'drive', 'speed', 'position')
    labels = ('bridge mode', 'signed drive', 'shaft speed\n(rev/s)',
              'position\n(rev)')
    figure, axes = plt.subplots(len(fields), 1, sharex=True, figsize=(6.2, 4.1))

    from armulator.telemetry.recorder import MODE_CODES
    for ax, field, label in zip(axes, fields, labels):
        times, values = telemetry.series(1, field)
        step = field in ('mode_code', 'drive')
        ax.plot(times, values, color=REGISTER_COLOUR, linewidth=1.0,
                drawstyle='steps-post' if step else 'default')
        ax.set_ylabel(label)
        if field == 'mode_code':
            ticks = sorted(MODE_CODES.values())
            names = {code: name for name, code in MODE_CODES.items()}
            ax.set_yticks(ticks)
            ax.set_yticklabels([names[code] for code in ticks])
            ax.set_ylim(min(ticks) - 0.4, max(ticks) + 0.4)
        if field == 'drive':
            ax.axhline(0.0, color='black', linewidth=0.6, alpha=0.4)

    ## Annotate the two behaviours a reader is most likely to misread as bugs. Both
    ## are pointed at the panel that actually shows them: the sub-stall duty is only
    ## visible as a non-zero drive, and braking is only visible as a rate of decay.
    axes[1].annotate('0.05 duty: below\nthe stall threshold', xy=(1.35, 0.05),
                     xytext=(0.10, -0.88), fontsize=6.5,
                     arrowprops=dict(arrowstyle='->', lw=0.6))
    axes[2].annotate('brake: shorted,\nstops fast', xy=(1.98, 1.0),
                     xytext=(1.15, 1.15), fontsize=6.5,
                     arrowprops=dict(arrowstyle='->', lw=0.6))

    axes[-1].set_xlabel('time (s)')
    figure.align_ylabels(axes)
    figure.tight_layout()
    figure.savefig(path, bbox_inches='tight')
    plt.close(figure)
    print('wrote %s' % path)


# ---------------------------------------------------------------------------
# figure 2: the two paths, side by side
# ---------------------------------------------------------------------------

def figure_conformance(path):
    """
    The gate itself: the same commands through the value seam and the register path.

    Three panels because there are three distinct things to show -- the transient, the
    displacement it integrates into, and the deadband, which is not a transient at all
    and never recovers.
    """
    straight = bridge.compare_drive([(3.0, 1.0, 0.0)], dt=DT)
    crawl = bridge.compare_drive([(2.0, 0.02, 0.0)], dt=DT)

    figure, axes = plt.subplots(1, 3, figsize=(9.2, 2.5))

    # -- wheel speed -------------------------------------------------------
    ax = axes[0]
    times = [row[0] for row in straight.plant_path]
    commanded = [row[4] for row in straight.plant_path]
    actual = [row[5] for row in straight.plant_path]
    ax.plot(times, commanded, color=REFERENCE_COLOUR, linewidth=1.2,
            label='value seam', drawstyle='steps-post')
    ax.plot(times, actual, color=REGISTER_COLOUR, linewidth=1.2,
            label='register path')
    ax.set_xlabel('time (s)')
    ax.set_ylabel('wheel speed (m/s)')
    ax.set_title('(a) spin-up transient')
    ax.legend(loc='lower right')

    # -- displacement ------------------------------------------------------
    ax = axes[1]
    ax.plot([r[0] for r in straight.reference_path],
            [r[2] for r in straight.reference_path],
            color=REFERENCE_COLOUR, linewidth=1.2, label='value seam')
    ax.plot([r[0] for r in straight.plant_path],
            [r[2] for r in straight.plant_path],
            color=REGISTER_COLOUR, linewidth=1.2, label='register path')
    ax.set_xlabel('time (s)')
    ax.set_ylabel('distance travelled (m)')
    ax.set_title('(b) %.3f m residual lag' % straight.final_position_error)
    ax.legend(loc='upper left')

    # -- stall deadband ----------------------------------------------------
    ax = axes[2]
    ax.plot([r[0] for r in crawl.reference_path],
            [r[2] for r in crawl.reference_path],
            color=REFERENCE_COLOUR, linewidth=1.2, label='value seam')
    ax.plot([r[0] for r in crawl.plant_path],
            [r[2] for r in crawl.plant_path],
            color=REGISTER_COLOUR, linewidth=1.2, label='register path')
    ax.set_xlabel('time (s)')
    ax.set_ylabel('distance travelled (m)')
    ax.set_title('(c) 0.02 m/s: below stall')
    ax.legend(loc='upper left')

    figure.tight_layout()
    figure.savefig(path, bbox_inches='tight')
    plt.close(figure)
    print('wrote %s  (lag %.4f m, steady-state error %.4f m/s)'
          % (path, straight.final_position_error, straight.final_speed_error))
    return straight, crawl


# ---------------------------------------------------------------------------
# figure 3: the sensor half of the same loop
# ---------------------------------------------------------------------------

def figure_lidar(path):
    """
    A scan recovered from the RPLIDAR wire, against the geometry that produced it.

    The left panel is what firmware would decode; the right is why the gate needs an
    angular tolerance rather than a distance one.
    """
    from armulator.sensors import Room

    room = Room(4.0)
    room.add_obstacle(2.0, 0.5, 0.4, name='box')
    room.add_obstacle(-1.5, -1.5, 0.7, name='pillar')

    report = bridge.compare_lidar(room, seconds=1.0, dt=DT,
                                  pose=(0.8, -0.4, 0.0), sample_rate=3000)

    figure = plt.figure(figsize=(7.4, 3.1))

    # -- the scan ----------------------------------------------------------
    ax = figure.add_subplot(1, 2, 1, projection='polar')
    bearings = [math.radians(p[0]) for p in report.pairs]
    ranges = [p[2] for p in report.pairs]
    ax.scatter(bearings, ranges, s=1.0, color=REGISTER_COLOUR, alpha=0.7)
    sweep = [math.radians(d) for d in range(0, 361)]
    truth = [room.range_at((0.8, -0.4), b) for b in sweep]
    ax.plot(sweep, truth, color=REFERENCE_COLOUR, linewidth=0.7, alpha=0.7)
    ax.set_ylim(0, 6.0)
    ax.set_theta_zero_location('E')
    ax.set_title('(a) decoded from the wire\n(%d returns)' % report.compared, pad=12)

    # -- where the error comes from ---------------------------------------
    ax = figure.add_subplot(1, 2, 2)
    naive = [abs(p[1] - p[2]) * 1000.0 for p in report.pairs]
    ax.hist(naive, bins=40, color=REGISTER_COLOUR, alpha=0.8)
    ax.axvline(report.QUANTISATION * 1000.0, color='black', linewidth=0.9,
               label='distance LSB (%.3f mm)' % (report.QUANTISATION * 1000.0))
    ax.set_yscale('log')
    ax.set_xlabel('naive range error (mm)')
    ax.set_ylabel('returns')
    ax.set_title('(b) dominated by the angle LSB')
    ax.legend(loc='upper right')

    figure.tight_layout()
    figure.savefig(path, bbox_inches='tight')
    plt.close(figure)
    print('wrote %s  (%d ranges, bracketed error %.6f m, naive %.6f m)'
          % (path, report.compared, report.max_range_error, report.max_raw_error))
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--outdir', default=os.path.join(ROOT, 'figures'))
    args = parser.parse_args()

    require()
    os.makedirs(args.outdir, exist_ok=True)

    figure_motor(os.path.join(args.outdir, 'fig_motor.png'))
    straight, crawl = figure_conformance(
        os.path.join(args.outdir, 'fig_conformance.png'))
    report = figure_lidar(os.path.join(args.outdir, 'fig_lidar.png'))

    ## Printed so the numbers quoted in the paper can be checked against a run
    ## rather than trusted.
    print('')
    print('numbers for the paper:')
    print('  straight-line residual lag   %.4f m over 3.0 s'
          % straight.final_position_error)
    print('  steady-state wheel error     %.4f m/s' % straight.final_speed_error)
    print('  peak transient wheel error   %.4f m/s' % straight.max_speed_error)
    print('  crawl: value seam            %.4f m' % crawl.reference_pose[1])
    print('  crawl: register path         %.4f m' % crawl.plant_pose[1])
    print('  lidar ranges compared        %d' % report.compared)
    print('  lidar error vs bracket       %.6f m' % report.max_range_error)
    print('  lidar naive error            %.6f m' % report.max_raw_error)


if __name__ == '__main__':
    main()
