Skip to main content

ritk_transform/transform/affine/
affine.rs

1//! Trainable affine transform.
2
3use coeus_autograd::{
4    add as add_variables, broadcast_to as broadcast_variable, matmul as matmul_variables, reshape,
5    sub as sub_variables, transpose_2d, Var,
6};
7use coeus_core::{Backend, CpuAddressableStorage, CpuAddressableStorageMut};
8use coeus_nn::Module;
9use coeus_ops::{add, broadcast_to, matmul, sub, BackendOps};
10use ritk_core::spatial::{Direction, Point, Spacing};
11use ritk_core::transform::{Resampleable, Transform};
12use ritk_image::tensor::Tensor;
13
14/// Trainable affine map `T(x) = A(x - c) + c + t`.
15#[derive(Clone)]
16pub struct AffineTransform<B: Backend + BackendOps<f32>, const D: usize> {
17    matrix: Var<f32, B>,
18    translation: Var<f32, B>,
19    center: Var<f32, B>,
20}
21
22impl<B: Backend + BackendOps<f32>, const D: usize> AffineTransform<B, D> {
23    /// Construct a trainable affine map with a fixed center.
24    ///
25    /// # Panics
26    ///
27    /// Panics unless the tensors have shapes `[D, D]`, `[D]`, and `[D]`.
28    #[must_use]
29    pub fn new(
30        matrix: Tensor<f32, B>,
31        translation: Tensor<f32, B>,
32        center: Tensor<f32, B>,
33    ) -> Self {
34        assert_eq!(
35            matrix.shape(),
36            [D, D],
37            "affine matrix must have shape [{D}, {D}]"
38        );
39        assert_eq!(
40            translation.shape(),
41            [D],
42            "affine translation must have shape [{D}]"
43        );
44        assert_eq!(center.shape(), [D], "affine center must have shape [{D}]");
45        Self {
46            matrix: Var::new(matrix, true),
47            translation: Var::new(translation, true),
48            center: Var::new(center, false),
49        }
50    }
51
52    /// Construct the identity map on `backend`.
53    #[must_use]
54    pub fn identity(center: Option<Tensor<f32, B>>, backend: &B) -> Self {
55        let mut values = vec![0.0; D * D];
56        for axis in 0..D {
57            values[axis * D + axis] = 1.0;
58        }
59        Self::new(
60            Tensor::from_slice_on([D, D], &values, backend),
61            Tensor::zeros_on([D], backend),
62            center.unwrap_or_else(|| Tensor::zeros_on([D], backend)),
63        )
64    }
65
66    /// Clone the current linear map.
67    #[must_use]
68    pub fn matrix(&self) -> Tensor<f32, B> {
69        self.matrix.tensor.clone()
70    }
71
72    /// Clone the current translation.
73    #[must_use]
74    pub fn translation(&self) -> Tensor<f32, B> {
75        self.translation.tensor.clone()
76    }
77
78    /// Clone the fixed center.
79    #[must_use]
80    pub fn center(&self) -> Tensor<f32, B> {
81        self.center.tensor.clone()
82    }
83
84    /// Apply the map while retaining the Coeus autograd graph.
85    ///
86    /// # Panics
87    ///
88    /// Panics when `points` is not shaped `[N, D]`.
89    #[must_use]
90    pub fn transform_variables(&self, points: &Var<f32, B>) -> Var<f32, B>
91    where
92        B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
93    {
94        let shape = points.tensor.shape();
95        assert!(
96            shape.len() == 2 && shape[1] == D,
97            "affine transform requires points shaped [N, {D}], got {shape:?}"
98        );
99        let target = vec![shape[0], D];
100        let center = broadcast_variable(&reshape(&self.center, [1, D]), target.clone());
101        let translation = broadcast_variable(&reshape(&self.translation, [1, D]), target);
102        let centered = sub_variables(points, &center);
103        let linear = matmul_variables(&centered, &transpose_2d(&self.matrix));
104        add_variables(&add_variables(&linear, &center), &translation)
105    }
106}
107
108impl<B: Backend + BackendOps<f32> + Default, const D: usize> Transform<B, D>
109    for AffineTransform<B, D>
110where
111    B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
112{
113    fn transform_points(&self, points: Tensor<f32, B>) -> Tensor<f32, B> {
114        let shape = points.shape();
115        assert!(
116            shape.len() == 2 && shape[1] == D,
117            "affine transform requires points shaped [N, {D}], got {shape:?}"
118        );
119        let backend = B::default();
120        let target = [shape[0], D];
121        let center = broadcast_to(&self.center.tensor.reshape([1, D]), &target, &backend);
122        let translation = broadcast_to(&self.translation.tensor.reshape([1, D]), &target, &backend);
123        let centered = sub(&points, &center, &backend);
124        let linear = matmul(&centered, &self.matrix.tensor.t(), &backend);
125        add(&add(&linear, &center, &backend), &translation, &backend)
126    }
127}
128
129impl<B: Backend + BackendOps<f32>, const D: usize> Resampleable<B, D> for AffineTransform<B, D> {
130    fn resample(
131        &self,
132        _shape: [usize; D],
133        _origin: Point<D>,
134        _spacing: Spacing<D>,
135        _direction: Direction<D>,
136    ) -> Self {
137        self.clone()
138    }
139}
140
141impl<B: Backend + BackendOps<f32> + Default, const D: usize> Module<f32, B>
142    for AffineTransform<B, D>
143where
144    B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
145{
146    fn parameters(&self) -> Vec<Var<f32, B>> {
147        vec![self.matrix.clone(), self.translation.clone()]
148    }
149
150    fn named_parameters(&self) -> Vec<coeus_autograd::Parameter<f32, B>> {
151        vec![
152            coeus_autograd::Parameter::new(self.matrix.clone(), "matrix"),
153            coeus_autograd::Parameter::new(self.translation.clone(), "translation"),
154        ]
155    }
156
157    fn forward(
158        &self,
159        input: &Var<f32, B>,
160    ) -> Result<Var<f32, B>, coeus_nn::ModuleError<<B as coeus_core::ComputeBackend>::Error>> {
161        Ok(self.transform_variables(input))
162    }
163
164    fn load_parameters(&mut self, parameters: &[Var<f32, B>]) {
165        assert_eq!(
166            parameters.len(),
167            2,
168            "invariant: affine transform owns matrix and translation parameters"
169        );
170        self.matrix = parameters[0].clone();
171        self.translation = parameters[1].clone();
172    }
173}
174
175#[cfg(test)]
176#[path = "tests_affine.rs"]
177mod tests;