Skip to main content

ritk_transform/transform/displacement_field/
resample.rs

1use super::core::{DisplacementField, DisplacementFieldError};
2use coeus_autograd::{reshape, Var};
3use coeus_core::{Backend, CpuAddressableStorage, CpuAddressableStorageMut};
4use coeus_ops::{BackendOps, Dimension, InterpolationError, SupportedDimension};
5use coeus_tensor::Tensor;
6use ritk_core::spatial::{Direction, Point, Spacing};
7
8use super::geometry::physical_grid;
9
10/// Resampling failure for a trainable displacement field.
11#[derive(Debug, thiserror::Error)]
12pub enum ResampleError {
13    /// Interpolation rejected the field or coordinate grid.
14    #[error(transparent)]
15    Interpolation(#[from] InterpolationError),
16    /// The reconstructed field violated a construction invariant.
17    #[error(transparent)]
18    Field(#[from] DisplacementFieldError),
19}
20
21impl<B: Backend + BackendOps<f32>, const D: usize> DisplacementField<B, D>
22where
23    Dimension<D>: SupportedDimension,
24    B::DeviceBuffer<f32>: CpuAddressableStorage<f32> + CpuAddressableStorageMut<f32>,
25{
26    /// Resample the field onto a new regular physical grid.
27    pub fn resample(
28        &self,
29        new_shape: [usize; D],
30        new_origin: Point<D>,
31        new_spacing: Spacing<D>,
32        new_direction: Direction<D>,
33    ) -> Result<Self, ResampleError> {
34        let points = physical_grid(new_shape, new_origin, new_spacing, new_direction)?;
35        let points = Var::new(
36            Tensor::from_slice_on([points.len() / D, D], &points, &B::default()),
37            false,
38        );
39        let components = self
40            .sample_components(&points, coeus_ops::Replicate)?
41            .iter()
42            .map(|sampled| reshape(sampled, new_shape).tensor)
43            .collect::<Vec<_>>();
44        Ok(Self::new(
45            components,
46            new_origin,
47            new_spacing,
48            new_direction,
49        )?)
50    }
51}