use ndarray::{Array2, Array3};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layout {
Projection,
Sinogram,
}
#[derive(Clone, Debug)]
pub struct Tomo<T = f32> {
pub array: Array3<T>,
pub layout: Layout,
}
impl<T: Clone> Tomo<T> {
pub fn new(array: Array3<T>, layout: Layout) -> Self {
Self { array, layout }
}
pub fn n_angles(&self) -> usize {
match self.layout {
Layout::Projection => self.array.shape()[0],
Layout::Sinogram => self.array.shape()[1],
}
}
pub fn n_rows(&self) -> usize {
match self.layout {
Layout::Projection => self.array.shape()[1],
Layout::Sinogram => self.array.shape()[0],
}
}
pub fn n_cols(&self) -> usize {
self.array.shape()[2]
}
pub fn to_layout(&self, target: Layout) -> Tomo<T> {
let array = if self.layout == target {
self.array.as_standard_layout().into_owned()
} else {
self.array
.view()
.permuted_axes([1, 0, 2])
.as_standard_layout()
.into_owned()
};
Tomo {
array,
layout: target,
}
}
pub fn as_layout(&self, target: Layout) -> std::borrow::Cow<'_, Tomo<T>> {
if self.layout == target {
std::borrow::Cow::Borrowed(self)
} else {
std::borrow::Cow::Owned(self.to_layout(target))
}
}
}
#[derive(Clone, Debug)]
pub struct Volume<T = f32> {
pub array: Array3<T>,
}
impl<T> Volume<T> {
pub fn new(array: Array3<T>) -> Self {
Self { array }
}
pub fn dims(&self) -> (usize, usize, usize) {
let s = self.array.shape();
(s[0], s[1], s[2])
}
}
pub type Slice2D<T = f32> = Array2<T>;
#[derive(Clone, Debug)]
pub struct Frames<T = f32> {
pub array: Array3<T>,
}
impl<T> Frames<T> {
pub fn new(array: Array3<T>) -> Self {
Self { array }
}
pub fn count(&self) -> usize {
self.array.shape()[0]
}
}
#[derive(Clone, Debug)]
pub struct Dataset<T = f32> {
pub data: Tomo<T>,
pub flat: Option<Frames<T>>,
pub dark: Option<Frames<T>>,
pub theta: Vec<f32>,
}
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::Cow;
#[test]
fn as_layout_borrows_when_matching_and_transposes_otherwise() {
let a = Array3::from_shape_fn((2, 3, 4), |(i, j, k)| (i * 100 + j * 10 + k) as f32);
let t = Tomo::new(a.clone(), Layout::Projection);
let same = t.as_layout(Layout::Projection);
assert!(matches!(same, Cow::Borrowed(_)));
assert_eq!(same.array, a);
let swapped = t.as_layout(Layout::Sinogram);
assert!(matches!(swapped, Cow::Owned(_)));
assert_eq!(swapped.layout, Layout::Sinogram);
assert_eq!(swapped.array.dim(), (3, 2, 4));
assert_eq!(swapped.array[[1, 0, 2]], a[[0, 1, 2]]);
assert_eq!(swapped.array, t.to_layout(Layout::Sinogram).array);
assert!(
swapped.array.as_slice().is_some(),
"transposed sinogram must be C-contiguous for as_slice()"
);
}
}