Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: rai-opensource/spatialmath-python
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 1.1.17
Choose a base ref
...
head repository: rai-opensource/spatialmath-python
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: 1.1.18
Choose a head ref
  • 16 commits
  • 30 files changed
  • 7 contributors

Commits on Aug 27, 2026

  1. Configuration menu
    Copy the full SHA
    51ceffc View commit details
    Browse the repository at this point in the history

Commits on Aug 31, 2026

  1. Configuration menu
    Copy the full SHA
    7e7fc92 View commit details
    Browse the repository at this point in the history

Commits on Sep 2, 2026

  1. Configuration menu
    Copy the full SHA
    a4f7c65 View commit details
    Browse the repository at this point in the history

Commits on Sep 3, 2026

  1. Configuration menu
    Copy the full SHA
    c3eaff6 View commit details
    Browse the repository at this point in the history
  2. test: force headless Matplotlib backend for local + CI test runs (#197)

    Local `pytest` runs were popping up real windows and, for a few tests,
    hanging outright. Two separate problems, one root cause:
    
    1. CI sets MPLBACKEND=Agg via the workflow env, but nothing did that
       for local runs. Several modules (geom2d, geom3d, spline, animate)
       import matplotlib.pyplot at module load time, so whatever backend
       is active when they're first imported sticks for the whole
       session. Locally that's the platform's interactive backend, hence
       the popups.
    
       Fix: tests/conftest.py sets os.environ.setdefault("MPLBACKEND",
       "Agg") before anything else runs. conftest.py is guaranteed to
       load before pytest imports any test module, so this closes the gap
       for local runs without touching the CI workflow (now redundant
       there, not conflicting). setdefault(), not a hard override, keeps
       an escape hatch: `MPLBACKEND=MacOSX pytest ...` still shows you a
       real plot when you actually want one.
    
    2. Forcing Agg everywhere surfaced a latent bug: Twist/pose animation
       tests use tranimate(..., wait=True), which busy-loops on
       `plt.pause()` waiting for FuncAnimation's timer callback to
       deregister itself. That deregistration is driven by the GUI event
       loop, which Agg doesn't have — so under Agg the loop never exits.
       Confirmed with a hard-alarm timeout: the affected test consumed a
       full 12s budget with zero output, versus completing normally under
       a real backend.
    
       These tests were already skipped in CI (via an `os.environ.get(
       "CI") == "true"` check) for a related but distinct reason — no
       display in the CI runner. That check happened to also mask this
       hang, but only in CI; locally, before this change, it ran fine
       because a real backend really does pump the event loop. Once Agg
       is forced locally too, the same hang would trigger there.
    
       Fix: broadened the three affected skip conditions (test_animate in
       test_transforms3d_plot.py; the two animate=True visualize tests
       and the inline guard in test_spline.py) to additionally skip
       whenever plt.get_backend() == "agg", which is the actual root
       cause rather than the CI-env-var proxy for it. Purely additive —
       no existing skip condition was removed, so CI behaviour is
       unchanged. Everything else (plain, non-animated plotting tests)
       now safely runs headless both locally and in CI, which is strictly
       more coverage than before.
    
    Verified: full suite passes locally with CI unset (339 passed, 3
    skipped, 1.6s, no windows, no hangs) and with CI=true set (338 passed,
    4 skipped, matching prior CI behaviour).
    petercorke authored Sep 3, 2026
    Configuration menu
    Copy the full SHA
    6e1edea View commit details
    Browse the repository at this point in the history

Commits on Sep 15, 2026

  1. Configuration menu
    Copy the full SHA
    09b0c43 View commit details
    Browse the repository at this point in the history
  2. Use new colored API (#173)

    `fg`, `bg`, and `attr` were renamed to `fore`, `back`, and `style` in
    `colored` 1.5.0 and onwards. Although these functions were added back in
    `colored` 2.1.1 for backwards-compatibility, the docstring indicates
    that they will be deprecated in the future.
    
    Co-authored-by: Peter Corke <[email protected]>
    shermansiu and petercorke authored Sep 15, 2026
    Configuration menu
    Copy the full SHA
    292d6ba View commit details
    Browse the repository at this point in the history
  3. Fix slerp at coincident/antipodal endpoints, and SO2/SE2.interp1() (#193

    )
    
    Two crashes in the interpolation methods, found sweeping the whole slerp
    surface (angle between the endpoints from 0 to pi across both singular
    ends, `s` over [0,1], `shortest` either way).
    
    ### slerp singularities
    
    The slerp weights `sin((1-s)t)/sin(t)` and `sin(s.t)/sin(t)` are
    singular wherever `sin(t)` vanishes: at `t = 0` (coincident endpoints)
    and at `t = pi` (antipodal endpoints, which are the same rotation under
    the double cover). `qslerp()` guards only `t = 0`;
    `UnitQuaternion.interp()` and `.interp1()` re-derive the weights inline
    and guard neither.
    
    ```python
    q = UnitQuaternion.Rx(0.3)
    q.interp(q, 0.5)                                 # ZeroDivisionError
    UnitQuaternion().interp1(0.5)                    # ZeroDivisionError
    UnitQuaternion.Rx(pi).interp(UnitQuaternion.Rx(-pi), 0.5, shortest=True)   # ZeroDivisionError
    UnitQuaternion.Rx(pi).interp(UnitQuaternion.Rx(-pi), 5)                    # TypeError
    qslerp(q.vec, -q.vec, 0.5)                       # [0 0 0 0], not a unit quaternion
    ```
    
    `acos(dotprod)` loses the small angle to rounding at both ends, so
    `sin(acos(dotprod))` is a poor denominator. This takes `sin(t)` directly
    as the length of the component of `q1` orthogonal to `q0`, which keeps
    full relative precision, and gets `t` from `atan2`. The only degenerate
    case left is `sin(t) == 0`, where the endpoints are the same rotation
    and so is every interpolate. The two `UnitQuaternion` methods now call
    `qslerp()`, which their own `:seealso:` already pointed at, so the
    formula lives in one place.
    
    Checked against a 50-digit `q0 exp(s log(q0^-1 q1))` reference —
    Lie-group form, so it shares no algebra with the sin-weight formula —
    over the full range of `t` and `s`:
    
    - endpoints within 1e-6 of antipodal: worst error 4.4e-5 -> 2.7e-10 rad
    - largest deviation from unit norm anywhere: 8.2e6 -> 2.8e-4 (just short
    of antipodal, `qslerp` was returning quaternions with a norm in the
    millions)
    - ordinary angles move by at most 1 ulp, and the patched surface agrees
    with `scipy.spatial.transform.Slerp` to 1.4e-15 rad over 10000 random
    pairs
    
    Exactly antipodal with `shortest=False` has no unique great circle, so
    there is no correct answer there; it now returns a unit quaternion for
    the rotation both endpoints share instead of a norm-1e6 vector or `[0 0
    0 0]`.
    
    ### SO2/SE2.interp1()
    
    The fix for #33 dropped the `start` local but replaced its uses only in
    the `N == 3` branch, so `SE2(1, 2, 0.3).interp1(0.5)` has raised
    `NameError: name 'start' is not defined` ever since — #33 did report it
    for both SE2 and SE3. `interp1()` had no test coverage in either
    dimension.
    
    ---
    
    4 new test cases, all red on master. The existing `test_slerp` and
    `test_interp` values were already correct and pass unchanged. Full suite
    green, `black` 23.10.0 clean.
    
    ---------
    
    Co-authored-by: Peter Corke <[email protected]>
    binggao1230 and petercorke authored Sep 15, 2026
    Configuration menu
    Copy the full SHA
    b7e7bee View commit details
    Browse the repository at this point in the history
  4. feat(pose,quaternion): add __imatmul__ (@=) operator (#199)

    ## What
    
    `X @= Y` now works as the augmented-assignment form of the existing `X @
    Y`
    (`__matmul__`, which composes with normalization) — previously only `X
    *= Y`
    existed, which composes *without* normalization. Useful when a pose or
    unit
    quaternion is updated incrementally over many cycles and you want the
    normalized form without writing `X = X @ Y` by hand.
    
    Added to `BasePoseMatrix` (covers `SO2`/`SE2`/`SO3`/`SE3`) and
    `Quaternion`
    (covers `Quaternion`/`UnitQuaternion`).
    
    Note on semantics: like the existing `__imul__`, this doesn't mutate the
    object in place — `__imatmul__` returns a new (normalized) object and
    Python
    rebinds the name, same as `X = X @ Y`. That matches the existing `*=`
    pattern in this codebase exactly, just saves writing `X = X @ Y`.
    
    ## A bug found while adding test coverage
    
    This started as a cherry-pick of old, never-merged WIP work. While
    writing
    tests I found `Quaternion.__imatmul__`'s docstring claimed `q1 @= q2`
    sets
    `q1 := qnorm(q1 * q2)`, but the implementation just delegated to
    `__mul__`
    — identical to plain `*=`, no normalization at all, contradicting both
    the
    docstring and the entire point of adding `@=`.
    
    `UnitQuaternion.__matmul__` (pre-existing, unchanged) already normalizes
    correctly via `smb.qunit(smb.qqmul(x, y))` — `qunit` being the actual
    normalizer; `qnorm` just returns the scalar magnitude, so it was never
    really the right function despite the docstring's wording.
    
    Fixed by having `__imatmul__` delegate to `left @ right` instead of
    `left.__mul__(right)`. Deliberately not `left.__matmul__(right)` either:
    plain `Quaternion` has no `__matmul__` (only `UnitQuaternion` defines
    one),
    and calling the dunder directly as a plain attribute bypasses Python's
    normal operator fallback, raising a confusing `AttributeError` instead
    of
    the `TypeError` that `q1 @ q2` already raises consistently for plain
    `Quaternion`. `left @ right` matches `@`'s behaviour exactly in both
    cases.
    
    Also fixed the docstring's `-> bool` return type annotation (should be
    `-> Quaternion`) and its example, which called `Quaternion.Eul()` — a
    method that only exists on `UnitQuaternion`.
    
    ## Testing
    
    - Added `@=` coverage for `SO3`/`SE3` (must match `@`) alongside the
      existing `*=` tests in `test_pose3d.py`.
    - Added `@=` coverage for `UnitQuaternion` (must match `@`, not `*`) and
    for
      plain `Quaternion` (must raise `TypeError`, matching `@`, not silently
      degrade to `*=`) in `test_quaternion.py`.
    - Full suite: 338 passed, 4 skipped.
    - `black --check` clean at the pinned 23.10.0.
    petercorke authored Sep 15, 2026
    Configuration menu
    Copy the full SHA
    45ed832 View commit details
    Browse the repository at this point in the history
  5. refactor: consistent printline() across pose and quaternion classes (#…

    …200)
    
    ## What
    
    Consistent `printline()` behaviour across `SO2`/`SE2`/`SO3`/`SE3`/
    `Quaternion`/`UnitQuaternion`:
    
    - Adds `Quaternion.printline()` (previously only the pose classes had
    it).
    - Splits the string-building logic out of `trprint`/`trprint2`/`qprint`
    into
      dedicated `tr2str`/`tr2str2`/`q2str`-style functions (the latter two
    already existed; `tr2str`/`tr2str2` are new), so "give me the formatted
    string" and "print the formatted string" are two separate, clearly-named
      functions instead of one function trying to do both via a `file` flag.
    - Fixes the original bug this was written for:
    `contextlib.redirect_stdout()`
      didn't work with the old code, because `file=sys.stdout` as a default
    argument value is evaluated once at function-definition time and freezes
    whatever `sys.stdout` was *then* - it doesn't see a later redirect.
    Fixed
    by using a `file=False` sentinel, resolved to `None` inside the function
      body (so `print()` looks up the *current* `sys.stdout` at call time).
    
    ## Bugs found while packaging this up for review
    
    This started as old WIP work from a local branch, never previously
    reviewed or merged. Testing it before submission turned up three real
    bugs,
    all fixed here:
    
    1. **`trprint()`/`qprint()` silently shifted `file` into the 2nd
    positional
       argument.** The original, already-published signatures had `orient`
    (`trprint`) / `delim` (`qprint`) there. `trprint(T, 'angvec')` or this
       library's *own documented* `x.printline('angvec')` example put
       `'angvec'` into `file` instead, crashing with `AttributeError: 'str'
       object has no attribute 'write'`. Fixed by restoring the original
       explicit parameter order for both (`trprint2` was unaffected - its
       parameter order happened to already put `file` in the same slot).
    2. **`trprint2()` captured `label` but never forwarded it** to
    `tr2str2()`
    - `trprint2(T, label='T')` silently dropped the label from the output.
    3. **All three stopped returning the formatted string**, only printing
    it -
    breaking the existing, still-supported `file=None` → "return the string
       instead of printing" usage that a couple of existing tests rely on
    (`test_transforms3d.py::test_print`,
    `test_transforms2d.py::test_print2`).
    
    While fixing (3), also formally deprecated that `file=None` pattern
    rather
    than silently perpetuating it: each function now has a real
    `tr2str()`/`tr2str2()`/`q2str()` sibling that returns the string
    directly,
    so `file=None` still works exactly as before (returns the string,
    doesn't
    print) but now raises a `DeprecationWarning` and says so explicitly in
    the
    docstring via `.. deprecated::`, pointing at the replacement function.
    
    All three (`trprint`/`trprint2`/`qprint`) now follow one consistent
    shape:
    build the string via the `*2str`/`q2str` sibling, always return it,
    print
    only when `file is not None`.
    
    ## Testing
    
    - Verified `file=None` still returns the correct string with a
      `DeprecationWarning` and no printing, for all three functions.
    - Verified the default path both prints (via
    `contextlib.redirect_stdout`,
      confirming the original bug is actually fixed) and returns the same
      string.
    - Verified positional-arg calls (`trprint(T, 'angvec')`,
      `x.printline('angvec')`) work correctly again.
    - Full suite: 338 passed, 4 skipped.
    - `black --check` clean at the pinned 23.10.0.
    
    ## Note on PR ordering
    
    This PR and #198 (lazy Matplotlib import) both touch adjacent code in
    `spatialmath/base/transforms3d.py` (right around `_vec2s`/
    `_matplotlib_exists`/`trprint`/`trplot`) - not a conflict with anything
    already merged, just two open PRs based on the same `upstream/master`
    point. Whichever lands first, the other will likely need a rebase to
    resolve a real merge conflict before it can land.
    petercorke authored Sep 15, 2026
    Configuration menu
    Copy the full SHA
    c20408d View commit details
    Browse the repository at this point in the history
  6. fix: SO3.RotatedVector returned identity for antipodal vectors (#201)

    ## Summary
    
    `SO3.RotatedVector(v1, v2)` computes the rotation axis as `v1 x v2`.
    That
    cross product is zero whenever `v1` and `v2` are (anti)parallel, and the
    existing singularity check (`abs(s) < tol * eps`) treats both cases
    identically -- returning identity regardless:
    
    ```python
    >>> from spatialmath import SO3
    >>> SO3.RotatedVector([0, 0, 1], [0, 0, -1])  # should flip, not be identity
       1         0         0
       0         1         0
       0         0         1
    ```
    
    That's correct when `v1` and `v2` point the same way, but wrong when
    they're antipodal (`v2 == -v1`) -- the correct answer there is a 180°
    rotation about any axis perpendicular to `v1`, not identity.
    
    - [x] Distinguish the two cases via the sign of `v1 . v2` at the
      singularity.
    - [x] The antipodal case uses the closed form for a 180° rotation about
    a
      unit axis `u` (`R = 2*u*u^T - I`), with `u` found by crossing `v1`
      against whichever world axis it's least aligned with (so the cross
      product used to find `u` is never itself degenerate).
    - [x] Existing test coverage
    (`tests/test_pose3d.py::test_rotatedvector`)
      only covered the general and exact-same-direction cases -- added the
      antipodal case there, parametrised over several different `v1` values.
    
    Found this while building a `FromTo(start, end)` constructor for an
    `Arrow` shape in a downstream package, which needs exactly this "rotate
    a
    reference axis to point along an arbitrary direction" operation and hit
    the bug immediately for a direction pointing straight backward relative
    to the reference axis.
    
    ## Test plan
    
    - [x] Full suite: `pytest tests/` -- 342 passed
    - [x] New antipodal-case test passes; confirmed it fails against the old
      code (returns identity instead of a real rotation)
    - [x] Confirmed the general-rotation and exact-same-direction cases are
      unaffected (existing test assertions unchanged)
    petercorke authored Sep 15, 2026
    Configuration menu
    Copy the full SHA
    59f3a3c View commit details
    Browse the repository at this point in the history
  7. fix: support scalar/2-elem dim shorthand in tranimate/Animate (#202)

    ## Summary
    
    `tranimate(T, dim=1.5)` — using the scalar-shorthand `dim` convention
    established by `plotvol2`/`plotvol3` elsewhere in this codebase —
    currently
    crashes with:
    
    ```
    TypeError: spatialmath.base.animate.Animate() got multiple values for keyword argument 'dim'
    ```
    
    Two compounding bugs, both fixed here:
    
    1. `tranimate()` popped `"dims"` (plural) out of `kwargs` before
    forwarding
       to `Animate(dim=..., **kwargs)`, but every other function in this
    codebase (`plotvol2`, `plotvol3`, `Animate.__init__` itself) names the
       parameter `dim` (singular). A caller correctly using `dim=` per that
       convention never got popped, so it stayed in `**kwargs` and collided
       with the explicit `dim=dim` already being passed — hence "multiple
       values for keyword argument 'dim'".
    2. Even with the right keyword, `Animate.__init__` had its own
    hand-rolled
       length check that only accepted a 2- or 6-element `dim`, silently
       dropping the scalar-shorthand convention (`A` → `[-A, A]` on every
       axis) that `plotvol3` already supports via the shared `expand_dims()`
       helper — `Animate` just never called it.
    
    ## Fix
    
    - `tranimate()` now accepts `dim`, with `dims` kept as a back-compat
    alias
      for existing callers following the old docstring examples.
    - `Animate.__init__` now calls `expand_dims(dim, nd=3)` (the same helper
    `plotvol3` uses) instead of its own incomplete validation, so scalar and
      2-element shorthand work consistently everywhere.
    
    ## Regression context
    
    This isn't a long-standing issue — it's a regression from #131 (`Jien
    Cao`,
    2024-07-29, fixing #126), which *introduced* both the `dims` rename and
    the
    new strict length check while trying to "expose `ax` and `dims`
    arguments
    to animate(...), to be consistent with other APIs." Before that commit,
    `tranimate` passed `**kwargs` straight through to `Animate`, and scalar
    `dim` worked correctly via `Animate`'s existing `plotvol3` delegation.
    
    ## Test plan
    
    - [x] Verified directly: `Animate(dim=1.5)`, `Animate(dim=[0,5])`,
          `tranimate(R, dim=1.5, movie=True)`, and `tranimate(R, dims=[0,5],
          movie=True)` (back-compat alias) all construct/run correctly
    - [x] Full existing test suite: 342 passed, no regressions
    petercorke authored Sep 15, 2026
    Configuration menu
    Copy the full SHA
    197d383 View commit details
    Browse the repository at this point in the history
  8. Fix sphinx automation (#162)

    The workflow to generate sphinx documentation seems to not be working.
    Trying to fix that with this PR.
    
    ---------
    
    Co-authored-by: Peter Corke <[email protected]>
    myeatman-bdai and petercorke authored Sep 15, 2026
    Configuration menu
    Copy the full SHA
    6f9e892 View commit details
    Browse the repository at this point in the history
  9. perf: defer Matplotlib import until something actually plots (#198)

    ## Problem
    
    `import spatialmath` unconditionally pulls in all of Matplotlib, even
    for
    users who never plot anything (RAI wishlist item: "Don't depend on
    matplotlib unless you're actually plotting").
    `spatialmath/base/__init__.py`
    did `from spatialmath.base.animate import *` / `from
    spatialmath.base.graphics import *` at package-import time, and those
    two
    modules do `import matplotlib.pyplot`. `geom2d.py`, `geom3d.py`,
    `spline.py`,
    and both `transforms2d.py`/`transforms3d.py` had their own copies of the
    same pattern — some via a `try: import matplotlib.pyplot ... except
    ImportError:` optional-dependency check that still imported eagerly,
    just
    without crashing if matplotlib turned out to be missing.
    
    Measured on my machine: bare `import matplotlib` costs ~96ms,
    `matplotlib.path` (needed structurally by `Polygon2`'s geometry, not
    just
    plotting) adds ~0ms on top of that, but `matplotlib.pyplot` specifically
    (backend resolution + figure/state setup) adds another ~160ms. That's
    the
    cost this PR removes from `import spatialmath`. (Caveat: on this machine
    matplotlib isn't the single biggest contributor to overall import time —
    `scipy.interpolate` and `sympy`, when installed, are comparable — so
    this
    alone may not fully explain reports of ~9s import time on other
    machines;
    worth keeping an eye on.)
    
    ## Approach
    
    Deliberately **not** touching matplotlib usage inside `graphics.py`/
    `animate.py` themselves — dozens of `plt.Axes`-style annotations live in
    there, and rewriting those would be a much bigger, riskier change than
    this
    needs to be. Instead, defer the **module import** of
    `graphics`/`animate`
    as a whole, plus a few other files with the same eager-import pattern:
    
    - **`spatialmath/base/__init__.py`**: replace the two blanket `import *`
      lines with a PEP 562 module `__getattr__` that imports
    `animate.py`/`graphics.py` lazily on first access of one of their names
      (`Animate`, `plot_box`, `tranimate`, etc.), not unconditionally at
      package import time.
    - **`spatialmath/base/transforms2d.py`, `transforms3d.py`**: both had a
      module-level `try: import matplotlib.pyplot ... except ImportError:
      _matplotlib_exists = False` used purely to decide whether to define
    `trplot`/`trplot2`/`tranimate`/`tranimate2` at all. Replaced with a
    cheap
      `importlib.util.find_spec("matplotlib")` check (no real import), and
      moved the small number of actual `plotvol2/3`, `axes_logic`,
      `Animate`/`Animate2`, and `plt.show()` call sites into the specific
      functions that use them.
    - **`spatialmath/spline.py`, `geom3d.py`**: same pattern — moved `import
      matplotlib.pyplot as plt` from module top into the one or two methods
      that actually plot.
    - **`spatialmath/geom2d.py`**: nuance — `Polygon2.__init__` uses
      `matplotlib.path.Path` for real geometry (point containment etc.), and
      `Polygon2.transformed()` uses `matplotlib.transforms.Affine2D` for the
      same reason, so both stay at module level (cheap anyway, per the
      measurement above). Only `matplotlib.pyplot` itself, and the
      `plot_ellipse` import (only used by `Ellipse.plot`), moved.
    
    All of the above needed `from __future__ import annotations` added where
    not already present, so a signature like `ax: Optional[plt.Axes] = None`
    doesn't force `plt` to be a real bound name at function *definition*
    time
    (module-import time, before the deferred import ever runs) — annotations
    become lazy strings instead, which type checkers still read fine.
    Matches
    the existing convention already used in 8 other files in this codebase.
    
    One real (minor) bug this surfaced: `tests/test_geom3d.py` used
    `plt.figure()` without importing `matplotlib.pyplot` itself — it only
    worked because `from spatialmath.geom3d import *` used to leak `plt` in
    as
    a wildcard-imported name. Fixed by importing it directly.
    
    ## Testing
    
    - `import spatialmath` no longer puts `matplotlib.pyplot` in
    `sys.modules`;
    `matplotlib` (the ~96ms base package, structurally needed by
    `Polygon2`'s
      geometry) still does.
    - Wall-clock `import spatialmath`, same machine, same warm caches:
    ~670ms
    average on 3 runs before this change (`upstream/master`, via a throwaway
      worktree), ~447ms average after.
    - Full test suite green in both CI-like mode (`CI=true MPLBACKEND=Agg`:
    338
      passed, 4 skipped) and a local-run simulation (`MPLBACKEND=Agg`, `CI`
    unset): 332 passed (excluding two files whose local-run behaviour
    depends
      on a separate, already-open PR, unrelated to this change).
    - Manual smoke test with a forced Agg backend: `trplot`, `trplot2`,
      `Polygon2.plot`/`.animate`/`.contains`, `Ellipse.plot`, `Line3.plot`,
      `Plane3.plot`, `BSplineSE3.visualize` all still produce real output.
    - `black --check` clean at the pinned 23.10.0.
    petercorke authored Sep 15, 2026
    Configuration menu
    Copy the full SHA
    f6a572c View commit details
    Browse the repository at this point in the history

Commits on Sep 16, 2026

  1. Fix SpatialForce/SpatialMomentum SE(3) transform to use the coadjoint…

    … (Ad^-T) (#207)
    
    Fixes #169.
    
    ## Problem
    
    A spatial force/wrench is **dual** to spatial motion, so under an SE(3)
    transform it must map by the **coadjoint** `Ad^-T` (inverse-transpose of
    the adjoint), not the adjoint transpose `Ad^T`. Because the SE(3)
    adjoint is non-orthogonal whenever the translation is nonzero, `Ad^T !=
    Ad^-T`, so `SpatialForce` and `SpatialMomentum` were transformed
    incorrectly for any pose with translation (correct only for a pure
    rotation, where `Ad` is orthogonal). Velocity/acceleration (motion),
    which correctly use `Ad`, were fine.
    
    ## Repro / self-oracle
    
    Instantaneous power `f . v` is frame-invariant, so it must be preserved
    by the transform:
    
    ```python
    from spatialmath import SE3, SpatialVelocity, SpatialForce
    import numpy as np
    
    T = SE3(1, 0, 0)                       # pure +x translation
    v = SpatialVelocity([0, 0, 0, 0, 1, 0])
    f = SpatialForce([0, 0, 1, 0, 0, 0])
    
    v2, f2 = T * v, T * f
    print(f.A @ v.A, f2.A @ v2.A)          # should be equal
    # before: 0.0 2.0   <- power not invariant (bug)
    # after:  0.0 0.0   <- invariant
    ```
    
    The transformed wrench's moment component came out with the wrong sign;
    `f2` should be `[0, 0, 1, 0, -1, 0]` but was `[0, 0, 1, 0, 1, 0]`.
    
    ## Fix
    
    Use `np.linalg.inv(Ad).T` (the coadjoint) in `SpatialForce.__rmul__` and
    in the force/momentum branch of the general `SpatialVector.__rmul__`
    (which `SpatialMomentum` uses). The motion branch is unchanged.
    
    ## Test
    
    The `test_products` stub in `tests/test_spatialvector.py` was empty, so
    these transforms were untested. Adds `test_spatial_transform_duality`
    asserting the power invariance (`f2 . v2 == f . v`,
    convention-independent) plus the explicit transformed wrench and
    momentum. Red before the fix (power `2 != 0`), green after; the existing
    motion tests are unaffected.
    
    Reported by @Yuxiang-Ma, who cited Featherstone's *Rigid Body Dynamics
    Algorithms*.
    
    ---
    This change was prepared with AI assistance and reviewed by me before
    submission.
    
    ---------
    
    Co-authored-by: Peter Corke <[email protected]>
    youdie006 and petercorke authored Sep 16, 2026
    Configuration menu
    Copy the full SHA
    3b25bb7 View commit details
    Browse the repository at this point in the history
  2. Configuration menu
    Copy the full SHA
    2de7801 View commit details
    Browse the repository at this point in the history
Loading