use std::borrow::Cow;
use std::path::{Path, PathBuf};
use ndarray::{Array3, Axis};
use rayon::prelude::*;
use crate::backend::Backend;
use crate::cuda::LaminoTileFn;
use crate::data::{Layout, Tomo};
use crate::error::{Error, Result};
use crate::geometry::{Angles, Beam, Center, Detector, Geometry};
use crate::params::{Algorithm, ReconParams};
use crate::pipeline::{CancelToken, PrepOptions};
use crate::recon::center::{RingCenter, SampleBand, TiltCandidates, TiltFocus, TiltViews};
use crate::recon::tilt_flow::TiltFlow;
pub struct PreppedStack {
path: PathBuf,
data: Tomo<f32>,
theta: Vec<f32>,
nproj: usize,
nz: usize,
nx: usize,
}
pub struct CenterSweep {
pub slice: usize,
pub frames: Array3<f32>,
pub focus: Vec<f64>,
}
impl PreppedStack {
pub fn load(backend: &dyn Backend, path: &Path) -> Result<Self> {
let mut reader = crate::io::open_dxchange(&path.to_string_lossy())?;
let theta = reader.read_theta()?;
let mut ds = reader.read_all()?;
crate::prep::normalize_dataset(&mut ds, backend)?;
let (nproj, nz, nx) = ds.data.as_layout(Layout::Projection).array.dim();
Ok(PreppedStack {
path: path.to_path_buf(),
data: ds.data,
theta,
nproj,
nz,
nx,
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn data(&self) -> &Tomo<f32> {
&self.data
}
pub fn shape(&self) -> (usize, usize, usize) {
(self.nproj, self.nz, self.nx)
}
pub fn bytes(&self) -> usize {
self.data.array.len() * std::mem::size_of::<f32>()
}
pub fn select(&self, indices: &[usize]) -> Result<PreppedStack> {
if let Some(&i) = indices.iter().find(|&&i| i >= self.nproj) {
return Err(Error::InvalidParam(format!(
"projection {i} out of range (nproj {})",
self.nproj
)));
}
let proj = self.data.as_layout(Layout::Projection);
Ok(PreppedStack {
path: self.path.clone(),
data: Tomo::new(proj.array.select(Axis(0), indices), Layout::Projection),
theta: indices.iter().map(|&i| self.theta[i]).collect(),
nproj: indices.len(),
nz: self.nz,
nx: self.nx,
})
}
pub fn moved(
&self,
backend: &dyn Backend,
dy: &[f32],
dx: &[f32],
roll_deg: f32,
) -> Result<PreppedStack> {
let mut proj = self.data.to_layout(Layout::Projection);
proj.array
.as_slice_mut()
.expect("to_layout is standard")
.par_iter_mut()
.for_each(|p| *p = (-*p).exp());
crate::prep::alignment::move_frames(&mut proj, dy, dx, roll_deg)?;
crate::prep::minus_log(&mut proj, backend)?;
Ok(PreppedStack {
path: self.path.clone(),
data: proj,
theta: self.theta.clone(),
nproj: self.nproj,
nz: self.nz,
nx: self.nx,
})
}
pub fn reconstruct(
&self,
backend: &dyn Backend,
geom: &Geometry,
algorithm: Algorithm,
params: &ReconParams,
prep: &PrepOptions,
on_tile: &mut LaminoTileFn,
) -> Result<(usize, usize, usize)> {
crate::pipeline::lamino_streaming_normalized(
Cow::Borrowed(&self.data),
geom,
algorithm,
params,
prep,
backend,
on_tile,
)
}
pub fn geometry(&self, center: f32, tilt_deg: Option<f32>) -> Geometry {
Geometry {
angles: Angles(self.theta.clone()),
center: Center::Scalar(center),
beam: match tilt_deg {
Some(d) => Beam::laminography(d),
None => Beam::Parallel,
},
detector: Detector {
width: self.nx,
height: self.nz,
pixel_size: 1.0,
},
}
}
pub fn depth(&self, tilt_deg: Option<f32>) -> usize {
match tilt_deg {
Some(d) => crate::cuda::lamino_recon_height(self.nz, d),
None => self.nz,
}
}
pub fn default_slice(&self, tilt_deg: Option<f32>, band: Option<(usize, usize)>) -> usize {
crate::recon::center::middle_slice(band, self.depth(tilt_deg))
}
pub fn rings(&self, backend: &dyn Backend, step: usize) -> Result<RingCenter> {
crate::recon::center::find_center_rings(&self.data, backend, step)
}
pub fn tilt_flow(&self, backend: &dyn Backend) -> Result<TiltFlow> {
crate::recon::tilt_flow::estimate_tilt_flow(&self.data, &self.theta, backend)
}
pub fn center_sweep(
&self,
tilt_deg: Option<f32>,
slice: usize,
centers: &[f32],
cancel: Option<&CancelToken>,
) -> Result<CenterSweep> {
let frames = crate::cuda::center_probe_sweep(
&self.data,
&self.geometry(self.nx as f32 / 2.0, tilt_deg),
&ReconParams::default(),
centers,
slice as i32,
cancel,
)?;
let focus = crate::recon::center::focus_by_z(frames.view());
Ok(CenterSweep {
slice,
frames,
focus,
})
}
pub fn tilt_scan(
&self,
center: f32,
tilts_deg: &[f32],
band: Option<SampleBand>,
cancel: Option<&CancelToken>,
on_tilt: &mut dyn FnMut(&TiltFocus, TiltViews<'_>) -> Result<()>,
) -> Result<Vec<TiltFocus>> {
crate::recon::center::lamino_tilt_scan(
&self.data,
&self.geometry(center, Some(0.0)), Algorithm::Fourierrec,
&ReconParams::default(),
TiltCandidates { tilts_deg, band },
cancel,
on_tilt,
)
}
}
pub fn grid(center: f32, half_width: f32, step: f32) -> Vec<f32> {
if step <= 0.0 || half_width < 0.0 {
return vec![center];
}
let n = (half_width / step).floor() as i32;
(-n..=n).map(|k| center + k as f32 * step).collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture() -> PathBuf {
PathBuf::from(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/streaming_dxchange.h5"
))
}
#[test]
fn grid_is_centred_and_symmetric() {
assert_eq!(
grid(396.0, 1.0, 0.5),
vec![395.0, 395.5, 396.0, 396.5, 397.0]
);
assert_eq!(grid(10.0, 0.2, 0.5), vec![10.0]);
assert_eq!(grid(396.0, 0.0, 0.25), vec![396.0]);
assert_eq!(grid(396.0, 8.0, 0.0), vec![396.0]);
}
#[test]
fn default_slice_is_the_band_midpoint_else_the_middle_of_the_volume() {
let st = PreppedStack::load(&crate::CpuBackend::new(), &fixture()).unwrap();
let (_nproj, nz, _nx) = st.shape();
assert_eq!(st.default_slice(None, None), nz / 2);
let tilted = st.default_slice(Some(44.0), None);
assert_eq!(tilted, crate::cuda::lamino_recon_height(nz, 44.0) / 2);
assert!(
tilted > nz / 2,
"a 44° tilt must push the middle of the volume past the detector's middle row: \
got {tilted} for nz {nz}"
);
assert_eq!(st.default_slice(Some(44.0), Some((2, 7))), 4);
}
#[test]
fn moved_by_nothing_is_the_same_stack() {
let cpu = crate::CpuBackend::new();
let st = PreppedStack::load(&cpu, &fixture()).unwrap();
let (nproj, _, _) = st.shape();
let zero = vec![0.0; nproj];
let m = st.moved(&cpu, &zero, &zero, 0.0).unwrap();
assert_eq!(m.shape(), st.shape());
assert_eq!(m.theta, st.theta);
let a = st.data.as_layout(Layout::Projection);
let b = m.data.as_layout(Layout::Projection);
let peak = a.array.iter().fold(0.0f32, |m, v| m.max(v.abs()));
for (x, y) in a.array.iter().zip(b.array.iter()) {
assert!((x - y).abs() <= 1e-4 * peak.max(1.0), "{x} vs {y}");
}
}
}