1use coeus_autograd::{
4 add as add_variables, broadcast_to as broadcast_variable, cat as cat_variables, cos,
5 matmul as matmul_variables, mul as mul_variables, neg as neg_variable, reshape, sin, slice,
6 sub as sub_variables, transpose_2d, Var,
7};
8use coeus_core::{Backend, CpuAddressableStorage, CpuAddressableStorageMut};
9use coeus_nn::Module;
10use coeus_ops::{add, broadcast_to, cat, matmul, sub, BackendOps};
11use ritk_core::spatial::{Direction, Point, Spacing};
12use ritk_core::transform::{Resampleable, Transform};
13use ritk_image::tensor::Tensor;
14
15#[derive(Clone)]
20pub struct RigidTransform<B: Backend + BackendOps<f32>, const D: usize> {
21 translation: Var<f32, B>,
22 rotation: Var<f32, B>,
23 center: Var<f32, B>,
24}
25
26impl<B: Backend + BackendOps<f32> + Default, const D: usize> RigidTransform<B, D>
27where
28 B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
29{
30 #[must_use]
37 pub fn new(
38 translation: Tensor<f32, B>,
39 rotation: Tensor<f32, B>,
40 center: Tensor<f32, B>,
41 ) -> Self {
42 assert!(
43 (1..=4).contains(&D),
44 "rigid transform supports dimensions 1 through 4"
45 );
46 assert_eq!(
47 translation.shape(),
48 [D],
49 "rigid translation must have shape [{D}]"
50 );
51 assert_eq!(center.shape(), [D], "rigid center must have shape [{D}]");
52 let angles = if D == 3 { 3 } else { 1 };
53 assert_eq!(
54 rotation.shape(),
55 [angles],
56 "rigid rotation must have shape [{angles}] for dimension {D}"
57 );
58 Self {
59 translation: Var::new(translation, true),
60 rotation: Var::new(rotation, true),
61 center: Var::new(center, false),
62 }
63 }
64
65 #[must_use]
67 pub fn identity(center: Option<Tensor<f32, B>>, backend: &B) -> Self {
68 Self::new(
69 Tensor::zeros_on([D], backend),
70 Tensor::zeros_on([if D == 3 { 3 } else { 1 }], backend),
71 center.unwrap_or_else(|| Tensor::zeros_on([D], backend)),
72 )
73 }
74
75 #[must_use]
77 pub fn translation(&self) -> Tensor<f32, B> {
78 self.translation.tensor.clone()
79 }
80
81 #[must_use]
83 pub fn rotation(&self) -> Tensor<f32, B> {
84 self.rotation.tensor.clone()
85 }
86
87 #[must_use]
89 pub fn center(&self) -> Tensor<f32, B> {
90 self.center.tensor.clone()
91 }
92
93 #[must_use]
95 pub fn matrix(&self) -> Tensor<f32, B> {
96 let backend = B::default();
97 let rotation = self.build_rotation_matrix();
98 let rotated_center =
99 matmul(&rotation, &self.center.tensor.reshape([D, 1]), &backend).reshape([D]);
100 let translated_center = add(&self.translation.tensor, &self.center.tensor, &backend);
101 let offset = sub(&translated_center, &rotated_center, &backend).reshape([D, 1]);
102 let top = cat(&[&rotation, &offset], 1);
103 let mut bottom = vec![0.0; D + 1];
104 bottom[D] = 1.0;
105 let bottom = Tensor::from_slice_on([1, D + 1], &bottom, &backend);
106 cat(&[&top, &bottom], 0)
107 }
108
109 #[must_use]
111 pub fn build_rotation_matrix(&self) -> Tensor<f32, B> {
112 self.rotation_matrix_variables().tensor
113 }
114
115 #[must_use]
117 pub fn transform_variables(&self, points: &Var<f32, B>) -> Var<f32, B> {
118 let shape = points.tensor.shape();
119 assert!(
120 shape.len() == 2 && shape[1] == D,
121 "rigid transform requires points shaped [N, {D}], got {shape:?}"
122 );
123 let target = vec![shape[0], D];
124 let center = broadcast_variable(&reshape(&self.center, [1, D]), target.clone());
125 let translation = broadcast_variable(&reshape(&self.translation, [1, D]), target);
126 let centered = sub_variables(points, ¢er);
127 let rotated = matmul_variables(¢ered, &transpose_2d(&self.rotation_matrix_variables()));
128 add_variables(&add_variables(&rotated, ¢er), &translation)
129 }
130
131 fn rotation_matrix_variables(&self) -> Var<f32, B> {
132 if D == 3 {
133 let x = slice(&self.rotation, &[(0, 1)]);
134 let y = slice(&self.rotation, &[(1, 2)]);
135 let z = slice(&self.rotation, &[(2, 3)]);
136 let (cx, sx) = (cos(&x), sin(&x));
137 let (cy, sy) = (cos(&y), sin(&y));
138 let (cz, sz) = (cos(&z), sin(&z));
139
140 let r11 = mul_variables(&cz, &cy);
141 let r12 = sub_variables(
142 &mul_variables(&mul_variables(&cz, &sy), &sx),
143 &mul_variables(&sz, &cx),
144 );
145 let r13 = add_variables(
146 &mul_variables(&mul_variables(&cz, &sy), &cx),
147 &mul_variables(&sz, &sx),
148 );
149 let r21 = mul_variables(&sz, &cy);
150 let r22 = add_variables(
151 &mul_variables(&mul_variables(&sz, &sy), &sx),
152 &mul_variables(&cz, &cx),
153 );
154 let r23 = sub_variables(
155 &mul_variables(&mul_variables(&sz, &sy), &cx),
156 &mul_variables(&cz, &sx),
157 );
158 let r31 = neg_variable(&sy);
159 let r32 = mul_variables(&cy, &sx);
160 let r33 = mul_variables(&cy, &cx);
161 matrix_from_rows(&[[&r11, &r12, &r13], [&r21, &r22, &r23], [&r31, &r32, &r33]])
162 } else if D == 2 {
163 let angle = slice(&self.rotation, &[(0, 1)]);
164 let cosine = cos(&angle);
165 let sine = sin(&angle);
166 let negative_sine = neg_variable(&sine);
167 matrix_from_rows(&[[&cosine, &negative_sine], [&sine, &cosine]])
168 } else {
169 Var::new(Tensor::eye_on(D, &B::default()), false)
170 }
171 }
172}
173
174pub(super) fn matrix_from_rows<T, B, const D: usize>(rows: &[[&Var<T, B>; D]; D]) -> Var<T, B>
175where
176 T: coeus_core::Scalar,
177 B: Backend + BackendOps<T> + Default,
178 B::DeviceBuffer<T>: CpuAddressableStorage<T> + CpuAddressableStorageMut<T>,
179{
180 let rows = rows
181 .iter()
182 .map(|row| {
183 let cells = row
184 .iter()
185 .map(|cell| reshape(cell, [1, 1]))
186 .collect::<Vec<_>>();
187 let references = cells.iter().collect::<Vec<_>>();
188 cat_variables(&references, 1)
189 })
190 .collect::<Vec<_>>();
191 let references = rows.iter().collect::<Vec<_>>();
192 cat_variables(&references, 0)
193}
194
195impl<B: Backend + BackendOps<f32> + Default, const D: usize> Transform<B, D>
196 for RigidTransform<B, D>
197where
198 B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
199{
200 fn transform_points(&self, points: Tensor<f32, B>) -> Tensor<f32, B> {
201 let shape = points.shape();
202 assert!(
203 shape.len() == 2 && shape[1] == D,
204 "rigid transform requires points shaped [N, {D}], got {shape:?}"
205 );
206 let backend = B::default();
207 let target = [shape[0], D];
208 let center = broadcast_to(&self.center.tensor.reshape([1, D]), &target, &backend);
209 let translation = broadcast_to(&self.translation.tensor.reshape([1, D]), &target, &backend);
210 let centered = sub(&points, ¢er, &backend);
211 let rotated = matmul(¢ered, &self.build_rotation_matrix().t(), &backend);
212 add(&add(&rotated, ¢er, &backend), &translation, &backend)
213 }
214}
215
216impl<B: Backend + BackendOps<f32>, const D: usize> Resampleable<B, D> for RigidTransform<B, D> {
217 fn resample(
218 &self,
219 _shape: [usize; D],
220 _origin: Point<D>,
221 _spacing: Spacing<D>,
222 _direction: Direction<D>,
223 ) -> Self {
224 self.clone()
225 }
226}
227
228impl<B: Backend + BackendOps<f32> + Default, const D: usize> Module<f32, B> for RigidTransform<B, D>
229where
230 B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
231{
232 fn parameters(&self) -> Vec<Var<f32, B>> {
233 vec![self.translation.clone(), self.rotation.clone()]
234 }
235
236 fn named_parameters(&self) -> Vec<coeus_autograd::Parameter<f32, B>> {
237 vec![
238 coeus_autograd::Parameter::new(self.translation.clone(), "translation"),
239 coeus_autograd::Parameter::new(self.rotation.clone(), "rotation"),
240 ]
241 }
242
243 fn forward(
244 &self,
245 input: &Var<f32, B>,
246 ) -> Result<Var<f32, B>, coeus_nn::ModuleError<<B as coeus_core::ComputeBackend>::Error>> {
247 Ok(self.transform_variables(input))
248 }
249
250 fn load_parameters(&mut self, parameters: &[Var<f32, B>]) {
251 assert_eq!(
252 parameters.len(),
253 2,
254 "invariant: rigid transform owns translation and rotation parameters"
255 );
256 self.translation = parameters[0].clone();
257 self.rotation = parameters[1].clone();
258 }
259}
260
261#[cfg(test)]
262#[path = "tests_rigid.rs"]
263mod tests;