use crate::backend::{Backend, Fft};
use crate::data::{Layout, Tomo};
use crate::dtype::Complex32;
use crate::error::{Error, Result};
use crate::geometry::{Angles, Beam, Center, Detector, Geometry};
use ndarray::{Array2, Array3, ArrayView2, ArrayView3, ArrayViewMut2, Axis, Slice};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RingCenter {
pub center: f32,
pub prominence: f32,
pub trustworthy: bool,
}
pub fn find_center_rings(
tomo: &Tomo<f32>,
backend: &dyn Backend,
step: usize,
) -> Result<RingCenter> {
find_center_rings_from_mean(mean_projection(tomo, step)?.view(), backend)
}
pub fn find_center_rings_from_mean(
mean: ArrayView2<f32>,
backend: &dyn Backend,
) -> Result<RingCenter> {
let fft = backend.fft().ok_or_else(|| Error::MissingCapability {
backend: backend.name(),
capability: "Fft",
})?;
let (ny, nx) = mean.dim();
if ny < 5 || nx < 4 {
return Err(Error::InvalidParam(format!(
"find_center_rings needs ≥5×4 pixels; got {ny}×{nx}"
)));
}
let prof = flip_registration_profile(&mean, fft)?;
Ok(ring_center_from_profile(&prof, nx))
}
pub fn mean_projection(tomo: &Tomo<f32>, step: usize) -> Result<Array2<f32>> {
if step == 0 {
return Err(Error::InvalidParam(
"mean_projection: step must be ≥1".into(),
));
}
let p = tomo.as_layout(Layout::Projection); let (nproj, ny, nx) = p.array.dim();
if nproj == 0 {
return Err(Error::InvalidParam(
"mean_projection: the stack has no projections".into(),
));
}
let mut mean = Array2::<f32>::zeros((ny, nx));
let mut cnt = 0usize;
for i in (0..nproj).step_by(step) {
mean += &p.array.index_axis(Axis(0), i);
cnt += 1;
}
mean /= cnt as f32;
Ok(mean)
}
fn flip_registration_profile(m: &ArrayView2<f32>, fft: &dyn Fft) -> Result<Vec<f32>> {
let (ny, nx) = m.dim();
let mean = m.sum() / (ny * nx) as f32;
let mut a: Vec<Complex32> = m.iter().map(|&v| Complex32::new(v - mean, 0.0)).collect();
let mut b: Vec<Complex32> = Vec::with_capacity(ny * nx);
for y in 0..ny {
for x in 0..nx {
b.push(Complex32::new(m[[y, nx - 1 - x]] - mean, 0.0));
}
}
fft.fft_2d(&mut a, ny, nx, 1, false)?;
fft.fft_2d(&mut b, ny, nx, 1, false)?;
for (av, bv) in a.iter_mut().zip(b.iter()) {
*av *= bv.conj();
}
fft.fft_2d(&mut a, ny, nx, 1, true)?;
let mut prof = vec![0.0f32; nx];
for dy in 0..5usize {
let y_shifted = ny / 2 - 2 + dy;
let y = (y_shifted + ny.div_ceil(2)) % ny; for (x, p) in prof.iter_mut().enumerate() {
let xs = (x + nx.div_ceil(2)) % nx; *p += a[y * nx + xs].re;
}
}
Ok(prof)
}
fn ring_center_from_profile(prof: &[f32], nx: usize) -> RingCenter {
let i = prof
.iter()
.enumerate()
.fold((0usize, f32::NEG_INFINITY), |(bi, bv), (k, &v)| {
if v > bv {
(k, v)
} else {
(bi, bv)
}
})
.0;
let d = if i == 0 || i + 1 >= prof.len() {
0.0
} else {
let (y0, y1, y2) = (prof[i - 1], prof[i], prof[i + 1]);
let den = 2.0 * (y0 - 2.0 * y1 + y2);
if den.abs() < f32::EPSILON {
0.0
} else {
(y0 - y2) / den
}
};
let lag = i as f32 + d - (nx / 2) as f32;
let center = (nx as f32 - 1.0 + lag) / 2.0;
let mut sorted: Vec<f32> = prof.to_vec();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let median = sorted[sorted.len() / 2];
let mut dev: Vec<f32> = prof.iter().map(|v| (v - median).abs()).collect();
dev.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let mad = dev[dev.len() / 2];
let prominence = if mad > 0.0 {
(prof[i] - median) / mad
} else {
0.0
};
RingCenter {
center,
prominence,
trustworthy: prominence >= 8.0,
}
}
pub fn slice_focus(img: &ndarray::ArrayView2<f32>) -> f64 {
let (ny, nx) = img.dim();
if ny < 3 || nx < 3 {
return 0.0;
}
let (cy, cx) = (ny as f32 / 2.0, nx as f32 / 2.0);
let r2 = (0.46 * nx.min(ny) as f32).powi(2); let (mut acc, mut cnt) = (0.0f64, 0usize);
for y in 1..ny - 1 {
for x in 1..nx - 1 {
if (x as f32 - cx).powi(2) + (y as f32 - cy).powi(2) >= r2 {
continue;
}
let gx = (img[[y, x + 1]] - img[[y, x - 1]]) as f64;
let gy = (img[[y + 1, x]] - img[[y - 1, x]]) as f64;
acc += gx * gx + gy * gy;
cnt += 1;
}
}
acc / cnt.max(1) as f64
}
pub fn focus_by_z(vol: ArrayView3<f32>) -> Vec<f64> {
use rayon::prelude::*;
(0..vol.len_of(Axis(0)))
.into_par_iter()
.map(|z| slice_focus(&vol.index_axis(Axis(0), z)))
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rival {
pub index: usize,
pub value: f32,
pub prominence: f64,
pub deficit: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SweepVerdict {
Resolved {
index: usize,
value: f32,
},
Railed {
index: usize,
value: f32,
},
Ambiguous {
index: usize,
value: f32,
rivals: Vec<Rival>,
},
Flat {
index: usize,
value: f32,
},
}
impl SweepVerdict {
pub fn resolved(&self) -> Option<f32> {
match *self {
SweepVerdict::Resolved { value, .. } => Some(value),
_ => None,
}
}
pub fn best(&self) -> (usize, f32) {
match *self {
SweepVerdict::Resolved { index, value }
| SweepVerdict::Railed { index, value }
| SweepVerdict::Ambiguous { index, value, .. }
| SweepVerdict::Flat { index, value } => (index, value),
}
}
}
const SIGNIFICANT_PROMINENCE: f64 = 0.2;
fn local_maxima(score: &[f64]) -> Vec<usize> {
let n = score.len();
let mut out = Vec::new();
let mut i = 0;
while i < n {
let mut j = i;
while j + 1 < n && score[j + 1] == score[i] {
j += 1;
}
let rises_before = i > 0 && score[i - 1] > score[i];
let rises_after = j + 1 < n && score[j + 1] > score[j];
if !rises_before && !rises_after {
out.push(i);
}
i = j + 1;
}
out
}
fn prominence(score: &[f64], i: usize) -> f64 {
let mut col = f64::NEG_INFINITY;
for dir in [-1i64, 1] {
let mut j = i as i64 + dir;
let mut low = score[i];
while j >= 0 && (j as usize) < score.len() {
let v = score[j as usize];
if v > score[i] {
break;
}
low = low.min(v);
j += dir;
}
col = col.max(low);
}
score[i] - col
}
pub fn judge_sweep(cands: &[f32], score: &[f64]) -> Option<SweepVerdict> {
if cands.is_empty() || score.len() != cands.len() {
return None;
}
let index = score
.iter()
.enumerate()
.fold((0usize, f64::NEG_INFINITY), |(bi, bv), (i, &x)| {
if x > bv {
(i, x)
} else {
(bi, bv)
}
})
.0;
let value = cands[index];
if cands.len() < 3 {
return Some(SweepVerdict::Resolved { index, value });
}
let height = score[index] - score.iter().copied().fold(f64::INFINITY, f64::min);
if height.is_nan() || height <= 0.0 {
return Some(SweepVerdict::Flat { index, value });
}
let winner = prominence(score, index);
if index == 0 || index == cands.len() - 1 || winner < SIGNIFICANT_PROMINENCE * height {
return Some(SweepVerdict::Railed { index, value });
}
let mut rivals: Vec<Rival> = local_maxima(score)
.into_iter()
.filter(|&i| i != index)
.filter_map(|i| {
let p = prominence(score, i);
(p >= SIGNIFICANT_PROMINENCE * height).then_some(Rival {
index: i,
value: cands[i],
prominence: p,
deficit: (score[index] - score[i]) / score[index],
})
})
.collect();
if rivals.is_empty() {
return Some(SweepVerdict::Resolved { index, value });
}
rivals.sort_by(|a, b| {
b.prominence
.partial_cmp(&a.prominence)
.unwrap_or(std::cmp::Ordering::Equal)
});
Some(SweepVerdict::Ambiguous {
index,
value,
rivals,
})
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SampleBand {
pub z: (usize, usize),
pub tilt_deg: f32,
}
impl SampleBand {
pub fn at(&self, rh_from: usize, tilt_to_deg: f32, rh_to: usize) -> (usize, usize) {
let map = |z: usize| -> usize {
let row =
(z as f64 - rh_from as f64 / 2.0) * f64::from(self.tilt_deg).to_radians().cos();
let z = row / f64::from(tilt_to_deg).to_radians().cos() + rh_to as f64 / 2.0;
z.round().clamp(0.0, rh_to as f64 - 1.0) as usize
};
(map(self.z.0), map(self.z.1))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TiltFocus {
pub tilt_deg: f32,
pub focus: f64,
pub z_peak: usize,
pub band: Option<(usize, usize)>,
pub depth: usize,
pub focus_by_z: Vec<f64>,
}
pub fn middle_slice(band: Option<(usize, usize)>, depth: usize) -> usize {
match band {
Some((lo, hi)) => (lo + hi) / 2,
None => depth / 2,
}
}
pub struct TiltViews<'a> {
pub layer: ArrayView2<'a, f32>,
pub layer_z: usize,
pub xz: ArrayView2<'a, f32>,
}
#[derive(Debug, Clone, Copy)]
pub struct TiltCandidates<'a> {
pub tilts_deg: &'a [f32],
pub band: Option<SampleBand>,
}
pub fn lamino_tilt_scan(
sino: &Tomo<f32>,
geom: &Geometry,
algorithm: crate::params::Algorithm,
params: &crate::params::ReconParams,
cands: TiltCandidates<'_>,
cancel: Option<&crate::pipeline::CancelToken>,
on_tilt: &mut dyn FnMut(&TiltFocus, TiltViews<'_>) -> Result<()>,
) -> Result<Vec<TiltFocus>> {
let TiltCandidates { tilts_deg, band } = cands;
if let Some(b) = &band {
if b.z.0 > b.z.1 {
return Err(Error::Backend(format!(
"the sample band {}..{} is inverted",
b.z.0, b.z.1
)));
}
}
let rh_for = |tilt_deg: f32| {
params
.lamino_rh
.unwrap_or_else(|| crate::cuda::lamino_recon_height(geom.detector.height, tilt_deg))
};
let mut out = Vec::with_capacity(tilts_deg.len());
for &tilt_deg in tilts_deg {
crate::pipeline::check_cancel(cancel)?;
let geom = Geometry {
beam: Beam::laminography(tilt_deg),
..geom.clone()
};
let rh = rh_for(tilt_deg);
let scored = band
.as_ref()
.map(|b| b.at(rh_for(b.tilt_deg), tilt_deg, rh));
let layer_z = middle_slice(scored, rh);
let mut layer: Option<Array2<f32>> = None;
let mut profile: Vec<f64> = Vec::new();
let mut xz: Vec<f32> = Vec::new();
let (depth, _, nx) = {
let mut on_tile = |z0: usize, tile: &crate::data::Volume<f32>| -> Result<()> {
crate::pipeline::check_cancel(cancel)?;
let ny = tile.array.dim().1;
xz.extend(tile.array.index_axis(Axis(1), ny / 2).iter());
for (k, f) in focus_by_z(tile.array.view()).into_iter().enumerate() {
profile.push(f);
if z0 + k == layer_z {
layer = Some(tile.array.index_axis(Axis(0), k).to_owned());
}
}
Ok(())
};
crate::cuda::reconstruct_lamino_streaming(
sino,
&geom,
algorithm,
params,
None,
cancel,
&mut on_tile,
)?
};
if depth != rh {
return Err(Error::Backend(format!(
"tilt {tilt_deg}°: the reconstruction is {depth} deep but the depth rule \
said {rh} — the sample band was mapped against the wrong depth"
)));
}
if profile.len() != depth {
return Err(Error::Backend(format!(
"tilt {tilt_deg}°: scored {} slices but the reconstruction is {depth} deep",
profile.len()
)));
}
let (lo, hi) = scored.unwrap_or((0, depth.saturating_sub(1)));
let in_band = profile
.get(lo..=hi)
.filter(|s| !s.is_empty())
.ok_or_else(|| {
Error::Backend(format!(
"the reconstruction at tilt {tilt_deg}° produced no slices to score"
))
})?;
let focus = in_band.iter().sum::<f64>() / in_band.len() as f64;
let z_peak = lo
+ in_band
.iter()
.enumerate()
.fold(0, |best, (k, &f)| if f > in_band[best] { k } else { best });
let layer = layer.ok_or_else(|| {
Error::Backend(format!(
"tilt {tilt_deg}°: slice {layer_z} never streamed past"
))
})?;
let xz = Array2::from_shape_vec((depth, nx), xz)
.map_err(|e| Error::Backend(format!("tilt {tilt_deg}°: the xz plane: {e}")))?;
let r = TiltFocus {
tilt_deg,
focus,
z_peak,
band: scored,
depth,
focus_by_z: profile,
};
on_tilt(
&r,
TiltViews {
layer: layer.view(),
layer_z,
xz: xz.view(),
},
)?;
out.push(r);
}
Ok(out)
}
pub fn find_center(
tomo: &Tomo<f32>,
theta: &[f32],
backend: &dyn Backend,
ind: Option<usize>,
init: Option<f32>,
tol: f32,
) -> Result<f32> {
let fft = backend.fft().ok_or_else(|| Error::MissingCapability {
backend: backend.name(),
capability: "Fft",
})?;
let sino = tomo.as_layout(Layout::Sinogram); let (nrows, nang, ncol) = sino.array.dim();
if theta.len() != nang {
return Err(Error::ShapeMismatch {
expected: format!("{nang} angles"),
found: format!("{} theta", theta.len()),
});
}
let ind = ind.unwrap_or(nrows / 2).min(nrows.saturating_sub(1));
let slc = Tomo::new(
sino.array
.index_axis(Axis(0), ind)
.to_owned()
.insert_axis(Axis(0)),
Layout::Sinogram,
);
let n = ncol; let init = init.unwrap_or((ncol / 2) as f32) as f64;
let mut rec0 = recon_at(&slc, theta, ncol as f32 / 2.0, n, fft)?;
let (mut mn, mut mx) = (f32::INFINITY, f32::NEG_INFINITY);
{
let mut img = rec0.index_axis_mut(Axis(0), 0);
circ_mask_inplace(&mut img);
for &v in img.iter() {
mn = mn.min(v);
mx = mx.max(v);
}
}
let hmin = adjust_hist_min(mn) as f64;
let hmax = adjust_hist_max(mx) as f64;
let cost = |center: f64| -> Result<f64> {
let mut rec = recon_at(&slc, theta, center as f32, n, fft)?;
let mut img = rec.index_axis_mut(Axis(0), 0);
circ_mask_inplace(&mut img);
Ok(entropy64(&img.view(), hmin, hmax))
};
let center = nelder_mead_1d(&cost, init, tol as f64, tol as f64)?;
Ok(center as f32)
}
#[allow(clippy::too_many_arguments)]
pub fn find_center_vo(
tomo: &Tomo<f32>,
backend: &dyn Backend,
ind: Option<usize>,
smin: f32,
smax: f32,
srad: f32,
step: f32,
ratio: f32,
drop: i32,
) -> Result<f32> {
let fft = backend.fft().ok_or_else(|| Error::MissingCapability {
backend: backend.name(),
capability: "Fft",
})?;
let sino = extract_slice(tomo, ind); let (nrow, ncol) = sino.dim();
let tomo_cs = gaussian_filter2d(&sino, 3.0, 1.0);
let tomo_fs = gaussian_filter2d(&sino, 2.0, 2.0);
let fine_cen = if nrow * ncol > 4_000_000 {
let coarse = downsample_cols(&tomo_cs, 2);
let init_cen = search_coarse(&coarse, smin / 4.0, smax / 4.0, ratio, drop, fft)? * 4.0;
search_fine(&tomo_fs, srad, step, init_cen, ratio, drop, fft)?
} else {
let init_cen = search_coarse(&tomo_cs, smin, smax, ratio, drop, fft)?;
search_fine(&tomo_fs, srad, step, init_cen, ratio, drop, fft)?
};
Ok(fine_cen)
}
pub fn find_center_pc(
proj0: &Array2<f32>,
proj180: &Array2<f32>,
backend: &dyn Backend,
tol: f32,
rotc_guess: Option<f32>,
) -> Result<f32> {
let fft = backend.fft().ok_or_else(|| Error::MissingCapability {
backend: backend.name(),
capability: "Fft",
})?;
let (nrow, ncol) = proj0.dim();
if proj180.dim() != (nrow, ncol) {
return Err(Error::ShapeMismatch {
expected: format!("{nrow}x{ncol}"),
found: format!("{}x{}", proj180.dim().0, proj180.dim().1),
});
}
let imgshift = match rotc_guess {
Some(g) => g as f64 - (ncol as f64 - 1.0) / 2.0,
None => 0.0,
};
let upsample = 1.0f64 / tol as f64;
let shift_col = if imgshift != 0.0 {
let p0 = ndimage_shift_spline3_constant(proj0, 0.0, -imgshift);
let p180 = ndimage_shift_spline3_constant(proj180, 0.0, -imgshift);
let mov = fliplr(&p180);
phase_cross_correlation(&p0, &mov, upsample, fft)?.1
} else {
let mov = fliplr(proj180);
phase_cross_correlation(proj0, &mov, upsample, fft)?.1
};
let center = (ncol as f64 + shift_col - 1.0) / 2.0;
Ok((center + imgshift) as f32)
}
pub fn register_shift(
reference: &Array2<f32>,
moving: &Array2<f32>,
backend: &dyn Backend,
upsample: f64,
) -> Result<(f64, f64)> {
let fft = backend.fft().ok_or_else(|| Error::MissingCapability {
backend: backend.name(),
capability: "Fft",
})?;
if reference.dim() != moving.dim() {
return Err(Error::ShapeMismatch {
expected: format!("{}x{}", reference.dim().0, reference.dim().1),
found: format!("{}x{}", moving.dim().0, moving.dim().1),
});
}
if reference.is_empty() || !(upsample >= 1.0 && upsample.is_finite()) {
return Err(Error::InvalidParam(format!(
"register_shift needs a non-empty image and upsample ≥ 1; got {:?}, {upsample}",
reference.dim()
)));
}
phase_cross_correlation(reference, moving, upsample, fft)
}
#[cfg(not(feature = "sift-center"))]
pub fn find_center_sift(
_proj0: &Array2<f32>,
_proj180: &Array2<f32>,
_threshold: f32,
) -> Result<f32> {
Err(Error::todo(
"center::find_center_sift (build with the `sift-center` feature)",
"tomocupy find_center.py:99",
))
}
#[cfg(feature = "sift-center")]
pub use sift::{find_center_sift, register_shift_sift};
#[cfg(feature = "sift-center")]
pub mod sift {
use super::{fliplr, Error, Result};
use lowe_sift::{match_descriptors, GrayImage, Sift};
use ndarray::Array2;
fn find_min_max(data: &[f32]) -> (f32, f32) {
const NBINS: usize = 1000;
let (mut dmin, mut dmax) = (f32::INFINITY, f32::NEG_INFINITY);
for &v in data {
if v < dmin {
dmin = v;
}
if v > dmax {
dmax = v;
}
}
let (first, last) = (dmin as f64, dmax as f64);
if last <= first {
return (dmin, dmax);
}
let edges: Vec<f64> = (0..=NBINS)
.map(|i| {
if i == NBINS {
last
} else {
first + (last - first) * (i as f64) / (NBINS as f64)
}
})
.collect();
let norm = NBINS as f64 / (last - first);
let mut h = vec![0u64; NBINS];
for &v in data {
let x = v as f64;
let mut idx = ((x - first) * norm) as i64;
if idx == NBINS as i64 {
idx -= 1;
}
let mut idx = idx.clamp(0, NBINS as i64 - 1) as usize;
if x < edges[idx] && idx > 0 {
idx -= 1;
}
if idx != NBINS - 1 && x >= edges[idx + 1] {
idx += 1;
}
h[idx] += 1;
}
let hmax = *h.iter().max().unwrap_or(&0);
let thr = hmax as f64 * 0.005;
let st = h.iter().position(|&c| c as f64 > thr).unwrap_or(0);
let end = h.iter().rposition(|&c| c as f64 > thr).unwrap_or(NBINS - 1);
(edges[st] as f32, edges[end + 1] as f32)
}
fn to_gray(img: &Array2<f32>, mmin: f32, mmax: f32) -> Result<GrayImage> {
let (rows, cols) = img.dim();
let scale = mmax - mmin;
let data = img
.iter()
.map(|&v| (((v - mmin) / scale * 255.0).clamp(0.0, 255.0) as u8) as f32 / 255.0)
.collect();
GrayImage::new(cols, rows, data).map_err(|e| Error::Backend(format!("lowe-sift: {e}")))
}
pub fn normalize_to_u8(img: &Array2<f32>) -> Vec<u8> {
let (mmin, mmax) = find_min_max(img.as_slice().expect("contiguous image"));
let scale = mmax - mmin;
img.iter()
.map(|&v| ((v - mmin) / scale * 255.0).clamp(0.0, 255.0) as u8)
.collect()
}
pub fn register_shift_sift(
datap1: &[Array2<f32>],
datap2: &[Array2<f32>],
threshold: f32,
) -> Result<(Array2<f32>, usize)> {
if datap1.len() != datap2.len() || datap1.is_empty() {
return Err(Error::InvalidParam(
"register_shift_sift: need equal, non-empty datap1/datap2".into(),
));
}
let sift = Sift::default();
let mut shifts = Array2::<f32>::zeros((datap1.len(), 2));
let mut ngood = 0usize;
for (id, (p1, p2)) in datap1.iter().zip(datap2).enumerate() {
let (mmin, mmax) = find_min_max(p1.as_slice().expect("contiguous datap1"));
let f1 = sift.detect_and_compute(&to_gray(p2, mmin, mmax)?); let f2 = sift.detect_and_compute(&to_gray(p1, mmin, mmax)?); let d1: Vec<_> = f1.iter().map(|f| f.descriptor.clone()).collect();
let d2: Vec<_> = f2.iter().map(|f| f.descriptor.clone()).collect();
let (mut sum_x, mut sum_y, mut n) = (0.0f64, 0.0f64, 0usize);
for m in match_descriptors(&d1, &d2, threshold) {
let src = &f1[m.query_index].keypoint;
let dst = &f2[m.train_index].keypoint;
sum_x += (src.x - dst.x) as f64;
sum_y += (src.y - dst.y) as f64;
n += 1;
}
if n == 0 {
return Err(Error::InvalidParam(format!(
"register_shift_sift: no good SIFT matches for pair {id}"
)));
}
ngood = n;
shifts[[id, 0]] = (sum_y / n as f64) as f32;
shifts[[id, 1]] = (sum_x / n as f64) as f32;
}
Ok((shifts, ngood))
}
pub fn find_center_sift(
proj0: &Array2<f32>,
proj180: &Array2<f32>,
threshold: f32,
) -> Result<f32> {
if proj0.dim() != proj180.dim() {
return Err(Error::ShapeMismatch {
expected: format!("{:?}", proj0.dim()),
found: format!("{:?}", proj180.dim()),
});
}
let ncol = proj0.dim().1;
let datap1 = [proj0.clone()];
let datap2 = [fliplr(proj180)];
let (shifts, _) = register_shift_sift(&datap1, &datap2, threshold)?;
Ok((ncol as f32 - 1.0) / 2.0 - shifts[[0, 1]] / 2.0)
}
}
pub fn write_center(
tomo: &Tomo<f32>,
theta: &[f32],
backend: &dyn Backend,
cen_range: Option<(f32, f32, f32)>,
ind: Option<usize>,
mask: bool,
ratio: f32,
) -> Result<(Vec<f32>, Array3<f32>)> {
let fft = backend.fft().ok_or_else(|| Error::MissingCapability {
backend: backend.name(),
capability: "Fft",
})?;
let sino = tomo.as_layout(Layout::Sinogram); let (nrows, nang, ncol) = sino.array.dim();
if theta.len() != nang {
return Err(Error::ShapeMismatch {
expected: format!("{nang} angles"),
found: format!("{} theta", theta.len()),
});
}
if nrows == 0 || nang == 0 || ncol == 0 {
return Ok((Vec::new(), Array3::zeros((0, ncol, ncol))));
}
let ind = ind.unwrap_or(nrows / 2).min(nrows - 1);
let (start, stop, step) = match cen_range {
Some((a, b, s)) => (a as f64, b as f64, s as f64),
None => {
let half = ncol as f64 / 2.0;
(half - 5.0, half + 5.0, 0.5)
}
};
let centers = arange(start, stop, step);
let slc = Tomo::new(
sino.array
.index_axis(Axis(0), ind)
.to_owned()
.insert_axis(Axis(0)),
Layout::Sinogram,
);
let n = ncol; let mut stack = Array3::<f32>::zeros((centers.len(), n, n));
for (m, &c) in centers.iter().enumerate() {
let mut rec = recon_at(&slc, theta, c as f32, n, fft)?; if mask {
let mut img = rec.index_axis_mut(Axis(0), 0);
circ_mask_inplace_ratio(&mut img, ratio as f64);
}
stack
.index_axis_mut(Axis(0), m)
.assign(&rec.index_axis(Axis(0), 0));
}
let centers: Vec<f32> = centers.iter().map(|&c| c as f32).collect();
Ok((centers, stack))
}
fn arange(start: f64, stop: f64, step: f64) -> Vec<f64> {
if step <= 0.0 {
return Vec::new();
}
let len = ((stop - start) / step).ceil();
let len = if len.is_finite() && len > 0.0 {
len as usize
} else {
0
};
(0..len).map(|i| start + i as f64 * step).collect()
}
fn recon_at(
sino: &Tomo<f32>,
theta: &[f32],
center: f32,
n: usize,
fft: &dyn Fft,
) -> Result<Array3<f32>> {
let geom = Geometry {
angles: Angles(theta.to_vec()),
center: Center::Scalar(center),
beam: Beam::Parallel,
detector: Detector {
width: sino.n_cols(),
height: 1,
pixel_size: 1.0,
},
};
crate::recon::gridrec::gridrec(sino, &geom, n, fft)
}
fn circ_mask_inplace_ratio(img: &mut ArrayViewMut2<f32>, ratio: f64) {
let (ny, nx) = img.dim();
let half_y = ny as f64 / 2.0;
let half_x = nx as f64 / 2.0;
let r2 = (ratio * (ny.min(nx) as f64 / 2.0)).powi(2);
for i in 0..ny {
let y = i as f64 + 0.5 - half_y;
for j in 0..nx {
let x = j as f64 + 0.5 - half_x;
if x * x + y * y >= r2 {
img[[i, j]] = 0.0;
}
}
}
}
fn circ_mask_inplace(img: &mut ArrayViewMut2<f32>) {
circ_mask_inplace_ratio(img, 1.0);
}
fn adjust_hist_min(v: f32) -> f32 {
if v < 0.0 {
2.0 * v
} else {
0.5 * v
}
}
fn adjust_hist_max(v: f32) -> f32 {
if v < 0.0 {
0.5 * v
} else {
2.0 * v
}
}
fn entropy64(img: &ndarray::ArrayView2<f32>, hmin: f64, hmax: f64) -> f64 {
const BINS: usize = 64;
let size = img.len() as f64;
let mut counts = [0.0f64; BINS];
let span = hmax - hmin;
for &v in img.iter() {
let v = v as f64;
if v < hmin || v > hmax {
continue; }
let mut idx = ((v - hmin) / span * BINS as f64) as usize;
if idx >= BINS {
idx = BINS - 1; }
counts[idx] += 1.0;
}
let mut val = 0.0f64;
for &c in counts.iter() {
let p = c / size + 1e-12;
val -= p * p.log2();
}
val
}
fn nelder_mead_1d<F>(f: &F, x0: f64, xatol: f64, fatol: f64) -> Result<f64>
where
F: Fn(f64) -> Result<f64>,
{
let (rho, chi, psi, sigma) = (1.0, 2.0, 0.5, 0.5);
let (nonzdelt, zdelt) = (0.05, 0.00025);
let mut s0 = x0;
let mut s1 = if x0 != 0.0 {
(1.0 + nonzdelt) * x0
} else {
zdelt
};
let mut f0 = f(s0)?;
let mut f1 = f(s1)?;
if f1 < f0 {
std::mem::swap(&mut s0, &mut s1);
std::mem::swap(&mut f0, &mut f1);
}
let (maxiter, maxfun) = (200usize, 200usize);
let mut fcalls = 2usize;
let mut iters = 1usize;
while fcalls < maxfun && iters < maxiter {
if (s1 - s0).abs() <= xatol && (f0 - f1).abs() <= fatol {
break;
}
let xbar = s0; let xr = (1.0 + rho) * xbar - rho * s1;
let fxr = f(xr)?;
fcalls += 1;
let mut doshrink = false;
if fxr < f0 {
let xe = (1.0 + rho * chi) * xbar - rho * chi * s1;
let fxe = f(xe)?;
fcalls += 1;
if fxe < fxr {
s1 = xe;
f1 = fxe;
} else {
s1 = xr;
f1 = fxr;
}
} else if fxr < f1 {
let xc = (1.0 + psi * rho) * xbar - psi * rho * s1;
let fxc = f(xc)?;
fcalls += 1;
if fxc <= fxr {
s1 = xc;
f1 = fxc;
} else {
doshrink = true;
}
} else {
let xcc = (1.0 - psi) * xbar + psi * s1;
let fxcc = f(xcc)?;
fcalls += 1;
if fxcc < f1 {
s1 = xcc;
f1 = fxcc;
} else {
doshrink = true;
}
}
if doshrink {
s1 = s0 + sigma * (s1 - s0);
f1 = f(s1)?;
fcalls += 1;
}
if f1 < f0 {
std::mem::swap(&mut s0, &mut s1);
std::mem::swap(&mut f0, &mut f1);
}
iters += 1;
}
Ok(s0)
}
fn fftfreq(n: usize, d: f64) -> Vec<f64> {
let nn = n as f64;
let cut = (n - 1) / 2; (0..n)
.map(|k| {
let idx = if k <= cut { k as f64 } else { k as f64 - nn };
idx / (nn * d)
})
.collect()
}
fn phase_cross_correlation(
reference: &Array2<f32>,
moving: &Array2<f32>,
upsample_factor: f64,
fft: &dyn Fft,
) -> Result<(f64, f64)> {
use std::f64::consts::PI;
let (nrow, ncol) = reference.dim();
let n = nrow * ncol;
let mut rf = vec![Complex32::new(0.0, 0.0); n];
let mut mf = vec![Complex32::new(0.0, 0.0); n];
for i in 0..nrow {
for j in 0..ncol {
rf[i * ncol + j] = Complex32::new(reference[[i, j]], 0.0);
mf[i * ncol + j] = Complex32::new(moving[[i, j]], 0.0);
}
}
fft.fft_2d(&mut rf, nrow, ncol, 1, false)?;
fft.fft_2d(&mut mf, nrow, ncol, 1, false)?;
let eps100 = 100.0 * f32::EPSILON as f64;
let mut pr = vec![0.0f64; n];
let mut pi = vec![0.0f64; n];
for k in 0..n {
let (ar, ai) = (rf[k].re as f64, rf[k].im as f64);
let (br, bi) = (mf[k].re as f64, mf[k].im as f64);
let re = ar * br + ai * bi; let im = ai * br - ar * bi;
let denom = (re * re + im * im).sqrt().max(eps100);
pr[k] = re / denom;
pi[k] = im / denom;
}
let mut cc = vec![Complex32::new(0.0, 0.0); n];
for k in 0..n {
cc[k] = Complex32::new(pr[k] as f32, pi[k] as f32);
}
fft.fft_2d(&mut cc, nrow, ncol, 1, true)?;
let (mut best, mut peak) = (-1.0f64, 0usize);
for (k, c) in cc.iter().enumerate() {
let m = (c.re as f64).hypot(c.im as f64);
if m > best {
best = m;
peak = k;
}
}
let (r0, c0) = ((peak / ncol) as f64, (peak % ncol) as f64);
let mut shift_r = if r0 > (nrow as f64 / 2.0).trunc() {
r0 - nrow as f64
} else {
r0
};
let mut shift_c = if c0 > (ncol as f64 / 2.0).trunc() {
c0 - ncol as f64
} else {
c0
};
if upsample_factor > 1.0 {
shift_r = (shift_r * upsample_factor).round() / upsample_factor;
shift_c = (shift_c * upsample_factor).round() / upsample_factor;
let region_f = (upsample_factor * 1.5).ceil();
let region = region_f as usize;
let dftshift = (region_f / 2.0).trunc();
let off_r = dftshift - shift_r * upsample_factor;
let off_c = dftshift - shift_c * upsample_factor;
let freq_c = fftfreq(ncol, upsample_factor);
let freq_r = fftfreq(nrow, upsample_factor);
let mut d1r = vec![0.0f64; region * nrow];
let mut d1i = vec![0.0f64; region * nrow];
for a in 0..region {
for r in 0..nrow {
let (mut sre, mut sim) = (0.0f64, 0.0f64);
for (c, &fc) in freq_c.iter().enumerate() {
let ang = -2.0 * PI * (a as f64 - off_c) * fc;
let (ks, kc) = ang.sin_cos();
let idx = r * ncol + c;
let (dre, dim) = (pr[idx], -pi[idx]); sre += kc * dre - ks * dim;
sim += kc * dim + ks * dre;
}
d1r[a * nrow + r] = sre;
d1i[a * nrow + r] = sim;
}
}
let (mut bestup, mut mb, mut ma) = (-1.0f64, 0usize, 0usize);
for b in 0..region {
for a in 0..region {
let (mut sre, mut sim) = (0.0f64, 0.0f64);
for (r, &fr) in freq_r.iter().enumerate() {
let ang = -2.0 * PI * (b as f64 - off_r) * fr;
let (ks, kc) = ang.sin_cos();
let (dre, dim) = (d1r[a * nrow + r], d1i[a * nrow + r]);
sre += kc * dre - ks * dim;
sim += kc * dim + ks * dre;
}
let m = (sre * sre + sim * sim).sqrt();
if m > bestup {
bestup = m;
mb = b;
ma = a;
}
}
}
shift_r += (mb as f64 - dftshift) / upsample_factor;
shift_c += (ma as f64 - dftshift) / upsample_factor;
}
if nrow == 1 {
shift_r = 0.0;
}
if ncol == 1 {
shift_c = 0.0;
}
Ok((shift_r, shift_c))
}
fn ndimage_shift_spline3_constant(
img: &Array2<f32>,
shift_row: f64,
shift_col: f64,
) -> Array2<f32> {
let (nr, nc) = img.dim();
let mut out = Array2::<f32>::zeros((nr, nc));
if nr == 0 || nc == 0 {
return out;
}
let coeff = spline_prefilter_2d(img); let (s_row, s_col) = (-shift_row, -shift_col);
let (nri, nci) = (nr as isize, nc as isize);
let (row_hi, col_hi) = (nr as f64 - 1.0, nc as f64 - 1.0);
for i in 0..nr {
let cc_row = i as f64 + s_row;
if cc_row < 0.0 || cc_row > row_hi {
continue; }
let w_row = spline_weights3(cc_row);
let start_row = (cc_row.floor() as isize) - 1; let row_taps = [
mirror_index(start_row, nri),
mirror_index(start_row + 1, nri),
mirror_index(start_row + 2, nri),
mirror_index(start_row + 3, nri),
];
for j in 0..nc {
let cc_col = j as f64 + s_col;
if cc_col < 0.0 || cc_col > col_hi {
continue; }
let w_col = spline_weights3(cc_col);
let start_col = (cc_col.floor() as isize) - 1;
let col_taps = [
mirror_index(start_col, nci),
mirror_index(start_col + 1, nci),
mirror_index(start_col + 2, nci),
mirror_index(start_col + 3, nci),
];
let mut t = 0.0f64;
for a in 0..4 {
let cr = coeff.row(row_taps[a]);
let wr = w_row[a];
for b in 0..4 {
t += cr[col_taps[b]] * wr * w_col[b];
}
}
out[[i, j]] = t as f32;
}
}
out
}
fn spline_prefilter_2d(img: &Array2<f32>) -> Array2<f64> {
let (nr, nc) = img.dim();
let z = 3.0f64.sqrt() - 2.0; let mut c = Array2::<f64>::from_shape_fn((nr, nc), |(i, j)| img[[i, j]] as f64);
if nr > 1 {
let mut line = vec![0.0f64; nr];
for j in 0..nc {
for (i, v) in line.iter_mut().enumerate() {
*v = c[[i, j]];
}
apply_spline_filter_mirror(&mut line, z);
for (i, &v) in line.iter().enumerate() {
c[[i, j]] = v;
}
}
}
if nc > 1 {
let mut line = vec![0.0f64; nc];
for i in 0..nr {
for (j, v) in line.iter_mut().enumerate() {
*v = c[[i, j]];
}
apply_spline_filter_mirror(&mut line, z);
for (j, &v) in line.iter().enumerate() {
c[[i, j]] = v;
}
}
}
c
}
fn apply_spline_filter_mirror(c: &mut [f64], z: f64) {
let n = c.len();
let gain = (1.0 - z) * (1.0 - 1.0 / z);
for v in c.iter_mut() {
*v *= gain;
}
let z_n_1 = z.powf((n - 1) as f64);
let mut acc = c[0] + z_n_1 * c[n - 1];
let mut z_i = z;
for i in 1..n - 1 {
acc += z_i * (c[i] + z_n_1 * c[n - 1 - i]);
z_i *= z;
}
c[0] = acc / (1.0 - z_n_1 * z_n_1);
for i in 1..n {
c[i] += z * c[i - 1];
}
c[n - 1] = (z * c[n - 2] + c[n - 1]) * z / (z * z - 1.0);
for i in (0..n - 1).rev() {
c[i] = z * (c[i + 1] - c[i]);
}
}
fn spline_weights3(cc: f64) -> [f64; 4] {
let x = cc - cc.floor(); let y = x;
let z = 1.0 - x;
let mut w = [0.0f64; 4];
w[1] = (y * y * (y - 2.0) * 3.0 + 4.0) / 6.0;
w[2] = (z * z * (z - 2.0) * 3.0 + 4.0) / 6.0;
w[0] = z * z * z / 6.0;
w[3] = 1.0 - w[0] - w[1] - w[2];
w
}
fn mirror_index(idx: isize, len: isize) -> usize {
if len == 1 {
return 0;
}
let mut v = idx;
if v < 0 {
let sz2 = 2 * len - 2;
v = sz2 * ((-v) / sz2) + v;
v = if v <= 1 - len { v + sz2 } else { -v };
} else if v > len - 1 {
let sz2 = 2 * len - 2;
v -= sz2 * (v / sz2);
if v >= len {
v = sz2 - v;
}
}
v as usize
}
fn extract_slice(tomo: &Tomo<f32>, ind: Option<usize>) -> Array2<f32> {
let sino = tomo.as_layout(Layout::Sinogram); let nrows = sino.array.dim().0;
let ind = ind.unwrap_or(nrows / 2).min(nrows.saturating_sub(1));
if nrows > 10 {
let lo = ind.saturating_sub(5);
let hi = (ind + 5).min(nrows);
sino.array
.slice_axis(Axis(0), Slice::from(lo..hi))
.mean_axis(Axis(0))
.unwrap()
} else {
sino.array.index_axis(Axis(0), ind).to_owned()
}
}
fn gaussian_kernel(sigma: f32) -> Vec<f32> {
let radius = (4.0 * sigma + 0.5) as isize;
let mut k = Vec::with_capacity((2 * radius + 1) as usize);
let mut sum = 0.0f32;
for i in -radius..=radius {
let w = (-0.5 * (i as f32 / sigma).powi(2)).exp();
k.push(w);
sum += w;
}
for w in &mut k {
*w /= sum;
}
k
}
fn reflect(p: isize, n: isize) -> usize {
if n == 1 {
return 0;
}
let m = 2 * n;
let mut q = p % m;
if q < 0 {
q += m;
}
if q >= n {
q = m - 1 - q;
}
q as usize
}
fn gaussian_filter2d(img: &Array2<f32>, sigma0: f32, sigma1: f32) -> Array2<f32> {
let (nr, nc) = img.dim();
let k1 = gaussian_kernel(sigma1);
let r1 = (k1.len() / 2) as isize;
let mut tmp = Array2::<f32>::zeros((nr, nc));
for i in 0..nr {
for j in 0..nc {
let mut acc = 0.0f32;
for (t, &w) in k1.iter().enumerate() {
let jj = reflect(j as isize + t as isize - r1, nc as isize);
acc += w * img[[i, jj]];
}
tmp[[i, j]] = acc;
}
}
let k0 = gaussian_kernel(sigma0);
let r0 = (k0.len() / 2) as isize;
let mut out = Array2::<f32>::zeros((nr, nc));
for j in 0..nc {
for i in 0..nr {
let mut acc = 0.0f32;
for (t, &w) in k0.iter().enumerate() {
let ii = reflect(i as isize + t as isize - r0, nr as isize);
acc += w * tmp[[ii, j]];
}
out[[i, j]] = acc;
}
}
out
}
fn downsample_cols(img: &Array2<f32>, level: u32) -> Array2<f32> {
let f = 1usize << level;
let (nr, nc) = img.dim();
let nc2 = nc / f;
let mut out = Array2::<f32>::zeros((nr, nc2));
for i in 0..nr {
for k in 0..nc2 {
let mut s = 0.0f32;
for d in 0..f {
s += img[[i, k * f + d]];
}
out[[i, k]] = s / f as f32;
}
}
out
}
fn fliplr(a: &Array2<f32>) -> Array2<f32> {
let (nr, nc) = a.dim();
Array2::from_shape_fn((nr, nc), |(i, j)| a[[i, nc - 1 - j]])
}
fn flipud(a: &Array2<f32>) -> Array2<f32> {
let (nr, nc) = a.dim();
Array2::from_shape_fn((nr, nc), |(i, j)| a[[nr - 1 - i, j]])
}
fn clipf(v: f32, lo: f32, hi: f32) -> f32 {
v.max(lo).min(hi)
}
fn search_coarse(
sino: &Array2<f32>,
smin: f32,
smax: f32,
ratio: f32,
drop: i32,
fft: &dyn Fft,
) -> Result<f32> {
let (nrow, ncol) = sino.dim();
let ncolf = ncol as f32;
let cen_fliplr = (ncolf - 1.0) / 2.0;
let smin_i = (clipf(smin + cen_fliplr, 0.0, ncolf - 1.0) - cen_fliplr) as i32;
let smax_i = (clipf(smax + cen_fliplr, 0.0, ncolf - 1.0) - cen_fliplr) as i32;
let start_cor = (ncol / 2) as i32 + smin_i;
let stop_cor = (ncol / 2) as i32 + smax_i;
let flip = fliplr(sino);
let comp = flipud(sino);
let mask = create_mask(2 * nrow, ncol, 0.5 * ratio * ncolf, drop);
let stop = stop_cor as f64 + 0.5;
let (mut best, mut best_cor) = (f32::INFINITY, start_cor as f32);
let mut k = 0i64;
loop {
let cor = start_cor as f64 + 0.5 * k as f64;
if cor >= stop {
break;
}
let shift = 2.0 * (cor - cen_fliplr as f64);
let m = calculate_metric(shift, sino, &flip, &comp, &mask, fft)?;
if m < best {
best = m;
best_cor = cor as f32;
}
k += 1;
}
Ok(best_cor)
}
fn search_fine(
sino: &Array2<f32>,
srad: f32,
step: f32,
init_cen: f32,
ratio: f32,
drop: i32,
fft: &dyn Fft,
) -> Result<f32> {
let (nrow, ncol) = sino.dim();
let ncolf = ncol as f32;
let cen_fliplr = (ncolf - 1.0) / 2.0;
let srad = clipf(srad.abs(), 1.0, ncolf / 4.0);
let step = clipf(step.abs(), 0.1, srad);
let init_cen = clipf(init_cen, srad, ncolf - srad - 1.0);
let flip = fliplr(sino);
let comp = flipud(sino);
let mask = create_mask(2 * nrow, ncol, 0.5 * ratio * ncolf, drop);
let stop = (srad + step) as f64;
let (mut best, mut best_cor) = (f32::INFINITY, init_cen - srad);
let mut k = 0i64;
loop {
let off = -(srad as f64) + step as f64 * k as f64;
if off >= stop {
break;
}
let cor = init_cen as f64 + off;
let shift = 2.0 * (cor - cen_fliplr as f64);
let m = calculate_metric(shift, sino, &flip, &comp, &mask, fft)?;
if m < best {
best = m;
best_cor = cor as f32;
}
k += 1;
}
Ok(best_cor)
}
fn create_mask(nrow: usize, ncol: usize, radius: f32, drop: i32) -> Array2<f32> {
let nrowf = nrow as f32;
let ncolf = ncol as f32;
let du = 1.0 / ncolf;
let dv = (nrowf - 1.0) / (nrowf * 2.0 * std::f32::consts::PI);
let cen_row = (nrowf / 2.0).ceil() as i32 - 1;
let cen_col = (ncolf / 2.0).ceil() as i32 - 1;
let drop = drop.min((0.05 * nrowf).ceil() as i32);
let mut mask = Array2::<f32>::zeros((nrow, ncol));
let ncol_i = ncol as i32;
for i in 0..nrow as i32 {
let val = (((i - cen_row) as f32) * dv / radius) / du;
let pos = val.ceil() as i32; let (a, b) = (-pos + cen_col, pos + cen_col);
let (p1, p2) = if a <= b { (a, b) } else { (b, a) };
let p1 = p1.clamp(0, ncol_i - 1);
let p2 = p2.clamp(0, ncol_i - 1);
for j in p1..=p2 {
mask[[i as usize, j as usize]] = 1.0;
}
}
let r0 = (cen_row - drop).max(0);
let r1 = (cen_row + drop).min(nrow as i32 - 1);
for i in r0..=r1 {
for j in 0..ncol {
mask[[i as usize, j]] = 0.0;
}
}
let c0 = (cen_col - 1).max(0);
let c1 = (cen_col + 1).min(ncol_i - 1);
for mut row in mask.rows_mut() {
for j in c0..=c1 {
row[j as usize] = 0.0;
}
}
mask
}
fn calculate_metric(
shift: f64,
sino: &Array2<f32>,
flip: &Array2<f32>,
comp: &Array2<f32>,
mask: &Array2<f32>,
fft: &dyn Fft,
) -> Result<f32> {
let (nrow, ncol) = sino.dim();
let nc = ncol as i32;
let ss = if (shift - shift.round()).abs() < 1e-9 {
let s = shift.round() as i32;
let mut ss = Array2::<f32>::zeros((nrow, ncol));
for i in 0..nrow {
for j in 0..ncol {
let src = ((j as i32 - s) % nc + nc) % nc;
ss[[i, j]] = flip[[i, src as usize]];
}
}
if s >= 0 {
for i in 0..nrow {
for j in 0..(s as usize).min(ncol) {
ss[[i, j]] = comp[[i, j]];
}
}
} else {
let from = (nc + s).max(0) as usize;
for i in 0..nrow {
for j in from..ncol {
ss[[i, j]] = comp[[i, j]];
}
}
}
ss
} else {
let mut ss = cubic_shift_cols(flip, shift);
if shift >= 0.0 {
let si = (shift.ceil() as i32).max(0) as usize;
for i in 0..nrow {
for j in 0..si.min(ncol) {
ss[[i, j]] = comp[[i, j]];
}
}
} else {
let from = (nc + shift.floor() as i32).max(0) as usize;
for i in 0..nrow {
for j in from..ncol {
ss[[i, j]] = comp[[i, j]];
}
}
}
ss
};
let rr = 2 * nrow;
let mut buf = vec![Complex32::new(0.0, 0.0); rr * ncol];
for i in 0..nrow {
for j in 0..ncol {
buf[i * ncol + j] = Complex32::new(sino[[i, j]], 0.0);
buf[(nrow + i) * ncol + j] = Complex32::new(ss[[i, j]], 0.0);
}
}
fft.fft_2d(&mut buf, rr, ncol, 1, false)?;
let mut acc = 0.0f64;
for i in 0..rr {
let mi = (i + rr / 2) % rr;
for j in 0..ncol {
let mj = (j + ncol / 2) % ncol;
acc += buf[i * ncol + j].norm() as f64 * mask[[mi, mj]] as f64;
}
}
Ok((acc / (rr * ncol) as f64) as f32)
}
fn cubic_shift_cols(img: &Array2<f32>, shift: f64) -> Array2<f32> {
let (nr, nc) = img.dim();
let mut out = Array2::<f32>::zeros((nr, nc));
let mut coeff = vec![0.0f64; nc];
for i in 0..nr {
for j in 0..nc {
coeff[j] = img[[i, j]] as f64;
}
prefilter_cubic(&mut coeff);
for j in 0..nc {
out[[i, j]] = eval_cubic(&coeff, j as f64 - shift) as f32;
}
}
out
}
fn prefilter_cubic(c: &mut [f64]) {
let n = c.len();
if n < 2 {
return;
}
let z = 3.0f64.sqrt() - 2.0;
let lambda = (1.0 - z) * (1.0 - 1.0 / z); for v in c.iter_mut() {
*v *= lambda;
}
let horizon = ((1e-9f64.ln() / z.abs().ln()).ceil() as usize).min(n);
let mut zn = z;
let mut sum = c[0];
for v in c.iter().take(horizon).skip(1) {
sum += zn * v;
zn *= z;
}
c[0] = sum;
for k in 1..n {
c[k] += z * c[k - 1];
}
c[n - 1] = (z / (z * z - 1.0)) * (z * c[n - 2] + c[n - 1]);
for k in (0..n - 1).rev() {
c[k] = z * (c[k + 1] - c[k]);
}
}
fn eval_cubic(c: &[f64], x: f64) -> f64 {
let n = c.len() as i64;
let xf = x.floor();
let base = xf as i64;
let mut val = 0.0;
for k in -1..=2 {
let idx = base + k;
if idx >= 0 && idx < n {
val += beta3((x - (xf + k as f64)).abs()) * c[idx as usize];
}
}
val
}
fn beta3(t: f64) -> f64 {
if t < 1.0 {
2.0 / 3.0 - t * t + 0.5 * t * t * t
} else if t < 2.0 {
let a = 2.0 - t;
a * a * a / 6.0
} else {
0.0
}
}
#[cfg(test)]
mod tests {
use super::{judge_sweep, ndimage_shift_spline3_constant, SampleBand, SweepVerdict};
use ndarray::{Array2, Array3};
use ndarray_npy::read_npy;
const WIDE: [f64; 81] = [
1.9491, 1.9521, 1.9564, 1.9635, 1.9709, 1.9765, 1.9824, 1.9879, 1.9892, 1.9892, 1.9910,
1.9971, 2.0092, 2.0228, 2.0306, 2.0338, 2.0348, 2.0357, 2.0372, 2.0352, 2.0272, 2.0167,
2.0056, 1.9913, 1.9757, 1.9649, 1.9585, 1.9581, 1.9594, 1.9614, 1.9694, 1.9845, 2.0095,
2.0437, 2.0865, 2.1321, 2.1749, 2.2101, 2.2364, 2.2557, 2.2625, 2.2521, 2.2318, 2.2077,
2.1832, 2.1593, 2.1369, 2.1182, 2.1022, 2.0909, 2.0855, 2.0880, 2.0985, 2.1178, 2.1412,
2.1663, 2.1944, 2.2219, 2.2412, 2.2536, 2.2645, 2.2701, 2.2694, 2.2666, 2.2618, 2.2572,
2.2502, 2.2407, 2.2312, 2.2219, 2.2075, 2.1902, 2.1745, 2.1638, 2.1576, 2.1581, 2.1680,
2.1814, 2.1933, 2.2041, 2.2153,
];
fn wide_cands() -> Vec<f32> {
(0..81).map(|k| 356.0 + k as f32).collect()
}
#[test]
fn judge_sweep_refuses_a_curve_whose_rival_lobe_it_cannot_separate() {
let v = judge_sweep(&wide_cands(), &WIDE).unwrap();
assert_eq!(
v.best(),
(61, 417.0),
"the argmax is unchanged — the verdict is what changed"
);
assert_eq!(
v.resolved(),
None,
"an interior argmax is not automatically an answer"
);
let SweepVerdict::Ambiguous { rivals, .. } = &v else {
panic!("expected Ambiguous, got {v:?}");
};
assert_eq!(rivals[0].value, 396.0);
assert!(
(rivals[0].deficit - 0.0033).abs() < 0.0005,
"the correct lobe trails the winner by {:.4}, not the measured 0.34 %",
rivals[0].deficit
);
assert_eq!(
rivals.iter().map(|r| r.value).collect::<Vec<_>>(),
vec![396.0, 374.0]
);
}
#[test]
fn judge_sweep_resolves_the_same_sweep_narrowed_onto_a_prior() {
let narrow: [f64; 17] = [
2.2364, 2.2419, 2.2470, 2.2517, 2.2557, 2.2590, 2.2612, 2.2623, 2.2623, 2.2610, 2.2587,
2.2554, 2.2514, 2.2468, 2.2419, 2.2366, 2.2310,
];
let cands: Vec<f32> = (0..17).map(|k| 394.0 + k as f32 * 0.25).collect();
let v = judge_sweep(&cands, &narrow).unwrap();
assert_eq!(v.resolved(), Some(395.75), "got {v:?}");
}
#[test]
fn judge_sweep_separates_an_optimum_from_a_range_running_out() {
let c = [1.0f32, 2.0, 3.0, 4.0, 5.0];
let v = judge_sweep(&c, &[1.0, 5.0, 9.0, 4.0, 2.0]).unwrap();
assert_eq!(v.resolved(), Some(3.0));
for (score, want) in [
([9.0, 5.0, 3.0, 2.0, 1.0], 0usize),
([1.0, 2.0, 3.0, 5.0, 9.0], 4usize),
] {
let v = judge_sweep(&c, &score).unwrap();
assert!(
matches!(v, SweepVerdict::Railed { index, .. } if index == want),
"a peak at candidate {want} of 5 is a boundary, got {v:?}"
);
assert_eq!(v.resolved(), None);
}
}
const RAMP: [f64; 81] = [
4.1183, 4.1169, 4.1190, 4.1315, 4.1298, 4.1197, 4.1210, 4.1252, 4.1388, 4.1493, 4.1455,
4.1588, 4.1625, 4.1693, 4.1633, 4.1294, 4.1122, 4.1089, 4.0989, 4.0949, 4.1065, 4.1236,
4.1347, 4.1329, 4.1241, 4.1348, 4.1513, 4.1504, 4.1573, 4.1552, 4.1551, 4.1665, 4.1770,
4.1792, 4.1778, 4.1795, 4.1852, 4.1893, 4.1866, 4.1959, 4.2149, 4.2293, 4.2380, 4.2457,
4.2510, 4.2529, 4.2503, 4.2527, 4.2580, 4.2700, 4.2708, 4.2754, 4.2911, 4.3181, 4.3312,
4.3420, 4.3433, 4.3342, 4.3294, 4.3467, 4.3753, 4.3886, 4.4000, 4.4071, 4.4062, 4.3896,
4.3878, 4.3984, 4.4147, 4.4216, 4.4220, 4.4096, 4.4092, 4.4127, 4.4103, 4.4205, 4.4423,
4.4492, 4.4645, 4.4749, 4.4738,
];
#[test]
fn judge_sweep_does_not_answer_from_a_curve_that_only_climbs() {
let cands: Vec<f32> = (0..81).map(|k| 356.0 + k as f32).collect();
let v = judge_sweep(&cands, &RAMP).unwrap();
assert!(
matches!(v, SweepVerdict::Railed { index: 79, .. }),
"an interior maximum one sample short of the edge is still the range \
running out, got {v:?}"
);
assert_eq!(v.resolved(), None, "435 is 39 px from the known 396");
let v = judge_sweep(&cands[..80], &RAMP[..80]).unwrap();
assert!(
matches!(v, SweepVerdict::Railed { index: 79, .. }),
"got {v:?}"
);
}
#[test]
fn sample_band_lands_on_the_measured_spike_at_other_tilts() {
let b = SampleBand {
z: (890, 890),
tilt_deg: 44.0,
};
assert_eq!(b.at(1424, 40.0, 1338), (836, 836));
assert_eq!(b.at(1424, 48.0, 1532), (957, 957));
assert_eq!(b.at(1424, 44.0, 1424), (890, 890));
let wide = SampleBand {
z: (0, 1423),
tilt_deg: 44.0,
};
let (lo, hi) = wide.at(1424, 40.0, 1338);
assert!(hi < 1338, "hi {hi} escaped the 1338-deep target volume");
assert_eq!(lo, 0);
}
#[test]
fn judge_sweep_does_not_answer_from_a_curve_that_never_responded() {
let v = judge_sweep(&[1.0f32, 2.0, 3.0, 4.0], &[0.0; 4]).unwrap();
assert!(matches!(v, SweepVerdict::Flat { .. }), "got {v:?}");
assert_eq!(v.resolved(), None);
}
#[test]
fn judge_sweep_does_not_rail_check_a_degenerate_sweep() {
assert_eq!(judge_sweep(&[7.0], &[1.0]).unwrap().resolved(), Some(7.0));
assert_eq!(
judge_sweep(&[7.0, 8.0], &[9.0, 1.0]).unwrap().resolved(),
Some(7.0)
);
assert!(judge_sweep(&[], &[]).is_none());
assert!(judge_sweep(&[1.0, 2.0], &[1.0]).is_none());
}
const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures");
#[test]
fn ndimage_shift_matches_scipy() {
let input: Array2<f32> = read_npy(format!("{FIXTURES}/ndimage_shift_input.npy")).unwrap();
let outputs: Array3<f32> =
read_npy(format!("{FIXTURES}/ndimage_shift_outputs.npy")).unwrap();
let params: Array2<f64> = read_npy(format!("{FIXTURES}/ndimage_shift_params.npy")).unwrap();
let ncases = params.dim().0;
assert_eq!(outputs.dim().0, ncases);
for k in 0..ncases {
let (sr, sc) = (params[[k, 0]], params[[k, 1]]);
let got = ndimage_shift_spline3_constant(&input, sr, sc);
let want = outputs.index_axis(ndarray::Axis(0), k);
let mut max_abs = 0.0f32;
let mut n_mismatch = 0usize;
for (g, w) in got.iter().zip(want.iter()) {
let d = (g - w).abs();
if d > max_abs {
max_abs = d;
}
if g.to_bits() != w.to_bits() {
n_mismatch += 1;
}
}
assert_eq!(
n_mismatch, 0,
"case {k} shift=({sr},{sc}): {n_mismatch} f32 bit-mismatches vs scipy, max|Δ|={max_abs:e}"
);
}
}
}