use ndarray::{Array3, ArrayViewMut2, Axis};
use crate::data::{Frames, Tomo, Volume};
use crate::dtype::{Complex32, Dtype, Element};
use crate::error::Result;
use crate::geometry::Geometry;
use crate::params::{FilterName, StripeMethod};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DeviceKind {
Cpu,
Cuda,
Wgpu,
}
pub trait DeviceBuffer<T: Element> {
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn copy_from_host(&mut self, src: &[T]) -> Result<()>;
fn copy_to_host(&self, dst: &mut [T]) -> Result<()>;
}
pub trait HostBuffer: Send {
fn as_mut_slice(&mut self) -> &mut [f32];
fn as_slice(&self) -> &[f32];
}
pub(crate) struct VecHostBuffer(Vec<f32>);
impl VecHostBuffer {
pub(crate) fn new(len: usize) -> Self {
VecHostBuffer(vec![0.0f32; len])
}
}
impl HostBuffer for VecHostBuffer {
fn as_mut_slice(&mut self) -> &mut [f32] {
&mut self.0
}
fn as_slice(&self) -> &[f32] {
&self.0
}
}
pub trait Backend: Send + Sync {
fn name(&self) -> &'static str;
fn device(&self) -> DeviceKind;
fn supports(&self, dt: Dtype) -> bool;
fn fft(&self) -> Option<&dyn Fft> {
None
}
fn fbp_filter(&self) -> Option<&dyn FbpFilter> {
None
}
fn backprojector(&self) -> Option<&dyn FilteredBackproject> {
None
}
fn fourier_reconstruct(&self) -> Option<&dyn FourierReconstruct> {
None
}
fn analytic_reconstruct(&self) -> Option<&dyn AnalyticReconstruct> {
None
}
fn lprec_reconstruct(&self) -> Option<&dyn LpRecReconstruct> {
None
}
fn projector(&self) -> Option<&dyn ForwardProject> {
None
}
fn ray_projector(&self) -> Option<&dyn RayProject> {
None
}
fn elementwise(&self) -> Option<&dyn Elementwise> {
None
}
fn rank_filter(&self) -> Option<&dyn RankFilter> {
None
}
fn alloc_host_buffer(&self, len: usize) -> Box<dyn HostBuffer> {
Box::new(VecHostBuffer::new(len))
}
fn wants_raw_chunks(&self) -> bool {
false
}
}
pub trait Fft: Send + Sync {
fn for_each_slice(
&self,
out: &mut Array3<f32>,
f: &(dyn Fn(usize, ArrayViewMut2<f32>) -> Result<()> + Sync),
) -> Result<()> {
for (row, slab) in out.axis_iter_mut(Axis(0)).enumerate() {
f(row, slab)?;
}
Ok(())
}
fn fft_1d(&self, buf: &mut [Complex32], len: usize, batch: usize, inverse: bool) -> Result<()>;
fn fft_2d(
&self,
buf: &mut [Complex32],
rows: usize,
cols: usize,
batch: usize,
inverse: bool,
) -> Result<()>;
}
pub trait FbpFilter {
fn make_filter(&self, name: FilterName, n: usize) -> Result<Vec<f32>>;
fn apply(&self, sino: &mut Tomo<f32>, filter: &[f32], geom: &Geometry) -> Result<()>;
}
pub fn make_fbp_filter(name: FilterName, n: usize) -> Result<Vec<f32>> {
if n == 0 {
return Err(crate::error::Error::InvalidParam(
"filter length must be > 0".into(),
));
}
let pad = (4 * n).next_power_of_two();
let pi = std::f32::consts::PI;
let mut f = vec![0.0f32; pad];
for (k, slot) in f.iter_mut().enumerate() {
let fk = if k <= pad / 2 { k } else { pad - k };
let r = 2.0 * fk as f32 / pad as f32;
let ramp = r;
*slot = match name {
FilterName::None => 1.0, FilterName::Ramp => ramp,
FilterName::Shepp => {
let x = pi * r / 2.0;
if x == 0.0 {
ramp
} else {
ramp * (x.sin() / x)
}
}
FilterName::Cosine => ramp * (pi * r / 2.0).cos(),
FilterName::Cosine2 => {
let c = (pi * r / 2.0).cos();
ramp * c * c
}
FilterName::Hamming => ramp * (0.54 + 0.46 * (pi * r).cos()),
FilterName::Hann => ramp * 0.5 * (1.0 + (pi * r).cos()),
FilterName::Parzen => ramp * (1.0 - r).powi(3),
};
}
Ok(f)
}
pub trait AnalyticReconstruct {
fn reconstruct(
&self,
sino: &Tomo<f32>,
geom: &Geometry,
algorithm: crate::params::Algorithm,
params: &crate::params::ReconParams,
) -> Result<Volume<f32>>;
fn streaming(
&self,
_algorithm: crate::params::Algorithm,
_params: &crate::params::ReconParams,
_geom: &Geometry,
_ncols: usize,
_max_nz: usize,
) -> Result<Option<Box<dyn StreamingAnalytic>>> {
Ok(None)
}
}
pub trait StreamingAnalytic {
fn reconstruct_chunk(&mut self, sino: &Tomo<f32>, geom: &Geometry) -> Result<Volume<f32>>;
fn reconstruct_chunk_raw(
&mut self,
_data: &[f32],
_dims: (usize, usize, usize),
_flat: Option<&Frames<f32>>,
_dark: Option<&Frames<f32>>,
_geom: &Geometry,
_stripe: StripeMethod,
) -> Result<Option<Volume<f32>>> {
Ok(None)
}
fn give_reuse_buffer(&mut self, _buf: Vec<f32>) {}
}
pub trait FourierReconstruct {
fn reconstruct(&self, filtered: &Tomo<f32>, geom: &Geometry, n: usize) -> Result<Volume<f32>>;
}
pub trait LpRecReconstruct {
fn reconstruct(&self, filtered: &Tomo<f32>, geom: &Geometry, n: usize) -> Result<Volume<f32>>;
}
pub trait FilteredBackproject {
fn backproject(&self, sino: &Tomo<f32>, geom: &Geometry, out: &mut Volume<f32>) -> Result<()>;
}
pub trait ForwardProject {
fn project(&self, vol: &Volume<f32>, geom: &Geometry, out: &mut Tomo<f32>) -> Result<()>;
}
#[derive(Clone, Debug, Default)]
pub struct RayRow {
pub pixels: Vec<u32>,
pub weights: Vec<f32>,
}
pub trait RayProject {
fn ray_rows(&self, geom: &Geometry, n: usize) -> Result<Vec<Vec<RayRow>>>;
}
pub trait Elementwise {
fn darkflat(&self, data: &mut Tomo<f32>, flat: &Frames<f32>, dark: &Frames<f32>) -> Result<()>;
fn minus_log(&self, data: &mut Tomo<f32>) -> Result<()>;
}
pub trait RankFilter {
fn median3d(&self, vol: &mut Volume<f32>, size: usize) -> Result<()>;
fn remove_outlier3d(&self, data: &mut Tomo<f32>, diff: f32, size: usize) -> Result<()>;
}