Skip to main content

ritk_transform/transform/affine/
scale.rs

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