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                .expect("translation transform requires backend evaluation to succeed"),
33        }
34    }
35
36    /// Clone the current translation tensor.
37    #[must_use]
38    pub fn translation(&self) -> Tensor<f32, B> {
39        self.translation.tensor.clone()
40    }
41
42    /// Apply the translation while retaining the Coeus autograd graph.
43    ///
44    /// # Panics
45    ///
46    /// Panics when `points` is not shaped `[N, D]`.
47    #[must_use]
48    pub fn transform_variables(&self, points: &Var<f32, B>) -> Var<f32, B>
49    where
50        B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
51    {
52        let shape = points.tensor.shape();
53        assert!(
54            shape.len() == 2 && shape[1] == D,
55            "translation transform requires points shaped [N, {D}], got {shape:?}"
56        );
57        let translation = reshape(&self.translation, [1, D])
58            .expect("translation transform requires backend evaluation to succeed");
59        let broadcast_translation = broadcast_variable(&translation, vec![shape[0], D])
60            .expect("translation transform requires backend evaluation to succeed");
61        add_variables(points, &broadcast_translation)
62            .expect("translation transform requires backend evaluation to succeed")
63    }
64}
65
66impl<B: Backend + BackendOps<f32> + Default, const D: usize> Transform<B, D>
67    for TranslationTransform<B, D>
68where
69    B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
70{
71    fn transform_points(&self, points: Tensor<f32, B>) -> Tensor<f32, B> {
72        let shape = points.shape();
73        assert!(
74            shape.len() == 2 && shape[1] == D,
75            "translation transform requires points shaped [N, {D}], got {shape:?}"
76        );
77        let backend = B::default();
78        let translation = self.translation.tensor.reshape([1, D]);
79        let translated = broadcast_to(&translation, &[shape[0], D], &backend)
80            .expect("translation transform requires backend evaluation to succeed");
81        add(&points, &translated, &backend)
82            .expect("translation transform requires backend evaluation to succeed")
83    }
84}
85
86impl<B: Backend + BackendOps<f32>, const D: usize> Resampleable<B, D>
87    for TranslationTransform<B, D>
88{
89    fn resample(
90        &self,
91        _shape: [usize; D],
92        _origin: Point<D>,
93        _spacing: Spacing<D>,
94        _direction: Direction<D>,
95    ) -> Self {
96        self.clone()
97    }
98}
99
100impl<B: Backend + BackendOps<f32> + Default, const D: usize> Module<f32, B>
101    for TranslationTransform<B, D>
102where
103    B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
104{
105    fn parameters(&self) -> Vec<Var<f32, B>> {
106        vec![self.translation.clone()]
107    }
108
109    fn named_parameters(&self) -> Vec<coeus_autograd::Parameter<f32, B>> {
110        vec![coeus_autograd::Parameter::new(
111            self.translation.clone(),
112            "translation",
113        )]
114    }
115
116    fn forward(
117        &self,
118        input: &Var<f32, B>,
119    ) -> Result<Var<f32, B>, coeus_nn::ModuleError<<B as coeus_core::ComputeBackend>::Error>> {
120        Ok(self.transform_variables(input))
121    }
122
123    fn load_parameters(&mut self, parameters: &[Var<f32, B>]) {
124        assert_eq!(
125            parameters.len(),
126            1,
127            "invariant: translation transform owns one parameter"
128        );
129        self.translation = parameters[0].clone();
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use coeus_core::SequentialBackend;
137
138    #[test]
139    fn translates_every_point() {
140        let backend = SequentialBackend;
141        let translation = Tensor::<f32, _>::from_slice_on([3], &[1.0, 2.0, 3.0], &backend)
142            .expect("test tensor is valid");
143        let transform = TranslationTransform::<SequentialBackend, 3>::new(translation);
144        let points =
145            Tensor::<f32, _>::from_slice_on([2, 3], &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], &backend)
146                .expect("test tensor is valid");
147
148        let transformed = transform.transform_points(points);
149
150        assert_eq!(transformed.as_slice(), &[1.0, 2.0, 3.0, 2.0, 3.0, 4.0]);
151    }
152}