#!/usr/bin/env python3
"""One-dimensional LIPM teaching example; Python standard library only.

This computes an ideal capture ZMP, not a feasible footstep or robot command.
Assumptions: point mass, fixed CoM height, level ground, no angular-momentum
change, exact state, and an instantaneous support change at capture time.
No hardware, collision, friction, torque or swing-leg constraints are tested.

Equations: Englsberger & Ott (2012), Sec. II-A, equations (1)-(4):
https://elib.dlr.de/79926/1/JohannesEnglsberger_HumanoidsPaper_2012.pdf
The numerical scenario, figure and executable checks below are original.
"""

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


def frequency(height, gravity=9.81):
    """Return sqrt(g/h), in inverse seconds, for positive finite g and h."""
    if not all(math.isfinite(v) and v > 0 for v in (height, gravity)):
        raise ValueError("height and gravity must be positive and finite")
    return math.sqrt(gravity / height)


def capture_point(x, velocity, height, gravity=9.81):
    """Horizontal capture point in metres; all positions share one frame."""
    if not all(math.isfinite(v) for v in (x, velocity)):
        raise ValueError("position and velocity must be finite")
    return x + velocity / frequency(height, gravity)


def advance(x, velocity, zmp, seconds, height, gravity=9.81):
    """Exact LIPM evolution for a CONSTANT ZMP; return (x, velocity)."""
    if not all(math.isfinite(v) for v in (x, velocity, zmp, seconds)) or seconds < 0:
        raise ValueError("finite inputs and nonnegative time are required")
    w = frequency(height, gravity)
    c, s = math.cosh(w * seconds), math.sinh(w * seconds)
    return zmp + (x - zmp) * c + velocity * s / w, w * (x - zmp) * s + velocity * c


def example():
    h, g, x0, v0, delay = 0.80, 9.81, 0.020, 0.60, 0.200
    w = frequency(h, g)
    instant = capture_point(x0, v0, h, g)
    xd, vd = advance(x0, v0, 0.0, delay, h, g)
    delayed = capture_point(xd, vd, h, g)
    xc, vc = advance(x0, v0, instant, 1.0, h, g)
    return {
        "model": "1D constant-height LIPM; analytical example, no robot test",
        "height_m": h, "gravity_m_s2": g, "omega_s_inv": w,
        "initial_x_m": x0, "initial_velocity_m_s": v0,
        "current_support_interval_m": [-0.10, 0.10],
        "initial_zmp_m": 0.0, "instant_capture_zmp_m": instant,
        "instant_capture_inside_current_support": -0.10 <= instant <= 0.10,
        "delay_s": delay, "delayed_x_m": xd, "delayed_velocity_m_s": vd,
        "delayed_capture_zmp_m": delayed,
        "x_after_1s_with_instant_capture_m": xc,
        "velocity_after_1s_with_instant_capture_m_s": vc,
    }


def figure_svg():
    """Original scalable diagram; horizontal geometry and a delay curve."""
    r = example()
    w, cp = r["omega_s_inv"], r["instant_capture_zmp_m"]
    sx = lambda x: 160 + 900 * x
    curve = " ".join(
        f"{90 + 450 * i / 40:.2f},{625 - 320 * (cp * math.exp(w * .2 * i / 40)):.2f}"
        for i in range(41)
    )
    return f'''<svg xmlns="http://www.w3.org/2000/svg" width="640" height="760" viewBox="0 0 640 760" role="img" aria-labelledby="title desc">
<title id="title">Capture point after a push: ideal instant support versus a 200 millisecond delay</title>
<desc id="desc">The centre of mass starts at x=0.020 metres with forward velocity 0.60 metres per second and height 0.80 metres. Its capture point is 0.191 metres, outside the current support interval from minus 0.10 to plus 0.10 metres. Holding the ZMP at zero for 200 milliseconds moves the capture point to 0.385 metres. This is a theoretical constant-height model, not a feasible footstep plan.</desc>
<rect width="640" height="760" rx="16" fill="#f7fafc"/>
<g font-family="Arial, sans-serif" fill="#162c42">
<text x="30" y="42" font-size="26" font-weight="700">After a push: where is the capture point?</text>
<text x="30" y="74" font-size="20">Constant-height model · h = 0.80 m</text>
<text x="30" y="111" font-size="23" font-weight="700">A. Ideal instantaneous capture</text>
<line x1="50" y1="258" x2="585" y2="258" stroke="#526577" stroke-width="2"/>
<rect x="70" y="249" width="180" height="18" rx="3" fill="#d3e2ef" stroke="#526577"/>
<line x1="{sx(.02):.2f}" y1="169" x2="{sx(.02):.2f}" y2="248" stroke="#526577" stroke-width="2" stroke-dasharray="5 5"/>
<circle cx="{sx(.02):.2f}" cy="169" r="10" fill="#116b91"/>
<text x="30" y="148" font-size="21">CoM: x = 0.020 m</text>
<line x1="196" y1="169" x2="291" y2="169" stroke="#116b91" stroke-width="3"/>
<path d="M281 161 L293 169 L281 177" fill="none" stroke="#116b91" stroke-width="3"/>
<text x="307" y="177" font-size="22">v = +0.60 m/s</text>
<line x1="{sx(cp):.2f}" y1="221" x2="{sx(cp):.2f}" y2="273" stroke="#9b3b0d" stroke-width="3"/>
<circle cx="{sx(cp):.2f}" cy="258" r="7" fill="#9b3b0d"/>
<text x="{sx(cp)-20:.2f}" y="211" font-size="22" fill="#9b3b0d">Capture: +{cp:.3f} m</text>
<g font-size="20" text-anchor="middle">
<text x="70" y="294">−0.10</text><text x="160" y="294">0</text><text x="250" y="294">+0.10</text><text x="520" y="294">x (m)</text>
</g>
<text x="52" y="327" font-size="21">Current support</text>
<text x="30" y="364" font-size="22">Horizontal scale; height is schematic.</text>
<text x="30" y="414" font-size="23" font-weight="700">B. Waiting moves the capture point farther</text>
<text x="30" y="446" font-size="20">During the delay: ZMP fixed at p = 0</text>
<rect x="90" y="593" width="450" height="32" fill="#d3e2ef"/>
<g stroke="#becbd6" stroke-width="1">
<line x1="90" y1="497" x2="540" y2="497"/><line x1="90" y1="561" x2="540" y2="561"/>
</g>
<path d="M90 480 V625 H555" fill="none" stroke="#526577" stroke-width="2"/>
<polyline points="{curve}" fill="none" stroke="#9b3b0d" stroke-width="4"/>
<circle cx="90" cy="{625-320*cp:.2f}" r="6" fill="#9b3b0d"/>
<circle cx="540" cy="{625-320*r['delayed_capture_zmp_m']:.2f}" r="6" fill="#9b3b0d"/>
<g font-size="20" text-anchor="end"><text x="78" y="504">0.4</text><text x="78" y="568">0.2</text><text x="78" y="632">0</text></g>
<text x="30" y="477" font-size="20">m</text>
<text x="116" y="552" font-size="21">0.191 m</text>
<text x="426" y="486" font-size="21">0.385 m</text>
<text x="111" y="616" font-size="22">Forward support limit: +0.10 m</text>
<g font-size="20" text-anchor="middle"><text x="90" y="656">0</text><text x="315" y="656">100</text><text x="540" y="656">200 ms</text></g>
<text x="30" y="702" font-size="21" font-weight="700">A model calculation, not a footstep command.</text>
<text x="30" y="733" font-size="22">No swing, friction or actuator feasibility checks.</text>
</g></svg>'''.replace('font-size="20"', 'font-size="22"').replace('font-size="21"', 'font-size="22"')


def _rk4(x, velocity, zmp, seconds, height, steps=2000):
    """Independent numerical ODE integration used ONLY by the checks."""
    dt, a = seconds / steps, 9.81 / height
    def derivative(state):
        return state[1], a * (state[0] - zmp)
    def shifted(state, slope, scale):
        return tuple(v + scale * d for v, d in zip(state, slope))
    state = (x, velocity)
    for _ in range(steps):
        k1 = derivative(state)
        k2 = derivative(shifted(state, k1, dt / 2))
        k3 = derivative(shifted(state, k2, dt / 2))
        k4 = derivative(shifted(state, k3, dt))
        state = tuple(v + dt * (a1 + 2*a2 + 2*a3 + a4) / 6
                      for v, a1, a2, a3, a4 in zip(state, k1, k2, k3, k4))
    return state


class CapturePointChecks(unittest.TestCase):
    def test_published_numbers(self):
        r = example()
        self.assertAlmostEqual(r["instant_capture_zmp_m"], 0.19134117475124773, places=12)
        self.assertAlmostEqual(r["delayed_capture_zmp_m"], 0.38545141025720153, places=12)
        self.assertFalse(r["instant_capture_inside_current_support"])

    def test_delayed_solution_against_numerical_integration(self):
        exact = advance(.02, .6, 0, .2, .8)
        numeric = _rk4(.02, .6, 0, .2, .8)
        for a, b in zip(exact, numeric):
            self.assertAlmostEqual(a, b, places=11)

    def test_capture_removes_growing_mode(self):
        p = capture_point(.02, .6, .8)
        numeric_x, numeric_v = _rk4(.02, .6, p, 1.0, .8)
        self.assertAlmostEqual(numeric_v, .6 * math.exp(-frequency(.8)), places=10)
        self.assertAlmostEqual(numeric_x, p - numeric_v / frequency(.8), places=10)
        self.assertLess(abs(numeric_v), .02)

    def test_delayed_capture_relation(self):
        for p in (-.05, 0.0, .08):
            x, v = advance(.02, .6, p, .2, .8)
            expected = p + (capture_point(.02, .6, .8) - p) * math.exp(frequency(.8) * .2)
            self.assertAlmostEqual(capture_point(x, v, .8), expected, places=12)

    def test_zero_velocity_and_zero_delay(self):
        self.assertEqual(capture_point(.07, 0, .8), .07)
        self.assertEqual(advance(.07, 0, .07, 2, .8), (.07, 0))
        x, v = advance(.02, .6, .04, 0, .8)
        self.assertAlmostEqual(x, .02)
        self.assertAlmostEqual(v, .6)

    def test_support_boundary_and_velocity_direction(self):
        limit_speed = .10 * frequency(.8)
        self.assertAlmostEqual(capture_point(0, limit_speed, .8), .10)
        self.assertGreater(capture_point(0, limit_speed + .001, .8), .10)
        self.assertAlmostEqual(capture_point(-.02, -.6, .8), -capture_point(.02, .6, .8))

    def test_non_capture_fixed_support_diverges(self):
        x, v = _rk4(.02, .6, 0, 1, .8)
        self.assertGreater(x, 1)
        self.assertGreater(v, .6)

    def test_reject_invalid_inputs(self):
        for h in (0, -1, math.nan, math.inf):
            with self.assertRaises(ValueError):
                capture_point(0, 1, h)
        for x, v, p, t in ((math.nan, 0, 0, 0), (0, math.inf, 0, 0), (0, 0, 0, -1)):
            with self.assertRaises(ValueError):
                advance(x, v, p, t, .8)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--test", action="store_true", help="run eight executable model checks")
    parser.add_argument("--json", action="store_true", help="print unrounded scenario results")
    parser.add_argument("--svg", type=Path, help="write the article's original SVG figure")
    args = parser.parse_args()
    if args.test:
        result = unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(CapturePointChecks))
        raise SystemExit(0 if result.wasSuccessful() else 1)
    if args.svg:
        args.svg.write_text(figure_svg() + "\n", encoding="utf-8")
    r = example()
    if args.json:
        print(json.dumps(r, indent=2, allow_nan=False))
    else:
        print("Theoretical 1D LIPM example; no robot or controller validation.")
        for key in ("omega_s_inv", "instant_capture_zmp_m", "delayed_x_m", "delayed_velocity_m_s", "delayed_capture_zmp_m", "x_after_1s_with_instant_capture_m", "velocity_after_1s_with_instant_capture_m_s"):
            print(f"{key}: {r[key]:.9f}")


if __name__ == "__main__":
    main()
