# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "marimo",
#     "numpy",
#     "matplotlib",
# ]
# ///

import marimo

__generated_with = "0.26.0"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    import matplotlib.pyplot as plt
    import numpy as np

    return mo, np, plt


@app.cell
def _(mo):
    mo.md(r"""
    # Module 4.3: Mass, Center of Mass, and Inertia Tensors

    Here we build intuition for $I = m r^2$ and 3D inertia tensors: why moving a heavy actuator toward the wrist quadratically punishes your shoulder motor, and how a rigid link's inertia depends on which axis you spin it around.
    """)
    return


@app.cell
def _(np):
    def link_inertia_stats(motor_ratio=0.75, payload_kg=0.5, motor_kg=2.4, length_m=0.8, alpha_rad_s2=8.0):
        """Compute CoM, rotational inertia I = m_m r^2 + m_p L^2, and required torque."""
        r = motor_ratio * length_m
        i_motor = motor_kg * (r ** 2)
        i_payload = payload_kg * (length_m ** 2)
        i_total = i_motor + i_payload

        total_mass = motor_kg + payload_kg
        com_m = (motor_kg * r + payload_kg * length_m) / total_mass if total_mass > 0 else 0.0
        torque_nm = i_total * alpha_rad_s2
        return {
            "r": r,
            "i_motor": i_motor,
            "i_payload": i_payload,
            "i_total": i_total,
            "com_m": com_m,
            "torque_nm": torque_nm,
        }

    def box_inertia_tensor(mass_kg, lx, ly, lz):
        """Principal 3x3 inertia tensor of a solid uniform rectangular link."""
        ixx = (1.0 / 12.0) * mass_kg * (ly ** 2 + lz ** 2)
        iyy = (1.0 / 12.0) * mass_kg * (lx ** 2 + lz ** 2)
        izz = (1.0 / 12.0) * mass_kg * (lx ** 2 + ly ** 2)
        return np.diag([ixx, iyy, izz])

    return box_inertia_tensor, link_inertia_stats


@app.cell
def _(mo):
    ratio_ui = mo.ui.slider(0.05, 0.95, step=0.05, value=0.75, label="Motor placement (r / L)")
    payload_ui = mo.ui.slider(0.0, 4.0, step=0.2, value=0.5, label="Tip payload mass (kg)")
    alpha_ui = mo.ui.slider(1, 20, step=1, value=8, label="Target swing accel α (rad/s²)")

    mo.hstack([ratio_ui, payload_ui, alpha_ui], justify="start")
    return alpha_ui, payload_ui, ratio_ui


@app.cell
def _(alpha_ui, link_inertia_stats, mo, np, payload_ui, plt, ratio_ui):
    _ratios = np.linspace(0.05, 0.95, 50)
    _torques = [
        link_inertia_stats(_r, float(payload_ui.value), 2.4, 0.8, float(alpha_ui.value))["torque_nm"]
        for _r in _ratios
    ]
    _cur = link_inertia_stats(float(ratio_ui.value), float(payload_ui.value), 2.4, 0.8, float(alpha_ui.value))
    _base = link_inertia_stats(0.05, float(payload_ui.value), 2.4, 0.8, float(alpha_ui.value))

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(10.5, 3.8))

    # Left: schematic arm link
    _ax1.plot([0, 0.8], [0, 0], lw=6, color="#111827", solid_capstyle="round", label="Link (L = 0.8 m)")
    _ax1.scatter([_cur["r"]], [0], s=260, marker="s", color="#2563eb", zorder=5, label=f"Motor (2.4 kg @ {_cur['r']:.2f} m)")
    _ax1.scatter([0.8], [0], s=90 + 90 * float(payload_ui.value), color="#dc2626", zorder=5, label=f"Payload ({payload_ui.value:.1f} kg)")
    _ax1.scatter([_cur["com_m"]], [0], s=90, color="#16a34a", zorder=6, label=f"CoM ({_cur['com_m']:.2f} m)")
    _ax1.set_xlim(-0.1, 0.95)
    _ax1.set_ylim(-0.35, 0.35)
    _ax1.set_yticks([])
    _ax1.set_xlabel("Distance from Shoulder Pivot (m)")
    _ax1.set_title(f"I = {_cur['i_total']:.3f} kg·m²  |  τ = {_cur['torque_nm']:.2f} N·m ({_cur['torque_nm'] / _base['torque_nm']:.1f}× baseline)")
    _ax1.grid(True, axis="x", alpha=0.25)
    _ax1.legend(loc="upper left", fontsize=8)

    # Right: quadratic r^2 torque curve
    _ax2.plot(_ratios, _torques, lw=2.3, color="#2563eb")
    _ax2.scatter([float(ratio_ui.value)], [_cur["torque_nm"]], s=80, color="#dc2626", zorder=5)
    _ax2.set_xlabel("Actuator Placement Ratio (r / L)")
    _ax2.set_ylabel("Required Torque (N·m)")
    _ax2.set_title("Quadratic Penalty of Distal Mass (τ ∝ r²)")
    _ax2.grid(True, alpha=0.25)

    plt.tight_layout()
    mo.vstack([_fig])
    return


@app.cell
def _(mo):
    mo.md(r"""
    ## Try this on your own

    1. **3D inertia tensor of a forearm link:** Use `box_inertia_tensor(mass_kg=1.8, lx=0.6, ly=0.07, lz=0.07)` to compare spinning the link along its long X-axis (`Ixx`) vs. swinging it end-over-end (`Iyy`, `Izz`).
    2. **Double the link length:** Compute `link_inertia_stats` for `length_m=1.6` vs. `length_m=0.8` at `motor_ratio=0.75`. How much does required torque jump?
    """)
    return


@app.cell
def _(box_inertia_tensor, link_inertia_stats):
    # Exercise sandbox — edit and run!
    _I_box = box_inertia_tensor(mass_kg=1.8, lx=0.6, ly=0.07, lz=0.07)
    print("3x3 Forearm Inertia Tensor (kg·m²):\n", _I_box.round(5))
    print(f"End-over-end Izz / Roll Ixx ratio = {_I_box[2, 2] / _I_box[0, 0]:.1f}x")

    _short = link_inertia_stats(motor_ratio=0.75, payload_kg=0.5, length_m=0.8)
    _long = link_inertia_stats(motor_ratio=0.75, payload_kg=0.5, length_m=1.6)
    print(f"0.8 m arm torque: {_short['torque_nm']:.2f} N·m | 1.6 m arm torque: {_long['torque_nm']:.2f} N·m ({_long['torque_nm'] / _short['torque_nm']:.1f}x)")
    return


if __name__ == "__main__":
    app.run()
