Skip to main content

ritk_transform/transform/affine/
translation.rs

1//! Trainable translation transform.
2
3use coeus_autograd::{add as add_variables, broadcast_to as broadcast_variable, reshape, Var};
4use coeus_core::{Backend, CpuAddressableStorage, CpuAddressableStorageMut};
5use coeus_nn::Module;
6use coeus_ops::{add, broadcast_to, BackendOps};
7use ritk_core::spatial::{Direction, Point, Spacing};
8use ritk_core::transform::{Resampleable, Transform};
9use ritk_image::tensor::Tensor;
10
11/// Translation by one trainable `[D]` offset vector.
12#[derive(Clone)]
13pub struct TranslationTransform<B: Backend + BackendOps<f32>, const D: usize> {
14    translation: Var<f32, B>,
15}
16
17impl<B: Backend + BackendOps<f32>, const D: usize> TranslationTransform<B, D> {
18    /// Construct a trainable translation parameter.
19    ///
20    /// # Panics
21    ///
22    /// Panics when `translation` is not shaped `[D]`.
23    #[must_use]
24    pub fn new(translation: Tensor<f32, B>) -> Self {
25        assert_eq!(
26            translation.shape(),
27            [D],
28            "translation parameter must have shape [{D}]"
29        );
30        Self {
31            translation: Var::new(translation, true),
32        }
33    }
34
35    /// Clone the current translation tensor.
36    #[must_use]
37    pub fn translation(&self) -> Tensor<f32, B> {
38        self.translation.tensor.clone()
39    }
40
41    /// Apply the translation while retaining the Coeus autograd graph.
42    ///
43    /// # Panics
44    ///
45    /// Panics when `points` is not shaped `[N, D]`.
46    #[must_use]
47    pub fn transform_variables(&self, points: &Var<f32, B>) -> Var<f32, B>
48    where
49        B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
50    {
51        let shape = points.tensor.shape();
52        assert!(
53            shape.len() == 2 && shape[1] == D,
54            "translation transform requires points shaped [N, {D}], got {shape:?}"
55        );
56        let translation = reshape(&self.translation, [1, D]);
57        add_variables(points, &broadcast_variable(&translation, vec![shape[0], D]))
58    }
59}
60
61impl<B: Backend + BackendOps<f32> + Default, const D: usize> Transform<B, D>
62    for TranslationTransform<B, D>
63where
64    B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
65{
66    fn transform_points(&self, points: Tensor<f32, B>) -> Tensor<f32, B> {
67        let shape = points.shape();
68        assert!(
69            shape.len() == 2 && shape[1] == D,
70            "translation transform requires points shaped [N, {D}], got {shape:?}"
71        );
72        let backend = B::default();
73        let translation = self.translation.tensor.reshape([1, D]);
74        let translated = broadcast_to(&translation, &[shape[0], D], &backend);
75        add(&points, &translated, &backend)
76    }
77}
78
79impl<B: Backend + BackendOps<f32>, const D: usize> Resampleable<B, D>
80    for TranslationTransform<B, D>
81{
82    fn resample(
83        &self,
84        _shape: [usize; D],
85        _origin: Point<D>,
86        _spacing: Spacing<D>,
87        _direction: Direction<D>,
88    ) -> Self {
89        self.clone()
90    }
91}
92
93impl<B: Backend + BackendOps<f32> + Default, const D: usize> Module<f32, B>
94    for TranslationTransform<B, D>
95where
96    B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
97{
98    fn parameters(&self) -> Vec<Var<f32, B>> {
99        vec![self.translation.clone()]
100    }
101
102    fn named_parameters(&self) -> Vec<coeus_autograd::Parameter<f32, B>> {
103        vec![coeus_autograd::Parameter::new(
104            self.translation.clone(),
105            "translation",
106        )]
107    }
108
109    fn forward(
110        &self,
111        input: &Var<f32, B>,
112    ) -> Result<Var<f32, B>, coeus_nn::ModuleError<<B as coeus_core::ComputeBackend>::Error>> {
113        Ok(self.transform_variables(input))
114    }
115
116    fn load_parameters(&mut self, parameters: &[Var<f32, B>]) {
117        assert_eq!(
118            parameters.len(),
119            1,
120            "invariant: translation transform owns one parameter"
121        );
122        self.translation = parameters[0].clone();
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use coeus_core::SequentialBackend;
130
131    #[test]
132    fn translates_every_point() {
133        let backend = SequentialBackend;
134        let translation = Tensor::<f32, _>::from_slice_on([3], &[1.0, 2.0, 3.0], &backend);
135        let transform = TranslationTransform::<SequentialBackend, 3>::new(translation);
136        let points =
137            Tensor::<f32, _>::from_slice_on([2, 3], &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], &backend);
138
139        let transformed = transform.transform_points(points);
140
141        assert_eq!(transformed.as_slice(), &[1.0, 2.0, 3.0, 2.0, 3.0, 4.0]);
142    }
143}