tpt-math-spatial 0.2.0

Spatial (Featherstone) kinematics for the tpt-math substrate: 6-D spatial vectors, dual quaternions and screw theory. In-house, no compliant-license wrap target. Built on tpt-math-geometry / tpt-math-linalg-fixed. No allocator.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
#![no_std]
#![forbid(unsafe_code)]
// Fixed-size 6-D spatial algebra is clearest with explicit indexing over
// fixed-size arrays; the indexed-loop and arithmetic-impl lints do not fit
// this code.
#![allow(
    clippy::needless_range_loop,
    clippy::manual_swap,
    clippy::suspicious_arithmetic_impl,
    clippy::suspicious_op_assign_impl
)]
//! In-house (no external-crate) spatial kinematics for the `tpt-math`
//! substrate: Featherstone 6-D spatial vectors, Plücker / adjoint transforms,
//! dual quaternions and screw theory (exponential / logarithmic maps).
//!
//! Everything is built on [`tpt_math_geometry`] ([`Isometry3`],
//! `Quaternion`, `UnitQuaternion`, …) and [`tpt_math_linalg_fixed`], is
//! `#![no_std]` and allocator-free (stack-allocated fixed-size storage), and
//! carries **no `nalgebra` dependency** (matching the workspace license policy,
//! ADR-0007). It exists to fill the spatial-algebra gap in-house.
//!
//! # Conventions (stated explicitly)
//!
//! * **Active (alibi) rotations** — a transform acts on a vector `v` as
//!   `R * v`; the *point/vector* is rotated, not the coordinate frame.
//! * **Column vectors** — transformations apply as `M * v`.
//! * **Right-handed coordinates** — positive angle about `+z` rotates `x → y`;
//!   `x × y = z`.
//! * **Spatial (6-D) vectors** are stored `[angular (top 3); linear (bottom
//!   3)]`: a motion vector `v = (ω, v)` and a force/wrench
//!   `f = (n, f)` (moment, force).
//! * **Spatial cross product** follows Featherstone's `crm` / `crf`
//!   operators (see [`SpatialVector::cross`] and friends); the result kind is
//!   determined by the operand kinds (motion⊗motion→motion, motion⊗force→force,
//!   force⊗motion→force, force⊗force→motion).
//! * **Screw exponential** `exp` maps a twist `(ω, v) ∈ se(3)` to an
//!   [`Isometry3`]; `log` is its inverse. The convention is the standard
//!   Lynch–Park `se(3)` exponential with an **active**, right-handed rotation.
//! * **Dual quaternions** are Hamilton quaternions `q + ε·qₑ` representing a
//!   rigid transform (rotation quaternion + half the translation quaternion
//!   pre-multiplied by the rotation).
//!
//! # Examples
//!
//! ```
//! use tpt_math_spatial::{MotionVector, Screw};
//! use tpt_math_geometry::{Isometry3, Rotation3, Translation};
//! use tpt_math_linalg_fixed::Vector3;
//!
//! // A 90° active rotation about +Z.
//! let rot = Rotation3::from_axis_angle(&Vector3::new([0.0_f64, 0.0, 1.0]), std::f64::consts::FRAC_PI_2);
//! let iso = Isometry3::new(Translation::new(Vector3::new([0.0, 0.0, 0.0])), rot);
//!
//! // A pure-linear motion (1,0,0): after the rotation its linear part is (0,1,0).
//! let m = MotionVector::new(Vector3::new([0.0, 0.0, 0.0]), Vector3::new([1.0, 0.0, 0.0]));
//! let m2 = m.transform_by(&iso);
//! assert!((m2.linear().x()).abs() < 1e-12);
//! assert!((m2.linear().y() - 1.0).abs() < 1e-12);
//!
//! // A screw twist exponentiates to the same isometry.
//! let screw = Screw::new(Vector3::new([0.0, 0.0, std::f64::consts::FRAC_PI_2]), Vector3::new([0.0, 0.0, 0.0]));
//! let iso2 = screw.exp();
//! assert!((iso2.rotation.matrix().data[0][1] - (-1.0)).abs() < 1e-12);
//! ```

extern crate alloc;

use core::fmt;
use core::marker::PhantomData;
use core::ops::{Add, Mul, Neg, Sub};

use tpt_math_geometry::{Isometry3, Quaternion, Rotation3, Translation, UnitQuaternion};
use tpt_math_linalg_fixed::{Matrix, Matrix3, Vector3, Vector6};
use tpt_math_numeric::Scalar;

/// A `6 × 6` matrix (fixed-size, row-major).
pub type Matrix6<T> = Matrix<T, 6, 6>;

#[inline]
fn c<T: Scalar>(x: f64) -> T {
    T::from(x).unwrap()
}

#[inline]
fn two<T: Scalar>() -> T {
    T::one() + T::one()
}

/// Skew-symmetric (`×`) matrix of a 3-vector.
#[inline]
fn skew<T: Scalar + Copy>(v: &Vector3<T>) -> Matrix3<T> {
    Matrix3::new([
        [T::zero(), -v.z(), v.y()],
        [v.z(), T::zero(), -v.x()],
        [-v.y(), v.x(), T::zero()],
    ])
}

// ===========================================================================
// Spatial (6-D) vectors
// ===========================================================================

/// Marker type for **motion**-type spatial vectors (velocities, accelerations).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Motion;
/// Marker type for **force**-type spatial vectors (wrenches: moment + force).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Force;

/// A 6-D spatial vector `v = [angular (top 3); linear (bottom 3)]`, tagged by
/// `K ∈ {`[`Motion`], [`Force`]`}` to control cross-product and transform
/// semantics (Featherstone's `crm` / `crf` operators).
///
/// * A [`MotionVector`] is `(ω, v)` (angular velocity, linear velocity).
/// * A [`ForceVector`] is `(n, f)` (moment, force).
///
/// See the [crate-level documentation](crate) for the full convention.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpatialVector<T, K> {
    /// The raw 6-components `[angular₀, angular₁, angular₂, linear₀, linear₁,
    /// linear₂]`.
    pub data: Vector6<T>,
    _marker: PhantomData<K>,
}

/// A **motion** spatial vector `(ω, v)`.
pub type MotionVector<T> = SpatialVector<T, Motion>;
/// A **force** / wrench spatial vector `(n, f)`.
pub type ForceVector<T> = SpatialVector<T, Force>;

impl<T: Scalar + Copy> SpatialVector<T, Motion> {
    /// Build a motion vector from its angular (top) and linear (bottom) halves.
    pub fn new(angular: Vector3<T>, linear: Vector3<T>) -> Self {
        SpatialVector {
            data: Vector6::new([
                angular.x(),
                angular.y(),
                angular.z(),
                linear.x(),
                linear.y(),
                linear.z(),
            ]),
            _marker: PhantomData,
        }
    }

    /// `motion ⊗ motion → motion` (Featherstone `crm`).
    pub fn cross(&self, rhs: &SpatialVector<T, Motion>) -> SpatialVector<T, Motion> {
        // (mω × nω, mω × nv + mv × nω)
        let mw = self.angular();
        let mv = self.linear();
        let nw = rhs.angular();
        let nv = rhs.linear();
        let top = mw.cross(&nw);
        let bot = mw.cross(&nv) + mv.cross(&nw);
        Self::new(top, bot)
    }

    /// `motion ⊗ force → force` (Featherstone `crm` applied to a force).
    pub fn cross_force(&self, rhs: &SpatialVector<T, Force>) -> SpatialVector<T, Force> {
        // (mω × fω + mv × fv, mω × fv)
        let mw = self.angular();
        let mv = self.linear();
        let fw = rhs.angular();
        let fv = rhs.linear();
        let top = mw.cross(&fw) + mv.cross(&fv);
        let bot = mw.cross(&fv);
        ForceVector::new(top, bot)
    }

    /// Transform this motion vector by an [`Isometry3`] using the motion
    /// Plücker adjoint `[R, 0; t×R, R]`.
    ///
    /// For a pure rotation this reduces to `R` acting on both halves, matching
    /// [`Isometry3::transform_vector`] componentwise.
    pub fn transform_by(&self, iso: &Isometry3<T>) -> Self {
        SpatialVector {
            data: adjoint_motion(iso) * self.data,
            _marker: PhantomData,
        }
    }
}

impl<T: Scalar + Copy> SpatialVector<T, Force> {
    /// Build a force vector from its angular (moment, top) and linear (force,
    /// bottom) halves.
    pub fn new(angular: Vector3<T>, linear: Vector3<T>) -> Self {
        SpatialVector {
            data: Vector6::new([
                angular.x(),
                angular.y(),
                angular.z(),
                linear.x(),
                linear.y(),
                linear.z(),
            ]),
            _marker: PhantomData,
        }
    }

    /// `force ⊗ motion → force` (Featherstone `crf`).
    pub fn cross_motion(&self, rhs: &SpatialVector<T, Motion>) -> SpatialVector<T, Force> {
        // (fω × mω, fω × mv + fv × mω)
        let fw = self.angular();
        let fv = self.linear();
        let mw = rhs.angular();
        let mv = rhs.linear();
        let top = fw.cross(&mw);
        let bot = fw.cross(&mv) + fv.cross(&mw);
        Self::new(top, bot)
    }

    /// `force ⊗ force → motion` (Featherstone `crf`).
    pub fn cross(&self, rhs: &SpatialVector<T, Force>) -> SpatialVector<T, Motion> {
        // (fω × gv + fv × gω, fv × gω)
        let fw = self.angular();
        let fv = self.linear();
        let gw = rhs.angular();
        let gv = rhs.linear();
        let top = fw.cross(&gv) + fv.cross(&gw);
        let bot = fv.cross(&gw);
        MotionVector::new(top, bot)
    }

    /// Transform this force vector by an [`Isometry3`] using the force
    /// Plücker adjoint `[R, t×R; 0, R]`.
    ///
    /// For a pure rotation this reduces to `R` acting on both halves, matching
    /// [`Isometry3::transform_vector`] componentwise.
    pub fn transform_by(&self, iso: &Isometry3<T>) -> Self {
        SpatialVector {
            data: adjoint_force(iso) * self.data,
            _marker: PhantomData,
        }
    }
}

// Shared accessors / transforms, generic over the kind marker.
impl<T: Scalar + Copy, K> SpatialVector<T, K> {
    /// The angular half (top 3 components).
    pub fn angular(&self) -> Vector3<T> {
        Vector3::new([self.data.data[0], self.data.data[1], self.data.data[2]])
    }

    /// The linear half (bottom 3 components).
    pub fn linear(&self) -> Vector3<T> {
        Vector3::new([self.data.data[3], self.data.data[4], self.data.data[5]])
    }

    /// Borrow the raw 6-vector.
    pub fn as_vector(&self) -> &Vector6<T> {
        &self.data
    }
}

impl<T: Scalar + Copy, K> Add for SpatialVector<T, K> {
    type Output = Self;
    /// # Panics
    ///
    /// Inherits `T`'s `+` semantics (never panics for floats).
    fn add(self, rhs: Self) -> Self {
        SpatialVector {
            data: self.data + rhs.data,
            _marker: PhantomData,
        }
    }
}

impl<T: Scalar + Copy, K> Sub for SpatialVector<T, K> {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self {
        SpatialVector {
            data: self.data - rhs.data,
            _marker: PhantomData,
        }
    }
}

impl<T: Scalar + Copy, K> Neg for SpatialVector<T, K> {
    type Output = Self;
    fn neg(self) -> Self {
        SpatialVector {
            data: -self.data,
            _marker: PhantomData,
        }
    }
}

impl<T: Scalar + Copy, K> Mul<T> for SpatialVector<T, K> {
    type Output = Self;
    fn mul(self, rhs: T) -> Self {
        SpatialVector {
            data: self.data * rhs,
            _marker: PhantomData,
        }
    }
}

impl<T: Scalar + Copy + fmt::Debug, K> fmt::Display for SpatialVector<T, K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[ω: {:?}; v: {:?}]",
            self.angular().data,
            self.linear().data
        )
    }
}

// ===========================================================================
// Adjoint (Plücker) transforms
// ===========================================================================

/// The **motion** adjoint `Ad_X` of an isometry `(R, t)`:
///
/// ```text
/// Ad_X = [ R      0   ]
///        [ t×R    R   ]
/// ```
///
/// Acting on a [`MotionVector`] `(ω, v)` it yields
/// `(R ω, R v + t × (R ω))`.
pub fn adjoint_motion<T: Scalar + Copy>(iso: &Isometry3<T>) -> Matrix6<T> {
    let r = *iso.rotation.matrix();
    let t = iso.translation.vector;
    let tl = skew(&t) * r;
    Matrix6::from_fn(|i, j| {
        if i < 3 && j < 3 {
            r.data[i][j]
        } else if i >= 3 && j < 3 {
            tl.data[i - 3][j]
        } else if i >= 3 && j >= 3 {
            r.data[i - 3][j - 3]
        } else {
            T::zero()
        }
    })
}

/// The **force** adjoint `Ad_X*` of an isometry `(R, t)`:
///
/// ```text
/// Ad_X* = [ R      t×R ]
///         [ 0      R   ]
/// ```
///
/// Acting on a [`ForceVector`] `(n, f)` it yields
/// `(R n + t × (R f), R f)`.
pub fn adjoint_force<T: Scalar + Copy>(iso: &Isometry3<T>) -> Matrix6<T> {
    let r = *iso.rotation.matrix();
    let t = iso.translation.vector;
    let tr = skew(&t) * r;
    Matrix6::from_fn(|i, j| {
        if i < 3 && j < 3 {
            r.data[i][j]
        } else if i < 3 && j >= 3 {
            tr.data[i][j - 3]
        } else if i >= 3 && j >= 3 {
            r.data[i - 3][j - 3]
        } else {
            T::zero()
        }
    })
}

// ===========================================================================
// Dual quaternions
// ===========================================================================

/// A dual quaternion `q = real + ε·dual`, each part a Hamilton
/// [`Quaternion`] (`w` last). A *unit* dual quaternion represents a rigid
/// transform (rotation + translation) with no scaling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DualQuaternion<T> {
    /// The real (rotation) part.
    pub real: Quaternion<T>,
    /// The dual (translation) part.
    pub dual: Quaternion<T>,
}

impl<T: Scalar> DualQuaternion<T> {
    /// Build a dual quaternion from its real and dual quaternion parts.
    pub fn new(real: Quaternion<T>, dual: Quaternion<T>) -> Self {
        DualQuaternion { real, dual }
    }

    /// A dual quaternion with a zero dual part (a pure rotation).
    pub fn from_real(real: Quaternion<T>) -> Self {
        DualQuaternion {
            real,
            dual: Quaternion::new(T::zero(), T::zero(), T::zero(), T::zero()),
        }
    }

    /// The (Hamilton) conjugate `(real*, dual*)`.
    pub fn conjugate(&self) -> Self {
        DualQuaternion {
            real: self.real.conjugate(),
            dual: self.dual.conjugate(),
        }
    }

    /// Normalise to a unit dual quaternion by dividing both parts by the norm
    /// of the real part. Returns `None` if the real part has zero norm.
    pub fn normalize(&self) -> Option<Self> {
        let n = self.real.norm();
        if n == T::zero() {
            return None;
        }
        let inv = T::one() / n;
        Some(DualQuaternion {
            real: self.real * inv,
            dual: self.dual * inv,
        })
    }

    /// Hamilton product of two dual quaternions
    /// `(r₁, d₁) * (r₂, d₂) = (r₁ r₂, r₁ d₂ + d₁ r₂)`.
    pub fn multiply(&self, rhs: &DualQuaternion<T>) -> DualQuaternion<T> {
        DualQuaternion {
            real: self.real.multiply(&rhs.real),
            dual: self.real.multiply(&rhs.dual) + self.dual.multiply(&rhs.real),
        }
    }

    /// Build a unit dual quaternion from a rigid transform.
    ///
    /// Given an isometry with rotation quaternion `q` and translation `t`, the
    /// dual quaternion is `q + ε·(½·t_q·q)` where `t_q = (t_x, t_y, t_z, 0)`.
    pub fn from_isometry(iso: &Isometry3<T>) -> Self {
        let q = *UnitQuaternion::<T>::from_rotation_matrix(&iso.rotation).quaternion();
        let t = iso.translation.vector;
        let tq = Quaternion::new(t.x(), t.y(), t.z(), T::zero());
        let dual = tq.multiply(&q) * (T::one() / (T::one() + T::one()));
        DualQuaternion { real: q, dual }
    }

    /// Recover the rigid transform represented by this (unit) dual quaternion.
    ///
    /// The rotation is the real part; the translation is recovered from
    /// `2·dual·real*` (taking the vector part).
    pub fn to_isometry(&self) -> Isometry3<T> {
        let real = self.real.normalize().unwrap_or(self.real);
        let rotation = Rotation3::from_quaternion(&UnitQuaternion::from_quaternion(real));
        let tq = self.dual.multiply(&real.conjugate()) * (T::one() + T::one());
        let translation = Translation::new(Vector3::new([
            tq.coords.data[0],
            tq.coords.data[1],
            tq.coords.data[2],
        ]));
        Isometry3::new(translation, rotation)
    }
}

// ===========================================================================
// Screw theory
// ===========================================================================

/// A screw (twist) in `se(3)`, stored as the 6-D spatial motion vector
/// `(ω, v)` where `ω` is the angular part (rotation axis × angle) and `v` is
/// the linear part.
///
/// The [`Screw::exp`] map sends this twist to an [`Isometry3`] via the standard
/// `se(3)` matrix exponential (Lynch–Park convention, active right-handed
/// rotation), and [`Screw::log`] is its inverse.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Screw<T> {
    /// The angular part (axis × angle).
    pub angular: Vector3<T>,
    /// The linear part.
    pub linear: Vector3<T>,
}

impl<T: Scalar + Copy> Screw<T> {
    /// Build a screw from its angular and linear 3-vectors.
    pub fn new(angular: Vector3<T>, linear: Vector3<T>) -> Self {
        Screw { angular, linear }
    }

    /// View the screw as a [`MotionVector`].
    pub fn as_motion(&self) -> MotionVector<T> {
        MotionVector::new(self.angular, self.linear)
    }

    /// The exponential map `exp: se(3) → SE(3)`.
    ///
    /// For `ω = 0` this is a pure translation by `v`; otherwise it is a rotation
    /// by `|ω|` about `ω/|ω|` with the Lynch–Park transported translation.
    pub fn exp(&self) -> Isometry3<T> {
        let w = self.angular;
        let v = self.linear;
        let theta = w.norm();
        let eps = c::<T>(1e-12);
        let rotation = if theta < eps {
            Rotation3::identity()
        } else {
            let axis = w / theta;
            Rotation3::from_axis_angle(&axis, theta)
        };
        let p = if theta < eps {
            v
        } else {
            let axis = w / theta;
            let vl = v / theta;
            let av = axis.cross(&vl); // A·vl
            let aav = axis.cross(&av); // A²·vl
            let (s, cth) = theta.sin_cos();
            let term1 = vl * theta;
            let term2 = av * (T::one() - cth);
            let term3 = aav * (theta - s);
            term1 + term2 + term3
        };
        Isometry3::new(Translation::new(p), rotation)
    }

    /// The logarithmic map `log: SE(3) → se(3)` — the inverse of [`Screw::exp`].
    ///
    /// Recovers the screw `(ω, v)` whose exponential equals `iso`. For a pure
    /// translation this is `(0, translation)`.
    ///
    /// # Numerical singularities
    ///
    /// `log` has two well-known singularities, both guarded here:
    ///
    /// * **`theta ≈ 0` (identity rotation).** Handled by the early-return
    ///   branch — the off-diagonal axis formula divides by `sin(theta)`, which
    ///   vanishes at `theta = 0`.
    /// * **`theta ≈ π` (180° rotation).** The same off-diagonal formula divides
    ///   by `sin(theta)`, which also vanishes at `theta = π`. The angle is taken
    ///   as `atan2(sin θ, cos θ)` with `cos θ = (tr − 1) / 2` and `sin θ = |skew|
    ///   / 2`, which stays in domain under rounding (unlike `acos`, which can
    ///   yield `NaN` near these limits), and the axis is extracted from `(R + I)
    ///   = 2·(w wᵀ)` instead of the off-diagonal differences in the `theta ≈ π`
    ///   regime.
    pub fn log(iso: &Isometry3<T>) -> Screw<T> {
        let m = iso.rotation.matrix().data;
        let tr = m[0][0] + m[1][1] + m[2][2];
        // cos(theta) = (trace - 1) / 2 and sin(theta) = |skew| / 2, where the
        // skew part (R - Rᵀ) has norm 2 sin(theta). theta = atan2(sin, cos) is
        // well-conditioned everywhere and cannot leave its domain, unlike
        // acos near 0 and pi where rounding pushes the argument out of range.
        let cos_t = (tr - T::one()) / two();
        let skew = Vector3::new([m[2][1] - m[1][2], m[0][2] - m[2][0], m[1][0] - m[0][1]]);
        let sin_t = skew.dot(&skew).sqrt() / two();
        let theta = sin_t.atan2(cos_t);
        let eps = c::<T>(1e-12);
        if theta < eps {
            return Screw::new(
                Vector3::new([T::zero(), T::zero(), T::zero()]),
                iso.translation.vector,
            );
        }
        let two_ = two::<T>();
        let pi = c::<T>(core::f64::consts::PI);
        // Angular axis.
        //
        // * For general theta the standard off-diagonal formula
        //   `w = (R - R^T) / (2 sin theta)` is exact and well-conditioned.
        // * Near theta ~= pi that formula divides by sin(theta) -> 0 (the
        //   *second* log singularity) and is catastrophically ill-conditioned.
        //   There we instead take the *direction* from (R + I) = 2 w w^T (exact
        //   at theta = pi, well-conditioned provided no axis component is tiny)
        //   and recover the *sign* from the skew part (R - R^T) = 2 sin(theta)
        //   [w]x, whose sign is unambiguous (sin theta > 0 for theta in (0, pi)).
        let axis = if theta > pi - c::<T>(1e-3) {
            let rpi = [
                [m[0][0] + T::one(), m[0][1], m[0][2]],
                [m[1][0], m[1][1] + T::one(), m[1][2]],
                [m[2][0], m[2][1], m[2][2] + T::one()],
            ];
            let n0 = rpi[0][0] * rpi[0][0] + rpi[1][0] * rpi[1][0] + rpi[2][0] * rpi[2][0];
            let n1 = rpi[0][1] * rpi[0][1] + rpi[1][1] * rpi[1][1] + rpi[2][1] * rpi[2][1];
            let n2 = rpi[0][2] * rpi[0][2] + rpi[1][2] * rpi[1][2] + rpi[2][2] * rpi[2][2];
            let (col, norm) = if n0 >= n1 && n0 >= n2 {
                ([rpi[0][0], rpi[1][0], rpi[2][0]], n0)
            } else if n1 >= n2 {
                ([rpi[0][1], rpi[1][1], rpi[2][1]], n1)
            } else {
                ([rpi[0][2], rpi[1][2], rpi[2][2]], n2)
            };
            let norm = norm.sqrt();
            let norm = if norm == T::zero() { T::one() } else { norm };
            let ax = Vector3::new([col[0] / norm, col[1] / norm, col[2] / norm]);
            if ax.dot(&skew) < T::zero() {
                -ax
            } else {
                ax
            }
        } else {
            let s = sin_t;
            Vector3::new([
                (m[2][1] - m[1][2]) / (two_ * s),
                (m[0][2] - m[2][0]) / (two_ * s),
                (m[1][0] - m[0][1]) / (two_ * s),
            ])
        };
        let p = iso.translation.vector;
        let ap = axis.cross(&p); // A·p
        let aap = axis.cross(&ap); // A²·p
                                   // coef = 1/theta - (1 + cos theta) / (2 sin theta)
                                   //      = 1/theta - (1/2) cot(theta/2).  The half-angle form avoids the
                                   // sin(theta) division (stable across the whole (0, pi) range, including
                                   // the theta ~= pi limit where (1 + cos theta)/(2 sin theta) -> 0).
        let half = theta / two_;
        let cot_half = half.cos() / half.sin();
        let coef = (T::one() / theta) - (cot_half / two_);
        let vl = (p / theta) - (ap * (T::one() / two_)) + (aap * coef);
        let angular = axis * theta;
        let linear = vl * theta;
        Screw::new(angular, linear)
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use tpt_math_geometry::Point3;

    type MVec = MotionVector<f64>;
    type FVec = ForceVector<f64>;

    #[inline]
    fn close(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-10
    }

    fn iso_z90() -> Isometry3<f64> {
        let rot = Rotation3::from_axis_angle(
            &Vector3::new([0.0, 0.0, 1.0]),
            core::f64::consts::FRAC_PI_2,
        );
        Isometry3::new(Translation::new(Vector3::new([0.0, 0.0, 0.0])), rot)
    }

    #[test]
    fn spatial_vector_accessors_and_arithmetic() {
        let a = MVec::new(Vector3::new([1.0, 2.0, 3.0]), Vector3::new([4.0, 5.0, 6.0]));
        assert!(close(a.angular().x(), 1.0));
        assert!(close(a.linear().z(), 6.0));
        let b = MVec::new(Vector3::new([0.0, 0.0, 0.0]), Vector3::new([1.0, 1.0, 1.0]));
        let s = a + b;
        assert!(close(s.linear().x(), 5.0));
        let n = -a;
        assert!(close(n.angular().x(), -1.0));
    }

    #[test]
    fn cross_motion_motion_known() {
        // m = (ω=(0,0,1), v=0), n = (ω=0, v=(1,0,0)).
        // m × n = (0, 0×0 + (0,0,1)×(1,0,0)) = (0, (0,1,0)).
        let m = MVec::new(Vector3::new([0.0, 0.0, 1.0]), Vector3::new([0.0, 0.0, 0.0]));
        let n = MVec::new(Vector3::new([0.0, 0.0, 0.0]), Vector3::new([1.0, 0.0, 0.0]));
        let r = m.cross(&n);
        assert!(close(r.angular().norm(), 0.0));
        assert!(close(r.linear().x(), 0.0));
        assert!(close(r.linear().y(), 1.0));
        assert!(close(r.linear().z(), 0.0));
    }

    #[test]
    fn cross_motion_force_known() {
        // m = (ω=(0,0,1), v=0), f = (n=0, f=(1,0,0)).
        // m × f = (mω×fω + mv×fv, mω×fv) = (0, (0,0,1)×(1,0,0)) = (0, (0,1,0)).
        let m = MVec::new(Vector3::new([0.0, 0.0, 1.0]), Vector3::new([0.0, 0.0, 0.0]));
        let f = FVec::new(Vector3::new([0.0, 0.0, 0.0]), Vector3::new([1.0, 0.0, 0.0]));
        let r = m.cross_force(&f);
        assert!(close(r.angular().norm(), 0.0));
        assert!(close(r.linear().x(), 0.0));
        assert!(close(r.linear().y(), 1.0));
        assert!(close(r.linear().z(), 0.0));
    }

    #[test]
    fn cross_force_force_known() {
        // f = (n=(0,0,1), f=0), g = (n=0, f=(1,0,0)).
        // f × g = ((0,0,1)×(1,0,0) + 0, 0) = ((0,1,0), 0) → motion.
        let f = FVec::new(Vector3::new([0.0, 0.0, 1.0]), Vector3::new([0.0, 0.0, 0.0]));
        let g = FVec::new(Vector3::new([0.0, 0.0, 0.0]), Vector3::new([1.0, 0.0, 0.0]));
        let r = f.cross(&g);
        assert!(close(r.angular().x(), 0.0));
        assert!(close(r.angular().y(), 1.0));
        assert!(close(r.angular().z(), 0.0));
        assert!(close(r.linear().norm(), 0.0));
    }

    #[test]
    fn transform_by_rotation_matches_isometry_vector() {
        let iso = iso_z90();
        // Pure-linear motion (1,0,0) → linear part rotates to (0,1,0), angular to 0.
        let m = MVec::new(Vector3::new([0.0, 0.0, 0.0]), Vector3::new([1.0, 0.0, 0.0]));
        let mt = m.transform_by(&iso);
        assert!(close(mt.angular().norm(), 0.0));
        assert!(close(mt.linear().x(), 0.0));
        assert!(close(mt.linear().y(), 1.0));

        // Angular part should transform like a vector under R.
        let m2 = MVec::new(Vector3::new([1.0, 0.0, 0.0]), Vector3::new([0.0, 0.0, 0.0]));
        let m2t = m2.transform_by(&iso);
        // R applied to (1,0,0) about z by 90° → (0,1,0).
        let expected = iso
            .rotation
            .transform_vector(&Vector3::new([1.0, 0.0, 0.0]));
        assert!(close(m2t.angular().x(), expected.data[0]));
        assert!(close(m2t.angular().y(), expected.data[1]));
        assert!(close(m2t.angular().z(), expected.data[2]));
    }

    #[test]
    fn adjoint_matches_transform() {
        let iso = iso_z90();
        let ad = adjoint_motion(&iso);
        let m = MVec::new(Vector3::new([1.0, 2.0, 3.0]), Vector3::new([4.0, 5.0, 6.0]));
        let via_matrix = MVec {
            data: ad * m.data,
            _marker: PhantomData,
        };
        let via_fn = m.transform_by(&iso);
        for i in 0..6 {
            assert!(
                close(via_matrix.data.data[i], via_fn.data.data[i]),
                "idx {i}"
            );
        }
    }

    #[test]
    fn transform_by_with_translation() {
        // Rotation 90° about Z plus translation (10, 0, 0).
        let rot = Rotation3::from_axis_angle(
            &Vector3::new([0.0, 0.0, 1.0]),
            core::f64::consts::FRAC_PI_2,
        );
        let iso = Isometry3::new(Translation::new(Vector3::new([10.0, 0.0, 0.0])), rot);
        // A force at the origin with linear force (1,0,0) and zero moment.
        // Force adjoint: fω' = R fω + t × (R fv), fv' = R fv.
        let f = FVec::new(Vector3::new([0.0, 0.0, 0.0]), Vector3::new([1.0, 0.0, 0.0]));
        let ft = f.transform_by(&iso);
        let rfv = rot.transform_vector(&Vector3::new([1.0, 0.0, 0.0])); // (0,1,0)
        let expected_top = Vector3::new([10.0, 0.0, 0.0]).cross(&rfv); // t × (R fv)
        assert!(close(ft.angular().x(), expected_top.data[0]));
        assert!(close(ft.angular().y(), expected_top.data[1]));
        assert!(close(ft.angular().z(), expected_top.data[2]));
        assert!(close(ft.linear().x(), 0.0));
        assert!(close(ft.linear().y(), 1.0));
    }

    #[test]
    fn dual_quaternion_roundtrip() {
        let rot = Rotation3::from_axis_angle(
            &Vector3::new([0.0, 0.0, 1.0]),
            core::f64::consts::FRAC_PI_2,
        );
        let iso = Isometry3::new(Translation::new(Vector3::new([1.0, 2.0, 3.0])), rot);
        let dq = DualQuaternion::from_isometry(&iso);
        let back = dq.to_isometry();
        for i in 0..3 {
            for j in 0..3 {
                assert!(
                    close(
                        back.rotation.matrix().data[i][j],
                        iso.rotation.matrix().data[i][j]
                    ),
                    "rot {i},{j}"
                );
            }
            assert!(
                close(
                    back.translation.vector.data[i],
                    iso.translation.vector.data[i]
                ),
                "trans {i}"
            );
        }
    }

    #[test]
    fn dual_quaternion_composition() {
        let r1 = Rotation3::from_axis_angle(
            &Vector3::new([0.0, 0.0, 1.0]),
            core::f64::consts::FRAC_PI_2,
        );
        let iso1 = Isometry3::new(Translation::new(Vector3::new([1.0, 0.0, 0.0])), r1);
        let r2 = Rotation3::from_axis_angle(
            &Vector3::new([0.0, 1.0, 0.0]),
            core::f64::consts::FRAC_PI_3,
        );
        let iso2 = Isometry3::new(Translation::new(Vector3::new([0.0, 2.0, 0.0])), r2);

        let dq1 = DualQuaternion::from_isometry(&iso1);
        let dq2 = DualQuaternion::from_isometry(&iso2);
        let composed_dq = dq1.multiply(&dq2);
        let composed_iso = iso1 * iso2;
        let from_dq = composed_dq.to_isometry();
        for i in 0..3 {
            for j in 0..3 {
                assert!(
                    close(
                        from_dq.rotation.matrix().data[i][j],
                        composed_iso.rotation.matrix().data[i][j]
                    ),
                    "rot {i},{j}"
                );
            }
            assert!(
                close(
                    from_dq.translation.vector.data[i],
                    composed_iso.translation.vector.data[i]
                ),
                "trans {i}"
            );
        }
    }

    #[test]
    fn screw_exp_log_roundtrip() {
        // Random-ish isometry.
        let rot = Rotation3::from_axis_angle(
            &Vector3::new([1.0, 2.0, 3.0]).normalize(),
            core::f64::consts::FRAC_PI_4,
        );
        let iso = Isometry3::new(Translation::new(Vector3::new([0.5, -1.0, 2.0])), rot);
        let screw = Screw::log(&iso);
        let iso2 = screw.exp();
        for i in 0..3 {
            for j in 0..3 {
                assert!(
                    close(
                        iso2.rotation.matrix().data[i][j],
                        iso.rotation.matrix().data[i][j]
                    ),
                    "rot {i},{j}"
                );
            }
            assert!(
                close(
                    iso2.translation.vector.data[i],
                    iso.translation.vector.data[i]
                ),
                "trans {i}"
            );
        }
    }

    #[test]
    fn screw_pure_translation() {
        let iso = Isometry3::new(
            Translation::new(Vector3::new([3.0, -2.0, 1.0])),
            Rotation3::identity(),
        );
        let screw = Screw::log(&iso);
        assert!(close(screw.angular.norm(), 0.0));
        for i in 0..3 {
            assert!(
                close(screw.linear.data[i], iso.translation.vector.data[i]),
                "lin {i}"
            );
        }
        let iso2 = screw.exp();
        for i in 0..3 {
            assert!(
                close(
                    iso2.translation.vector.data[i],
                    iso.translation.vector.data[i]
                ),
                "trans {i}"
            );
        }
    }

    #[test]
    fn screw_exp_log_point_recovery() {
        // exp(log(iso)) must act identically to iso on an arbitrary point.
        let rot = Rotation3::from_axis_angle(
            &Vector3::new([0.3, 1.0, -0.7]).normalize(),
            core::f64::consts::FRAC_PI_3,
        );
        let iso = Isometry3::new(Translation::new(Vector3::new([2.0, 1.0, -3.0])), rot);
        let screw = Screw::log(&iso);
        let iso2 = screw.exp();
        let p = Point3::new(Vector3::new([1.0, -2.0, 0.5]));
        let q1 = iso.transform_point(&p);
        let q2 = iso2.transform_point(&p);
        for i in 0..3 {
            assert!(close(q1.coords.data[i], q2.coords.data[i]), "pt {i}");
        }
    }

    #[test]
    fn screw_composition_identity() {
        // exp(a) * exp(b) exponentiates (as an isometry product) to a transform
        // whose log exponentiates back to itself.
        let a = Screw::new(Vector3::new([0.0, 0.0, 0.1]), Vector3::new([0.2, 0.0, 0.0]));
        let b = Screw::new(Vector3::new([0.1, 0.0, 0.0]), Vector3::new([0.0, 0.3, 0.0]));
        let iso_a = a.exp();
        let iso_b = b.exp();
        let iso_ab = iso_a * iso_b;
        let screw_ab = Screw::log(&iso_ab);
        let iso_ab2 = screw_ab.exp();
        for i in 0..3 {
            for j in 0..3 {
                assert!(
                    close(
                        iso_ab2.rotation.matrix().data[i][j],
                        iso_ab.rotation.matrix().data[i][j]
                    ),
                    "rot {i},{j}"
                );
            }
            assert!(
                close(
                    iso_ab2.translation.vector.data[i],
                    iso_ab.translation.vector.data[i]
                ),
                "trans {i}"
            );
        }
    }

    #[test]
    fn screw_log_180_rotation() {
        // theta = pi is the *second* log singularity: the standard off-diagonal
        // axis formula divides by sin(pi) = 0. log must fall back to the
        // (R + I) = 2 w w^T extraction and recover a clean 180° twist.
        let rot = Rotation3::from_axis_angle(&Vector3::new([0.0, 0.0, 1.0]), core::f64::consts::PI);
        let iso = Isometry3::new(Translation::new(Vector3::new([0.0, 0.0, 0.0])), rot);
        let screw = Screw::log(&iso);
        assert!(close(screw.angular.x(), 0.0));
        assert!(close(screw.angular.y(), 0.0));
        assert!(close(screw.angular.z(), core::f64::consts::PI));
        assert!(close(screw.linear.norm(), 0.0));
        // Round-trips back to the same isometry.
        let iso2 = screw.exp();
        for i in 0..3 {
            for j in 0..3 {
                assert!(
                    close(
                        iso2.rotation.matrix().data[i][j],
                        iso.rotation.matrix().data[i][j]
                    ),
                    "rot {i},{j}"
                );
            }
        }
    }

    #[test]
    fn screw_log_180_rotation_with_translation() {
        // Same singularity, now with a non-trivial translation so the linear
        // part of the screw is also exercised.
        let rot = Rotation3::from_axis_angle(
            &Vector3::new([1.0, 1.0, 1.0]).normalize(),
            core::f64::consts::PI,
        );
        let iso = Isometry3::new(Translation::new(Vector3::new([1.0, -2.0, 0.5])), rot);
        let screw = Screw::log(&iso);
        // Angular magnitude must be pi (to within the rounding inherited from
        // the irrational-axis rotation matrix — its trace is only ~-1, so the
        // recovered angle is ~pi - O(1e-8)). The stricter correctness check is
        // the point-round-trip below.
        assert!((screw.angular.norm() - core::f64::consts::PI).abs() < 1e-7);
        // exp(log(iso)) must reproduce iso's action on a point. At theta ~= pi
        // the log is ill-conditioned (the recovered axis carries an
        // O(pi - theta) error inherited from the rotation matrix), so allow the
        // relaxed ~1e-7 tolerance that the singularity implies rather than 1e-10.
        let iso2 = screw.exp();
        let p = Point3::new(Vector3::new([2.0, -1.0, 3.0]));
        let q1 = iso.transform_point(&p);
        let q2 = iso2.transform_point(&p);
        for i in 0..3 {
            let d = (q1.coords.data[i] - q2.coords.data[i]).abs();
            assert!(d < 1e-7, "pt {i}: diff {d}");
        }
    }

    #[test]
    fn screw_log_small_rotation() {
        // theta ~= 0 is the *first* log singularity. The early-return branch
        // must give a clean small-rotation twist (angular = angle * axis).
        let angle = 1e-6;
        let axis = Vector3::new([1.0, 2.0, 3.0]).normalize();
        let rot = Rotation3::from_axis_angle(&axis, angle);
        let iso = Isometry3::new(Translation::new(Vector3::new([0.0, 0.0, 0.0])), rot);
        let screw = Screw::log(&iso);
        assert!(close(screw.angular.norm(), angle));
        // Axis direction recovered up to the tiny angle's precision.
        let recovered = screw.angular / angle;
        assert!(close(recovered.x(), axis.x()));
        assert!(close(recovered.y(), axis.y()));
        assert!(close(recovered.z(), axis.z()));
    }

    #[test]
    fn screw_small_twist_bch_approx() {
        // For small twists, exp(a) * exp(b) ≈ exp(a + b) up to the (second-order)
        // Baker–Campbell–Hausdorff commutator term, which is O(||a||·||b||).
        let a = Screw::new(
            Vector3::new([0.01, 0.0, 0.0]),
            Vector3::new([0.0, 0.02, 0.0]),
        );
        let b = Screw::new(
            Vector3::new([0.0, 0.01, 0.0]),
            Vector3::new([0.0, 0.0, 0.01]),
        );
        let sum = Screw::new(a.angular + b.angular, a.linear + b.linear);
        let iso_ab = a.exp() * b.exp();
        let iso_sum = sum.exp();
        // Loose tolerance: the first-order approximation error is ~1e-3 here.
        for i in 0..3 {
            let dt: f64 = iso_ab.translation.vector.data[i] - iso_sum.translation.vector.data[i];
            assert!(dt.abs() < 1e-3, "trans {i}");
            for j in 0..3 {
                let dr: f64 =
                    iso_ab.rotation.matrix().data[i][j] - iso_sum.rotation.matrix().data[i][j];
                assert!(dr.abs() < 1e-3, "rot {i},{j}");
            }
        }
    }
}