Verification

Sizing reaction wheels to hold the structure still during spiral-outward assembly

Scope: Reaction wheel sizing for the spiral-outward assembly (one commit)

The spiral-outward assembly needs wheels that store up to 7.33 N m s and deliver up to 17.99 N m. The 20 tests pass. The extra checks I ran here also pass. The result holds only for the ideal, isolated model, and no hardware was checked.

What the code does

While the robot, gantry and tiles move, the whole assembly has zero total angular momentum. If nothing absorbs the robot's internal momentum, the structure turns. Reaction wheels fixed to the structure can absorb it. Then the structure stays still. This change adds the sizing code.

Module docstring states the momentum balance and the wheel equations.

h_w(t) = -h_rel(t)

Read the wheel sizing moduler3

How the sizing works

The pipeline has three code steps after the momentum table. build_table samples the scenario every 0.01 s and keeps every phase cut. It uses exact analytic rates, not finite differences, so a coarse sample cannot hide the peak torque. requirement takes the peaks. design_wheel turns a peak into a wheel.

The design rule is: design momentum =m⋅Hreq= m \cdot H_{req}, design torque =m⋅τreq= m \cdot \tau_{req}, wheel inertia =Hdesign/Ωmax= H_{design}/\Omega_{max}, and mass =I/(kr2)= I/(k r^2). Here mm is the margin and must be at least 1.

Flow from scenario to momentum table, then requirement, wheel design and attitude check.
The scenario is sampled once into a table. Requirement, design and closed-loop check all read that table. — Figure sourcer9

build_table and design_wheel in wheel_sizing.py.

H_design = margin * H_req;  I_w = H_design / Omega_max;

Read the cut middle of the sizing moduler5

What the spiral needs

I computed the requirement from the committed momentum table. It covers 31,953 samples over 309.1 s.

QuantityxyzNorm
Peak momentum (N m s)1.0911.1367.3287.332
Peak torque (N m)11.17911.64117.98517.994

Requirement and example design computed here from the committed table.

peak |tau| Nm 17.994 at t 283.3

Example z-axis design from design_wheel with default arguments.

'mass_kg': 1.7494

Compute the wheel requirement, an example design, and passive vs wheel attitude errorr8

Do the wheels hold the attitude?

simulate_attitude integrates the momentum balance with wheel control. I ran it without wheels and with wheels. The wheel run uses feedforward, a small PD loop, and torque and momentum limits set to 1.5 times the peaks.

Passive and wheel runs, as recorded here.

wheel peak err deg 0.0163 final 0.00025

Compute the wheel requirement, an example design, and passive vs wheel attitude errorr8

What the tests assert

All 20 tests in tests/test_wheel_sizing.py pass in 42 s. These are the ones that matter for sizing:

Full test run.

============================= 20 passed in 42.04s =============================

Run the wheel sizing test filer7

Checks

Material limits

Changed files
References
Scope and commits

Reaction wheel sizing for the spiral-outward assembly (one commit) · committed content

Head commit
5cefd4ed0c7d7b88a86470a478e22b1549240f2f

Scope resolutionr2

Exact command log · 11 records

Working tree before the walkthrough (taken by the tool, not the agent) — exit 0r0

Stdout

 M .DS_Store
 M backlog/.DS_Store
 M notebooks/zo25/01_angular_momentum_basics.ipynb
?? literature/~$lit_toolkit.xlsx

Exact command

git status --porcelain --untracked-files=all -- . ':(exclude).walkthrough'

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:22:18.088Z
Duration (ms)
50
Execution status
exit 0
Snapshot
before
Recorded tree snapshot
{
  ".DS_Store": "fb1a9d7cec7ec20d6c24534b985bd33b65ff787ab6384a3df4c8b4953e9519b1",
  "backlog/.DS_Store": "2606164498ffde2ebfb61f5f046c8023cf022462ef960db660289637caf2d2bc",
  "notebooks/zo25/01_angular_momentum_basics.ipynb": "8f045d7f7cf02a26e8f5a2c5283a722f17e64cc2ed1df95d4c647598767bd460",
  "literature/~$lit_toolkit.xlsx": "19e3923c4089f22600981bc0ad9384295acfefb15fa2838381fe2911efd9ed67",
  ".pi/": "directory",
  ".pytest_cache/": "directory",
  "Literature Review/": "directory",
  "Reaction Wheel/": "directory",
  "__pycache__/": "directory",
  "backlog/": "directory",
  "deliverables/": "directory",
  "literature/": "directory",
  "notebooks/": "directory",
  "outputs/": "directory",
  "tests/": "directory",
  "walkthrough/": "directory"
}
Inspect scope: repo state, recent commits, and files mentioning spiral and reaction wheel — exit 0r1

Stdout

/Users/mikek/Zig_ORLO*
 M .DS_Store
 M backlog/.DS_Store
 M notebooks/zo25/01_angular_momentum_basics.ipynb
?? literature/~$lit_toolkit.xlsx
3f58563 ZO-30.1-30.5: literature toolkit (Zotero + workbook), 74 verified seeds triaged, pull list and first-week queue, breadth search for S1-S4 (161 new papers, 332 logged queries)
be4411b Add pod clinic write-up and reaction wheel screenshot
6e6fb01 ZO-25: add wheel comparison PDF and its build script
8fdfae9 ZO-24: shorter animations (main and four-way about 27 s, close-up at 1.2x), regenerated media, manifests and report; update render-job test
af2cd86 ZO-30: literature review toolkit plan (doc-14 design, doc-15 session handoff) and tasks ZO-30.1-ZO-30.8
5cefd4e ZO-25: reaction wheel sizing, 5 teaching notebooks, flight-style controller and wheel comparison; record ZO-24 decision and Track 1/2 tasks (ZO-25..ZO-29)
bbfc67b ZO-24.6: shareable report, slides and HTML; one independent review; layout fixes
7bb7dd4 ZO-24.5: technical decision package (ledger-token template, builder/checker, tests)
./wheel_control.py
./literature/search/cache/afb8e77866859b567556caaf640764d2.txt
./literature/search/cache/54ddd86bdec5fc18864ac0c29165f08d.txt
./literature/search/cache/1c2a08b41d9df7d606cc707979d5593c.txt
./literature/search/cache/6877bfc6562adfc4fbef902d5b18cb66.txt
./literature/search/cache/d83eec80bd6d0f90366714c5d0fd2d7e.txt
./literature/search/cache/a878527f741b3d1640771380cb5750cf.txt
./literature/search/cache/74f12aa6e4b03a5593f561830eb1dac8.txt
./literature/search/cache/5f754c220b3db75181d59d792c02542b.txt
./literature/search/raw/S3/q04.json
./literature/search/raw/S3/q06.json
./literature/search/raw/S1/nt20.json
./literature/search/raw/S1/refs_schenk.json
./literature/search/raw/S1/oa10.json
./literature/seeds/cache/bdd2573c85e23668de906261d809d7e0.json
./literature/seeds/cache/269c5511e2cc73b2c8a3e178746c4210.json
./literature/seeds/cache/10592fb29b89038e0362a734c2386104.json
./literature/seeds/cache/445770afc9e208da361a7c5465a60515.json
./literature/seeds/cache/a373e94452431e21561c895f0a1c9a8c.json
./literature/seeds/cache/620a5a2646f27f59b18c6d3ac7902c56.json
./render_strategy.py
./.pytest_cache/v/cache/nodeids
./backlog/tasks/zo-24.6 - Write-the-shareable-report-for-a-professor-and-labmates-with-one-independent-review.md
./backlog/tasks/zo-24.3 - Render-high-quality-assembly-animations-and-stills-for-the-strategies.md
./backlog/tasks/zo-24.4 - Produce-comparison-graphs-for-the-key-results.md
./backlog/tasks/zo-19 - Build-a-reproducible-candidate-library-for-alternative-assembly-strategies.md
./backlog/tasks/zo-23 - Stress-test-shortlisted-strategies-and-identify-missing-physical-validation.md
./backlog/tasks/zo-24.2 - Build-a-strategy-agnostic-assembly-renderer-from-saved-momentum-histories.md
./backlog/tasks/zo-21 - Compare-baseline-and-alternative-layout-families-under-matched-assumptions.md
./backlog/tasks/zo-24 - Present-assembly-strategy-tradeoffs-and-choose-the-next-validation-experiment.md
./wheel_control.py
./literature/tools/lit_tool.py
./literature/search/zo305_graph.json
./literature/search/candidates_S3.json
./literature/search/candidates_S2.json
./literature/search/cache/f7b31172a98505f9e148bd0acf2975ce.txt
./literature/search/cache/42a90697e5bc33d823eed1a4dd2f6762.txt
./literature/search/cache/66823301834f6cdeacbbdf23531d8906.txt
./literature/search/cache/b131cd6e058cb538d30cd65514fa5207.txt
./literature/search/cache/48e5046f97c222073c5a95a5ceae1a48.txt
./literature/search/cache/d6cac58f388829624f3b8305a8f3c7f1.txt
./literature/search/cache/56dc6d55bc1b5e98e6c791cf4fdc172e.txt
./literature/search/cache/a4c735241c5f301e137c13537cfe9225.txt
./literature/search/cache/7467543bda48cd2b2665acf4ae3f878d.txt
./literature/search/cache/6acb3325c8b1b06e3004f58bee8a83c5.txt
./literature/search/cache/7de12a3a59d8e19d7f7b88f385dbefaf.txt
./literature/search/cache/8414ec5d54dfad942d6c01da8200ae6b.txt
./literature/search/cache/597e3da5fa0ef9a7e1b25cf77071761f.txt
./literature/search/cache/c12d7df1f932967af4ff54b33dbe513e.txt
./literature/search/cache/766005fc17a77c937ce449cddcdcf633.txt

Exact command

cd "/Users/mikek/Zig_ORLO*" 2>/dev/null || true; pwd; git status --short | head; git log --oneline -8; grep -rIil "spiral" --exclude-dir=.git --exclude-dir=node_modules --exclude-dir=zig-cache --exclude-dir=.zig-cache . | head -30; grep -rIil "reaction.wheel" --exclude-dir=.git --exclude-dir=.zig-cache . | head -20

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:22:18.088Z
Duration (ms)
3389
Execution status
exit 0
See files in the wheel-sizing commit — exit 0r2

Stdout

5cefd4ed0c7d7b88a86470a478e22b1549240f2f ZO-25: reaction wheel sizing, 5 teaching notebooks, flight-style controller and wheel comparison; record ZO-24 decision and Track 1/2 tasks (ZO-25..ZO-29)

 ...nshot 2026-10-25 at 10.47.51\342\200\257PM.png" | Bin 0 -> 1028639 bytes
 ...nshot 2026-10-25 at 10.48.02\342\200\257PM.png" | Bin 0 -> 89962 bytes
 ...nshot 2026-10-25 at 10.48.17\342\200\257PM.png" | Bin 0 -> 222239 bytes
 ...nshot 2026-10-25 at 10.48.27\342\200\257PM.png" | Bin 0 -> 59964 bytes
 ...-path-enumeration-on-MIT-ORCD-Engaging-after.md |  19 +
 ...ord-ZO-24-user-decision-and-research-roadmap.md |  38 ++
 ...production-instructions-and-track-follow-ups.md |   8 +-
 ...ral-outward-assembly-with-teaching-notebooks.md |  64 ++
 ...l-each-other-attitude-change-during-assembly.md |  36 ++
 ...built-state-and-complete-the-10x10-structure.md |  34 +
 ...hs-under-the-tile-rules-on-MIT-ORCD-Engaging.md |  38 ++
 ...s-and-a-tested-job-workflow-for-this-project.md |  32 +
 notebooks/zo25/01_angular_momentum_basics.ipynb    | 258 ++++++++
 notebooks/zo25/02_wheel_needs_from_spiral.ipynb    | 228 +++++++
 notebooks/zo25/03_wheel_design_and_margin.ipynb    | 266 ++++++++
 notebooks/zo25/04_closed_loop_check.ipynb          | 189 ++++++
 .../05_flight_controller_and_wheel_choice.ipynb    | 426 +++++++++++++
 notebooks/zo25/README.md                           |  39 ++
 notebooks/zo25/build_notebooks.py                  | 681 +++++++++++++++++++++
 .../zo25/data/spiral_outward_internal_momentum.npz | Bin 0 -> 1997401 bytes
 notebooks/zo25/data/spiral_outward_rest_times.npy  | Bin 0 -> 4232 bytes
 notebooks/zo25/nb_check.py                         |  72 +++
 requirements-notebooks.txt                         |  10 +
 tests/test_wheel_sizing.py                         | 180 ++++++
 wheel_control.py                                   | 285 +++++++++
 wheel_sizing.py                                    | 299 +++++++++
 26 files changed, 3201 insertions(+), 1 deletion(-)
6e6fb01e06bc288ae3e3a8c82c3a91ca33b88bb6 ZO-25: add wheel comparison PDF and its build script

 deliverables/zo25/make_wheel_comparison_pdf.py | 203 +++++++++++++++++++++++++
 deliverables/zo25/wheel_comparison.pdf         | Bin 0 -> 1226844 bytes
 2 files changed, 203 insertions(+)
__pycache__
AGENTS.md
animation.py
assembly_candidate.py
assembly_sequence.py
backlog
candidate_library.py
compare_strategies.py
deliverables
evaluate_strategy.py
evaluation_checks.py
export_assumptions.py
forward_assembly.py
gantry.py
Left Tile.png
literature
Literature Review
momentum_core.py
motion_planner.py
notebooks
ORLO Zig.xlsx
outputs
params.py
placement.py
publish_strategy_search.py
rail_kinematics.py
Reaction Wheel
README.md
render_forward.py
render_strategy.py
reporting.py
requirements-notebooks.txt
Right Tile.png
scenario_a1.py
scenario_a2.py
scenario_motion.py
search_evaluation_io.py
search_strategies.py
snake_path.py
Straight Tile.png
strategy_metrics.py
tests
validation.py
verify_assembly_sequence.py
verify_forward_outputs.py
walkthrough
wheel_control.py
wheel_sizing.py
zo23_analyze_results.py
zo23_parity_check.py
zo23_run_driver.py
     285 wheel_control.py
__pycache__
test_animation.py
test_assembly_candidate.py
test_assembly_sequence.py
test_candidate_library.py
test_compare_strategies.py
test_core_regressions.py
test_evaluate_strategy.py
test_evaluation_checks.py
test_forward_assembly.py
test_gantry.py
test_internal_motion_integration.py
test_mass_override.py
test_momentum_core.py
test_motion_planner.py
test_params.py
test_placement.py
test_publish_strategy_search.py
test_rail_kinematics.py
test_render_forward.py
test_reporting.py
test_scenario_a1.py
test_scenario_a2.py
test_search_evaluation_io.py
test_search_strategies.py
test_snake_path.py
test_strategy_limits.py
test_strategy_metrics.py
test_validation.py
test_wheel_sizing.py

Exact command

git show --stat --format='%H %s' 5cefd4e | head -40; git show --stat --format='%H %s' 6e6fb01 | head; ls; wc -l wheel_control.py; ls tests | head -30

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:22:24.079Z
Duration (ms)
74
Execution status
exit 0
Read the wheel sizing module — exit 0 · truncated outputr3

Stdout

Truncated: 4885 bytes omitted from stdout. This is not the complete output.

"""Reaction-wheel sizing for holding structure attitude during assembly (ZO-25).

Physics (same frame and identity as momentum_core / doc-3)
-----------------------------------------------------------
B is the structure frame. The robot, gantry and tiles move relative to B with
a prescribed motion. Their *internal* (relative) angular momentum about the
system centre of mass, expressed in B, is ``h_rel(t)`` (momentum_core
``MassProperties.relative_momentum_B``). With no external torque and zero
initial momentum, the total angular momentum stays zero:

    J(t) @ omega + h_rel(t) + h_w = 0                         (1)

``J`` is the locked inertia of the whole system about its centre of mass,
``omega`` is the structure angular velocity and ``h_w`` is the momentum stored
in reaction wheels that are fixed in B (one wheel per body axis). Without a
wheel, omega = -J^-1 h_rel and the structure turns. To hold omega = 0 exactly,
the wheels must store

    h_w(t) = -h_rel(t)                                         (2)

and the wheel motors must apply (wheel axes are fixed in B, so B components of
h_w change only through motor torque)

    tau_motor(t) = dh_w/dt = -dh_rel/dt.                       (3)

The reaction torque on the structure is -tau_motor. Because h_rel returns to
zero when the robot stops, the wheels end at zero speed: no momentum dumping
is needed in this isolated model.

Assumptions (state them with any number from this module)
- Rigid, isolated, prescribed-motion model; no gravity gradient, drag or
  external torque. Physical hardware feasibility is not checked.
- The wheel mass and inertia are not added to J and do not move the CoM. The
  wheel is small next to the 50 kg structure; the notebooks show the size of
  this error.
- Three orthogonal wheels aligned with B. Other layouts (pyramid, 4-wheel)
  are not modelled.
"""
from __future__ import annotations

import math
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Callable, Sequence

import numpy as np
from scipy.spatial.transform import Rotation

ROOT = Path(__file__).resolve().parent
DEFAULT_TABLE = ROOT / "notebooks" / "zo25" / "data" / "spiral_outward_internal_momentum.npz"
RETAINED_HISTORY = ROOT / "outputs" / "zo21_spiral_outward" / "nominal" / "momentum_history.npz"
RPM = 2 * math.pi / 60.0


# --------------------------------------------------------------- the table
@dataclass(frozen=True)
class MomentumTable:
    """Internal-momentum history on a dense grid, in body frame B.

    time [s], h_rel [N m s] (n,3), h_rel_dot [N m] (n,3) analytic,
    inertia [kg m^2] (n,3,3) locked system inertia about the CoM.
    """
    time: np.ndarray
    h_rel: np.ndarray
    h_rel_dot: np.ndarray
    inertia: np.ndarray
    case_id: str = "spiral-outward"

    def interp(self, t: float):
        """Linear interpolation of (h_rel, h_rel_dot, J) at time t (clamped)."""
        t = float(np.clip(t, self.time[0], self.time[-1]))
        k = int(np.clip(np.searchsorted(self.time, t) - 1, 0, len(self.time) - 2))
        t0, t1 = self.time[k], self.time[k + 1]
        a = 0.0 if t1 == t0 else (t - t0) / (t1 - t0)
        lerp = lambda x: (1 - a) * x[k] + a * x[k + 1]
        return lerp(self.h_rel), lerp(self.h_rel_dot), lerp(self.inertia)

    def save(self, path: str | Path = DEFAULT_TABLE) -> Path:
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        np.savez_compressed(path, time=self.time, h_rel=self.h_rel, h_rel_dot=self.h_rel_dot,
                            inertia=self.inertia, case_id=self.case_id)
        return path


def load_table(path: str | Path = DEFAULT_TABLE) -> MomentumTable:
    d = np.load(path)
    return MomentumTable(d["time"], d["h_rel"], d["h_rel_dot"], d["inertia"], str(d["case_id"]))


def build_table(case_id: str = "spiral-outward", dt: float = 0.01) -> MomentumTable:
    """Evaluate the prescribed scenario on a dense grid that keeps every phase cut.

    Uses the exact analytic h_rel and dh_rel/dt from momentum_core (no
    finite differences), so peak torque is not limit
[... 4885 bytes cut by walkthrough_record ...]
i], req.peak_torque_axis_Nm[i], axis=a, **kw)
            for i, a in enumerate("xyz")]


# ------------------------------------------------------- closed-loop check
@dataclass
class ControlledRun:
    time: np.ndarray
    q_IB: np.ndarray            # structure attitude (x, y, z, w)
    omega: np.ndarray           # rad/s in B
    h_w: np.ndarray             # wheel momentum in B
    tau: np.ndarray             # motor torque in B (dh_w/dt)
    attitude_error_deg: np.ndarray

    @property
    def peak_error_deg(self) -> float:
        return float(self.attitude_error_deg.max())

    @property
    def final_error_deg(self) -> float:
        return float(self.attitude_error_deg[-1])


def simulate_attitude(table: MomentumTable, *, feedforward: float = 1.0, kp: float = 0.0, kd: float = 0.0,
                      torque_limit: Sequence[float] | float | None = None,
                      momentum_limit: Sequence[float] | float | None = None,
                      wheels: bool = True, dt: float | None = None) -> ControlledRun:
    """Integrate equation (1) with wheel control on the table grid.

    Wheel momentum h_w is the state. omega is algebraic: omega = -J^-1 (h_rel + h_w).
    Motor command  u = -feedforward * dh_rel/dt + J (kp * e + kd * omega),
    with e the attitude error rotation vector (B frame, small-angle PD). Torque
    and momentum limits saturate per axis. wheels=False gives the passive
    (no-wheel) structure motion. Fixed-step RK2 (midpoint) on the table grid,
    or on a uniform grid of step dt.
    """
    t = table.time if dt is None else np.arange(table.time[0], table.time[-1] + dt / 2, dt)
    n = len(t)
    tl = None if torque_limit is None else np.broadcast_to(np.asarray(torque_limit, float), (3,))
    hl = None if momentum_limit is None else np.broadcast_to(np.asarray(momentum_limit, float), (3,))
    q = np.empty((n, 4)); w = np.empty((n, 3)); hw = np.zeros((n, 3)); tau = np.zeros((n, 3))
    q[0] = (0, 0, 0, 1)

    def rates(tk, qk, hwk):
        h, hd, J = table.interp(tk)
        if not wheels:
            return -np.linalg.solve(J, h), np.zeros(3)
        omega = -np.linalg.solve(J, h + hwk)
        e = Rotation.from_quat(qk).as_rotvec()          # B->I rotation; hold identity
        e_B = Rotation.from_quat(qk).inv().apply(e)
        u = -feedforward * hd + J @ (kp * e_B + kd * omega)
        if tl is not None:
            u = np.clip(u, -tl, tl)
        if hl is not None:                               # no torque further into saturation
            u = np.where((np.abs(hwk) >= hl) & (np.sign(u) == np.sign(hwk)), 0.0, u)
        return omega, u

    def qstep(qk, omega, h):
        return (Rotation.from_quat(qk) * Rotation.from_rotvec(omega * h)).as_quat()

    for k in range(n - 1):
        h = t[k + 1] - t[k]
        w0, u0 = rates(t[k], q[k], hw[k])
        w[k], tau[k] = w0, u0
        qm = qstep(q[k], w0, h / 2)
        hm = hw[k] + u0 * h / 2
        if hl is not None:
            hm = np.clip(hm, -hl, hl)
        wm, um = rates(t[k] + h / 2, qm, hm)
        q[k + 1] = qstep(q[k], wm, h)
        hw[k + 1] = hw[k] + um * h
        if hl is not None:
            hw[k + 1] = np.clip(hw[k + 1], -hl, hl)
    w[-1], tau[-1] = rates(t[-1], q[-1], hw[-1])
    err = np.degrees(Rotation.from_quat(q).magnitude())
    return ControlledRun(t, q, w, hw, tau, err)


def wheel_inertia_error(design_mass_kg: float, offset_m: float, inertia_min_kgm2: float) -> float:
    """Fractional change of the smallest system inertia if a wheel of this mass
    sits offset_m from the CoM (parallel-axis upper estimate of the neglected term)."""
    return design_mass_kg * offset_m**2 / inertia_min_kgm2


def main() -> None:  # regenerate the committed table
    import argparse
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--dt", type=float, default=0.01)
    ap.add_argument("--out", default=str(DEFAULT_TABLE))
    a = ap.parse_args()
    table = build_table(dt=a.dt)
    print(table.save(a.out), len(table.time), requirement(table))


if __name__ == "__main__":
    main()

Exact command

cat wheel_sizing.py

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:22:26.668Z
Duration (ms)
10
Execution status
exit 0
Read the notebook README and the sizing tests — exit 0r4

Stdout

# ZO-25: Reaction-wheel sizing notebooks

Five Jupyter notebooks that teach, step by step, how to size reaction wheels
that hold the structure attitude during the spiral-outward assembly.

| Notebook | What you learn |
|---|---|
| `01_angular_momentum_basics.ipynb` | Conservation of angular momentum with a toy plate and arm; what a wheel does |
| `02_wheel_needs_from_spiral.ipynb` | Momentum and torque the wheels need, from the real spiral simulation |
| `03_wheel_design_and_margin.ipynb` | Wheel inertia, speed, mass, motor torque and power, with margin |
| `04_closed_loop_check.ipynb` | Simulate the wheels holding attitude; motor limits; feedforward vs feedback |
| `05_flight_controller_and_wheel_choice.ipynb` | Flight-style controller (sensors, estimator, robot progress, limits); real flown wheels compared by assembly time |

## Set up and start

```bash
cd "/Users/mikek/Zig_ORLO*"
python3 -m pip install -r requirements-notebooks.txt
cd notebooks/zo25
python3 -m jupyter lab
```

Open the notebooks in order. Each exercise has a variable set to `None`.
Put in your answer and run the cell; `check(...)` tells you if it is right.
The worked answer is in a closed "Worked answer" block under each exercise.

To start over with clean outputs: in JupyterLab, use *Kernel > Restart Kernel and Clear Outputs*.

## Files

- `data/spiral_outward_internal_momentum.npz`: internal momentum `h_rel`, its exact rate and the
  system inertia every 0.01 s. Regenerate with `python3 wheel_sizing.py` from the repo root (about 1 minute).
- `nb_check.py`: answer checks.
- `build_notebooks.py`: the source of the notebook text. Edit it, then run `python3 build_notebooks.py`.
- `data/spiral_outward_rest_times.npy`: times when every part is at rest (move boundaries). Regenerate with `python3 wheel_control.py`.
- Library: `wheel_sizing.py` and `wheel_control.py` (repo root; wheel catalogue with datasheet sources, retiming, flight controller). Tests: `tests/test_wheel_sizing.py` (runs every notebook).

Notebook 2 and the passive check in Notebook 4 also read the Git-ignored ZO-21 history
`outputs/zo21_spiral_outward/nominal/momentum_history.npz` to compare with ZO-23.
"""ZO-25: reaction-wheel sizing library and teaching notebooks."""
import math
import sys
from pathlib import Path

import numpy as np
import pytest
from scipy.spatial.transform import Rotation as R

import wheel_sizing as ws

ROOT = Path(__file__).resolve().parents[1]
NB_DIR = ROOT / "notebooks" / "zo25"
sys.path.insert(0, str(NB_DIR))


@pytest.fixture(scope="module")
def table():
    return ws.load_table()


def test_table_matches_live_scenario(table):
    import momentum_core as mc
    from assembly_sequence import build_generalized_scenario
    from candidate_library import library_cases
    spec = next(c for c in library_cases() if c.case_id == "spiral-outward")
    sc = build_generalized_scenario(spec.candidate())
    for k in (0, 5000, 20000, len(table.time) - 1):
        p = mc.mass_properties(tuple(sc.configuration(float(table.time[k]))))
        np.testing.assert_allclose(p.relative_momentum_B, table.h_rel[k], atol=1e-12)
        np.testing.assert_allclose(p.relative_momentum_dot_B, table.h_rel_dot[k], atol=1e-10)


def test_requirement_matches_zo23(table):
    req = ws.requirement(table)
    assert req.peak_momentum_norm_Nms == pytest.approx(7.33, abs=0.01)       # ZO-23 hold momentum
    assert req.peak_torque_norm_Nm >= 17.81                                   # ZO-23 sampled lower bound
    assert req.sample_dt_max_s <= 0.0101
    assert np.allclose(req.final_momentum_Nms, 0, atol=1e-9)                  # no dumping needed


def test_analytic_rate_consistent_with_finite_difference(table):
    fd = np.gradient(table.h_rel, table.time, axis=0)
    # away from phase cuts the analytic and finite-difference rates agree
    assert np.median(np.abs(fd - table.h_rel_dot)) < 1e-3


def test_design_wheel_formulas():
    d = ws.design_wheel(2.0, 1.0, margin=1.5, max_speed_rpm=3000, radius_m=0.2, shape_factor=0.5)
    omega = 3000 * 2 * math.pi / 60
    assert d.inertia_kgm2 == pytest.approx(3.0 / omega)
    assert d.mass_kg == pytest.approx(3.0 / omega / (0.5 * 0.04))
    assert d.design_torque_Nm == pytest.approx(1.5)
    assert d.peak_power_W == pytest.approx(1.5 * omega)
    with pytest.raises(ValueError):
        ws.design_wheel(1, 1, margin=0.9)


def test_passive_sim_reproduces_full_model(table):
    if not ws.RETAINED_HISTORY.exists():
        pytest.skip("retained ZO-21 history is Git-ignored and not present")
    p = ws.simulate_attitude(table, wheels=False)
    q_ref = ws.requirement_from_history()["q_IB"][-1]
    diff = np.degrees((R.from_quat(p.q_IB[-1]).inv() * R.from_quat(q_ref)).magnitude())
    assert diff < 0.01
    assert p.peak_error_deg > 170


def test_wheel_holds_attitude(table):
    req = ws.requirement(table)
    run = ws.simulate_attitude(table, kp=0.04, kd=0.4,
                               torque_limit=1.5 * np.array(req.peak_torque_axis_Nm),
                               momentum_limit=1.5 * np.array(req.peak_momentum_axis_Nms))
    assert run.peak_error_deg < 0.05
    assert run.final_error_deg < 0.01
    # total momentum J w + h_rel + h_w stays zero
    tot = np.einsum("tij,tj->ti", table.inertia, run.omega) + table.h_rel + run.h_w
    assert np.abs(tot).max() < 1e-9


Exact command

cat notebooks/zo25/README.md; sed -n 1,80p tests/test_wheel_sizing.py

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:22:26.679Z
Duration (ms)
11
Execution status
exit 0
Read the cut middle of the sizing module — exit 0r5

Stdout

    finite differences), so peak torque is not limited by the sampling of a
    saved history. Takes about 2 minutes for the spiral at dt = 0.01 s.
    """
    import momentum_core as mc
    from assembly_sequence import build_generalized_scenario
    from candidate_library import library_cases

    spec = next(c for c in library_cases() if c.case_id == case_id)
    scenario = build_generalized_scenario(spec.candidate())
    cuts = np.unique(np.r_[0.0, scenario.duration_s, scenario.breakpoints,
                           [x for e in scenario.events for x in (e.start_time, e.end_time, *e.breakpoints)]])
    cuts = cuts[(cuts >= 0) & (cuts <= scenario.duration_s)]
    parts = []
    for a, b in zip(cuts[:-1], cuts[1:]):
        n = max(2, math.ceil((b - a) / dt))
        # Sample just inside each phase so one-sided values at cuts are kept.
        eps = min(1e-9, (b - a) * 1e-6)
        parts.append(np.linspace(a + eps, b - eps, n + 1))
    times = np.concatenate(parts)
    h, hd, J = (np.empty((len(times), 3)), np.empty((len(times), 3)), np.empty((len(times), 3, 3)))
    for k, t in enumerate(times):
        p = mc.mass_properties(tuple(scenario.configuration(float(t))))
        h[k], hd[k], J[k] = p.relative_momentum_B, p.relative_momentum_dot_B, p.inertia_B
    return MomentumTable(times, h, hd, J, case_id)


# ------------------------------------------------------------ requirements
@dataclass(frozen=True)
class WheelRequirement:
    """What the wheels must do to hold omega = 0 (equations 2 and 3)."""
    peak_momentum_axis_Nms: tuple      # max |h_w| per body axis x, y, z
    peak_momentum_norm_Nms: float      # max |h_w| (vector)
    t_peak_momentum_s: float
    peak_torque_axis_Nm: tuple         # max |tau| per axis
    peak_torque_norm_Nm: float
    t_peak_torque_s: float
    final_momentum_Nms: tuple          # should be ~0: no dumping needed
    sample_dt_max_s: float

    def as_dict(self):
        return asdict(self)


def requirement(table: MomentumTable) -> WheelRequirement:
    hw = -table.h_rel
    tau = -table.h_rel_dot
    hn, tn = np.linalg.norm(hw, axis=1), np.linalg.norm(tau, axis=1)
    return WheelRequirement(
        tuple(float(x) for x in np.abs(hw).max(0)), float(hn.max()), float(table.time[hn.argmax()]),
        tuple(float(x) for x in np.abs(tau).max(0)), float(tn.max()), float(table.time[tn.argmax()]),
        tuple(float(x) for x in hw[-1]), float(np.diff(table.time).max()))


def requirement_from_history(path: str | Path = RETAINED_HISTORY) -> dict:
    """ZO-23 method: h = J omega from a saved history, torque by np.gradient.

    Gives a *sampled* torque, which is a lower bound on the true peak.
    """
    d = np.load(path)
    t, J, w = d["time"], d["inertia_B"], d["omega_B"]
    h = np.einsum("tij,tj->ti", J, w)       # = -h_rel = wheel momentum needed
    dh = np.gradient(h, t, axis=0)
    return {"peak_momentum_norm_Nms": float(np.linalg.norm(h, axis=1).max()),
            "peak_torque_norm_Nm_sampled": float(np.linalg.norm(dh, axis=1).max()),
            "peak_momentum_axis_Nms": tuple(float(x) for x in np.abs(h).max(0)),
            "peak_torque_axis_Nm_sampled": tuple(float(x) for x in np.abs(dh).max(0)),
            "time": t, "wheel_momentum": h, "q_IB": d["q_IB"]}


# ------------------------------------------------------------------ design
@dataclass(frozen=True)
class WheelDesign:
    """One wheel. Rim model: I = k * m * r^2 (k = 1 thin rim, 0.5 solid disc)."""
    axis: str
    required_momentum_Nms: float
    required_torque_Nm: float
    margin: float
    max_speed_rpm: float
    design_momentum_Nms: float
    inertia_kgm2: float
    design_torque_Nm: float
    radius_m: float
    shape_factor: float
    mass_kg: float
    peak_power_W: float               # design torque * max speed (motor sizing bound)

    def as_dict(self):
        return asdict(self)


def design_wheel(required_momentum: float, required_torque: float, *, axis: str = "z",
                 margin: float = 1.5, max_speed_rpm: float = 6000.0, radius_m: float = 0.10,
                 shape_factor: float = 1.0) -> WheelDesign:
    """Size one wheel from momentum and torque needs.

    H_design = margin * H_req;  I_w = H_design / Omega_max;
    tau_design = margin * tau_req;  m = I_w / (k r^2);  P = tau_design * Omega_max.
    """
    if margin < 1 or max_speed_rpm <= 0 or radius_m <= 0 or not 0 < shape_factor <= 1:
        raise ValueError("need margin >= 1, positive speed and radius, 0 < shape_factor <= 1")
    omega = max_speed_rpm * RPM
    H = margin * required_momentum
    I = H / omega
    tau = margin * required_torque
    return WheelDesign(axis, required_momentum, required_torque, margin, max_speed_rpm, H, I, tau,
                       radius_m, shape_factor, I / (shape_factor * radius_m**2), tau * omega)

Exact command

sed -n 95,200p wheel_sizing.py

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:22:30.529Z
Duration (ms)
7
Execution status
exit 0
Run the wheel sizing test file — exit 127r6

Stdout

bash: timeout: command not found

Exact command

timeout 110 python3 -m pytest tests/test_wheel_sizing.py -q -p no:cacheprovider --durations=5 2>&1 | tail -25

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:22:30.538Z
Duration (ms)
6
Execution status
exit 127
Run the wheel sizing test file — exit 0r7

Stdout

collecting ... collected 20 items

tests/test_wheel_sizing.py::test_table_matches_live_scenario PASSED      [  5%]
tests/test_wheel_sizing.py::test_requirement_matches_zo23 PASSED         [ 10%]
tests/test_wheel_sizing.py::test_analytic_rate_consistent_with_finite_difference PASSED [ 15%]
tests/test_wheel_sizing.py::test_design_wheel_formulas PASSED            [ 20%]
tests/test_wheel_sizing.py::test_passive_sim_reproduces_full_model PASSED [ 25%]
tests/test_wheel_sizing.py::test_wheel_holds_attitude PASSED             [ 30%]
tests/test_wheel_sizing.py::test_answer_keys_accept_worked_answers PASSED [ 35%]
tests/test_wheel_sizing.py::test_notebook_runs_clean[01_angular_momentum_basics.ipynb] PASSED [ 40%]
tests/test_wheel_sizing.py::test_notebook_runs_clean[02_wheel_needs_from_spiral.ipynb] PASSED [ 45%]
tests/test_wheel_sizing.py::test_notebook_runs_clean[03_wheel_design_and_margin.ipynb] PASSED [ 50%]
tests/test_wheel_sizing.py::test_notebook_runs_clean[04_closed_loop_check.ipynb] PASSED [ 55%]
tests/test_wheel_sizing.py::test_notebook_runs_clean[05_flight_controller_and_wheel_choice.ipynb] PASSED [ 60%]
tests/test_wheel_sizing.py::test_four_notebooks_present PASSED           [ 65%]
tests/test_wheel_sizing.py::test_rest_times_are_true_rest_states PASSED  [ 70%]
tests/test_wheel_sizing.py::test_retime_respects_wheel_limits PASSED     [ 75%]
tests/test_wheel_sizing.py::test_retime_preserves_attitude_path PASSED   [ 80%]
tests/test_wheel_sizing.py::test_assembly_time_comparison PASSED         [ 85%]
tests/test_wheel_sizing.py::test_flight_controller_holds_attitude_with_noise_and_timing_error PASSED [ 90%]
tests/test_wheel_sizing.py::test_quaternion_helpers_match_scipy PASSED   [ 95%]
tests/test_wheel_sizing.py::test_notebook5_answer_keys PASSED            [100%]

============================= slowest 5 durations ==============================
19.84s call     tests/test_wheel_sizing.py::test_notebook_runs_clean[04_closed_loop_check.ipynb]
5.44s call     tests/test_wheel_sizing.py::test_notebook_runs_clean[05_flight_controller_and_wheel_choice.ipynb]
3.87s call     tests/test_wheel_sizing.py::test_flight_controller_holds_attitude_with_noise_and_timing_error
2.89s call     tests/test_wheel_sizing.py::test_retime_preserves_attitude_path
2.62s call     tests/test_wheel_sizing.py::test_wheel_holds_attitude
============================= 20 passed in 42.04s ==============================

Exact command

python3 -m pytest tests/test_wheel_sizing.py -v -p no:cacheprovider --durations=5 2>&1 | tail -30

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:22:34.203Z
Duration (ms)
42628
Execution status
exit 0
Compute the wheel requirement, an example design, and passive vs wheel attitude error — exit 0r8

Stdout

case spiral-outward samples 31953 duration_s 309.0885783182188
peak |h| Nms 7.332 at t 283.0
peak |h| axis [1.091, 1.136, 7.328]
peak |tau| Nm 17.994 at t 283.3
peak |tau| axis [11.179, 11.641, 17.985]
final h [-0.0, 2.16e-18, 4.32e-17] max dt 0.009999999966680662
design z default: {'axis': 'z', 'required_momentum_Nms': 7.328, 'required_torque_Nm': 17.9853, 'margin': 1.5, 'max_speed_rpm': 6000.0, 'design_momentum_Nms': 10.992, 'inertia_kgm2': 0.0175, 'design_torque_Nm': 26.978, 'radius_m': 0.1, 'shape_factor': 1.0, 'mass_kg': 1.7494, 'peak_power_W': 16950.7543}
passive peak err deg 180.0
wheel peak err deg 0.0163 final 0.00025

Exact command

python3 - <<'EOF'
import wheel_sizing as ws, numpy as np
t=ws.load_table(); r=ws.requirement(t)
print("case",t.case_id,"samples",len(t.time),"duration_s",t.time[-1])
print("peak |h| Nms",round(r.peak_momentum_norm_Nms,3),"at t",round(r.t_peak_momentum_s,1))
print("peak |h| axis",[round(x,3) for x in r.peak_momentum_axis_Nms])
print("peak |tau| Nm",round(r.peak_torque_norm_Nm,3),"at t",round(r.t_peak_torque_s,1))
print("peak |tau| axis",[round(x,3) for x in r.peak_torque_axis_Nm])
print("final h",[float(f"{x:.2e}") for x in r.final_momentum_Nms],"max dt",r.sample_dt_max_s)
d=ws.design_wheel(r.peak_momentum_axis_Nms[2],r.peak_torque_axis_Nm[2],axis="z")
print("design z default:",{k:round(v,4) if isinstance(v,float) else v for k,v in d.as_dict().items()})
p=ws.simulate_attitude(t,wheels=False); print("passive peak err deg",round(p.peak_error_deg,1))
run=ws.simulate_attitude(t,kp=0.04,kd=0.4,torque_limit=1.5*np.array(r.peak_torque_axis_Nm),momentum_limit=1.5*np.array(r.peak_momentum_axis_Nms))
print("wheel peak err deg",round(run.peak_error_deg,4),"final",round(run.final_error_deg,5))
EOF

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:23:28.527Z
Duration (ms)
4246
Execution status
exit 0
Check figure tooling and draw the sizing data-flow diagram — exit 0r9

Stdout

figkit: environment ok
.walkthrough/figs/flow.svg: 0 findings

Exact command

mkdir -p .walkthrough/figs; "$WALKTHROUGH_FIGKIT/scripts/check-env.sh" 2>&1 | tail -3
cat > .walkthrough/figs/flow.py <<'EOF'
from svgfig import Figure
f = Figure()
rows = lambda h, *r: [h, *r]
a = f.node(20, 20, ["Spiral scenario", "robot, gantry, tiles move", "relative to structure B"], cat=0, w=220)
b = f.node(290, 20, ["momentum_core", "exact $h_{rel}(t)$, $\\dot h_{rel}$, $J$", "every 0.01 s, phase cuts kept"], cat=0, w=240)
c = f.node(570, 20, ["Momentum table (npz)", "committed data file", "read by all later steps"], cat=1, w=210)
f.arrow(a.r, b.l); f.arrow(b.r, c.l)
d = f.node(20, 190, ["requirement()", "$h_w=-h_{rel}$, $\\tau=-\\dot h_{rel}$", "peak per axis and norm"], cat=2, w=220)
e = f.node(290, 190, ["design_wheel()", "margin, max rpm, radius", "gives inertia, mass, power"], cat=2, w=240)
g = f.node(570, 190, ["simulate_attitude()", "closed loop with limits", "checks attitude error"], cat=3, w=210)
f.connector([c.b, (c.cx, 150), (d.cx, 150), d.t], color="cat1")
f.arrow(d.r, e.l); f.arrow(e.r, g.l)
f.save(".walkthrough/figs/flow.svg")
EOF
"$WALKTHROUGH_FIGKIT/run.sh" .walkthrough/figs/flow.py

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:23:32.773Z
Duration (ms)
1365
Execution status
exit 0

Figure artifacts

  • .walkthrough/figs/r9-flow.svg · 26449 bytes
    SHA-256: e3e43a491d5ba7e7d08f4d85cb322e9cd73884e0f54cf07f9124438bde192f79
    figkit lint: 0 findings
    Embedded as text outlines: .walkthrough/figs/r9-flow.outlined.svg · SHA-256 01afec25a16a353331dc927c013dd3c1b71394159a6154a238bb8f93d6e14d42

Requested artifact: .walkthrough/figs/flow.svg

Working tree when walkthrough_write was called (taken by the tool, not the agent) — exit 0r10

Stdout

 M .DS_Store
 M backlog/.DS_Store
 M notebooks/zo25/01_angular_momentum_basics.ipynb
?? literature/~$lit_toolkit.xlsx

Exact command

git status --porcelain --untracked-files=all -- . ':(exclude).walkthrough'

Technical metadata

Working directory
/Users/mikek/Zig_ORLO*
Started
2026-10-29T02:24:11.848Z
Duration (ms)
44
Execution status
exit 0
Snapshot
after
Recorded tree snapshot
{
  ".DS_Store": "fb1a9d7cec7ec20d6c24534b985bd33b65ff787ab6384a3df4c8b4953e9519b1",
  "backlog/.DS_Store": "2606164498ffde2ebfb61f5f046c8023cf022462ef960db660289637caf2d2bc",
  "notebooks/zo25/01_angular_momentum_basics.ipynb": "8f045d7f7cf02a26e8f5a2c5283a722f17e64cc2ed1df95d4c647598767bd460",
  "literature/~$lit_toolkit.xlsx": "19e3923c4089f22600981bc0ad9384295acfefb15fa2838381fe2911efd9ed67",
  ".pi/": "directory",
  ".pytest_cache/": "directory",
  "Literature Review/": "directory",
  "Reaction Wheel/": "directory",
  "__pycache__/": "directory",
  "backlog/": "directory",
  "deliverables/": "directory",
  "literature/": "directory",
  "notebooks/": "directory",
  "outputs/": "directory",
  "tests/": "directory",
  "walkthrough/": "directory"
}
Report metadata
Repository
Zig_ORLO*
Branch
main
Commit
3f58563
Working tree
uncommitted changes
Recorded on
2026-10-29 02:24
Model
MIT-parley/bedrock/claude-sonnet-5-5
Budget
20 commands (built-in default), 5 min total (built-in default)
Working directory
/Users/mikek/Zig_ORLO*

Working-tree comparison: checked; no changed paths detected.

Before snapshotr0 After snapshotr10