tpt-sci-image 0.1.1

n-dimensional image processing and tomographic reconstruction for the tpt-science pillar (built from scratch)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! 3-D tomographic reconstruction: parallel-beam computed tomography of a volume.
//!
//! This extends the 2-D machinery in the crate root to a [`Volume`]. The
//! acquisition rotates the beam about the `z` axis, so each `z` slice is
//! independently Radon-transformed and reconstructed — the 3-D filtered
//! back-projection is exactly a stack of independent 2-D FBP reconstructions
//! (the `z` coordinate is invariant under rotation about `z`). That is a
//! standard, correct parallel-beam volume geometry (it does not model a generic
//! cone beam).
//!
//! * [`radon_transform_3d`] — the forward Radon transform of a [`Volume`]
//!   (one `n_z × n_bins` sinogram [`DMatrix`] per projection angle).
//! * [`filtered_back_projection_3d`] — the ram-lak FBP inverse, returning a
//!   reconstructed [`Volume`].

#[cfg(feature = "rayon")]
use rayon::prelude::*;
use tpt_math_linalg::tpt_math_linalg_dense::DMatrix;

use crate::error::ImageError;
use crate::ramp_filter;

/// A dense 3-D scalar field stored row-major as a flat buffer.
///
/// Voxels are addressed `index = ix + iy·nx + iz·nx·ny` (so `x` is the
/// fastest-varying axis and `z` the slowest), matching the layout of a 3-D
/// structured grid (`nx·ny·nz` nodes).
#[derive(Debug, Clone)]
pub struct Volume {
    /// Node count along `x`.
    pub nx: usize,
    /// Node count along `y`.
    pub ny: usize,
    /// Node count along `z`.
    pub nz: usize,
    /// Flat buffer of `nx·ny·nz` values in `ix + iy·nx + iz·nx·ny` order.
    pub data: Vec<f64>,
}

impl Volume {
    /// Create a zero-filled volume.
    #[must_use]
    pub fn new(nx: usize, ny: usize, nz: usize) -> Self {
        Self {
            nx,
            ny,
            nz,
            data: vec![0.0; nx * ny * nz],
        }
    }

    /// Build a volume from a closure `f(ix, iy, iz) -> value`.
    #[must_use]
    pub fn from_fn(
        nx: usize,
        ny: usize,
        nz: usize,
        f: impl Fn(usize, usize, usize) -> f64,
    ) -> Self {
        let mut data = vec![0.0; nx * ny * nz];
        for iz in 0..nz {
            for iy in 0..ny {
                for ix in 0..nx {
                    data[ix + iy * nx + iz * nx * ny] = f(ix, iy, iz);
                }
            }
        }
        Self { nx, ny, nz, data }
    }

    /// Lexicographic voxel index `ix + iy·nx + iz·nx·ny`.
    #[must_use]
    pub fn index(&self, ix: usize, iy: usize, iz: usize) -> usize {
        ix + iy * self.nx + iz * self.nx * self.ny
    }

    /// Total voxel count `nx·ny·nz`.
    #[must_use]
    pub fn len(&self) -> usize {
        self.nx * self.ny * self.nz
    }

    /// Whether the volume is empty (`nx·ny·nz == 0`).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// Bilinear sample of the `z` slice of `vol` at fractional `(col, row)` in the
/// `x`/`y` plane. Out-of-extent coordinates return `0.0`.
fn sample_slice(vol: &Volume, z: usize, col: f64, row: f64) -> f64 {
    let nrows = vol.ny as f64;
    let ncols = vol.nx as f64;
    if col < 0.0 || row < 0.0 || col > ncols - 1.0 || row > nrows - 1.0 {
        return 0.0;
    }
    let c0 = col.floor() as usize;
    let r0 = row.floor() as usize;
    let c1 = (c0 + 1).min(vol.nx - 1);
    let r1 = (r0 + 1).min(vol.ny - 1);
    let dc = col - c0 as f64;
    let dr = row - r0 as f64;
    let base = vol.index(0, 0, z);
    let v00 = vol.data[base + c0 + r0 * vol.nx];
    let v01 = vol.data[base + c1 + r0 * vol.nx];
    let v10 = vol.data[base + c0 + r1 * vol.nx];
    let v11 = vol.data[base + c1 + r1 * vol.nx];
    v00 * (1.0 - dc) * (1.0 - dr) + v01 * dc * (1.0 - dr) + v10 * (1.0 - dc) * dr + v11 * dc * dr
}

/// Linear interpolation of a 1-D projection at fractional bin `x`. Returns `0.0`
/// for out-of-range positions.
fn sample_1d(v: &[f64], x: f64) -> f64 {
    let n = v.len();
    if n == 0 || x < 0.0 || x > (n - 1) as f64 {
        return 0.0;
    }
    let i0 = x.floor() as usize;
    let i1 = (i0 + 1).min(n - 1);
    let d = x - i0 as f64;
    v[i0] * (1.0 - d) + v[i1] * d
}

/// Trilinear sample of `vol` at fractional voxel coordinates `(x, y, z)`.
///
/// Unlike [`sample_slice`] (which only interpolates within a fixed `z`
/// slice, sufficient for the parallel-beam geometry where rays never move in
/// `z`), this interpolates all three axes — required for the divergent rays
/// of [`crate::cone_beam`]. Out-of-extent coordinates return `0.0`.
pub(crate) fn sample_trilinear(vol: &Volume, x: f64, y: f64, z: f64) -> f64 {
    let nx = vol.nx as f64;
    let ny = vol.ny as f64;
    let nz = vol.nz as f64;
    if x < 0.0 || y < 0.0 || z < 0.0 || x > nx - 1.0 || y > ny - 1.0 || z > nz - 1.0 {
        return 0.0;
    }
    let x0 = x.floor() as usize;
    let y0 = y.floor() as usize;
    let z0 = z.floor() as usize;
    let x1 = (x0 + 1).min(vol.nx - 1);
    let y1 = (y0 + 1).min(vol.ny - 1);
    let z1 = (z0 + 1).min(vol.nz - 1);
    let dx = x - x0 as f64;
    let dy = y - y0 as f64;
    let dz = z - z0 as f64;

    let at = |ix: usize, iy: usize, iz: usize| -> f64 { vol.data[vol.index(ix, iy, iz)] };

    let c00 = at(x0, y0, z0) * (1.0 - dx) + at(x1, y0, z0) * dx;
    let c10 = at(x0, y1, z0) * (1.0 - dx) + at(x1, y1, z0) * dx;
    let c01 = at(x0, y0, z1) * (1.0 - dx) + at(x1, y0, z1) * dx;
    let c11 = at(x0, y1, z1) * (1.0 - dx) + at(x1, y1, z1) * dx;
    let c0 = c00 * (1.0 - dy) + c10 * dy;
    let c1 = c01 * (1.0 - dy) + c11 * dy;
    c0 * (1.0 - dz) + c1 * dz
}

/// Forward 3-D Radon transform (parallel beam, rotation about `z`) of `volume`
/// over `angles`.
///
/// Returns one sinogram [`DMatrix`] per angle. Each sinogram has `n_z` rows (one
/// per `z` slice) and `n_bins = max(nx, ny)` columns (the beam-direction
/// detector bins), following the same centre convention and rotation sense as
/// the crate-root [`crate::radon_transform`].
///
/// # Errors
///
/// Returns [`ImageError::EmptyImage`] if the volume has no voxels, or
/// [`ImageError::EmptyAngles`] if `angles` is empty.
pub fn radon_transform_3d(
    volume: &Volume,
    angles: &[f64],
) -> Result<Vec<DMatrix<f64>>, ImageError> {
    if volume.is_empty() {
        return Err(ImageError::EmptyImage {
            nrows: volume.ny,
            ncols: volume.nx,
        });
    }
    if angles.is_empty() {
        return Err(ImageError::EmptyAngles);
    }
    let nb = volume.nx.max(volume.ny);
    let c = (nb - 1) as f64 / 2.0;
    let cx = (volume.nx - 1) as f64 / 2.0;
    let cy = (volume.ny - 1) as f64 / 2.0;

    let mut out = Vec::with_capacity(angles.len());
    for &theta in angles {
        let cos = theta.cos();
        let sin = theta.sin();
        let mut proj = vec![0.0_f64; volume.nz * nb];
        for z in 0..volume.nz {
            for i in 0..nb {
                let u = i as f64 - c;
                for j in 0..nb {
                    let v = j as f64 - c;
                    let sx = cos * u - sin * v;
                    let sy = sin * u + cos * v;
                    proj[z * nb + i] += sample_slice(volume, z, sx + cx, sy + cy);
                }
            }
        }
        out.push(DMatrix::from_fn(volume.nz, nb, |z, i| proj[z * nb + i]));
    }
    Ok(out)
}

/// Filtered back-projection (FBP) reconstruction of a [`Volume`] from a 3-D
/// sinogram stack.
///
/// Each angle's sinogram (one `[n_z × n_bins]` [`DMatrix`] from
/// [`radon_transform_3d`]) is ramp-filtered per `z` row and back-projected. The
/// reconstruction has dimensions `nx × ny × nz`, which must match the volume
/// that produced the sinograms (`n_bins = max(nx, ny)`).
///
/// # Errors
///
/// Returns [`ImageError::EmptyAngles`] if `angles` is empty,
/// [`ImageError::EmptyImage`] if `nx`/`ny`/`nz` is zero,
/// [`ImageError::AngleCountMismatch`] if the sinogram count disagrees with the
/// angle count, or [`ImageError::DimensionMismatch`] if a sinogram's dimensions
/// are not `n_z × max(nx, ny)`.
pub fn filtered_back_projection_3d(
    sinograms: &[DMatrix<f64>],
    angles: &[f64],
    nx: usize,
    ny: usize,
    nz: usize,
) -> Result<Volume, ImageError> {
    if angles.is_empty() {
        return Err(ImageError::EmptyAngles);
    }
    if nx == 0 || ny == 0 || nz == 0 {
        return Err(ImageError::EmptyImage {
            nrows: ny,
            ncols: nx,
        });
    }
    if sinograms.len() != angles.len() {
        return Err(ImageError::AngleCountMismatch {
            sino_rows: sinograms.len(),
            n_angles: angles.len(),
        });
    }
    let nb = nx.max(ny);
    for s in sinograms {
        if s.ncols() != nb {
            return Err(ImageError::DimensionMismatch {
                expected: nb,
                got: s.ncols(),
            });
        }
        if s.nrows() != nz {
            return Err(ImageError::DimensionMismatch {
                expected: nz,
                got: s.nrows(),
            });
        }
    }

    let c = (nb - 1) as f64 / 2.0;
    let cx = (nx - 1) as f64 / 2.0;
    let cy = (ny - 1) as f64 / 2.0;

    // Pre-filter each sinogram row (per z) once.
    let mut filtered: Vec<Vec<Vec<f64>>> = Vec::with_capacity(sinograms.len());
    for s in sinograms {
        let mut rows = Vec::with_capacity(s.nrows());
        for z in 0..s.nrows() {
            let row: Vec<f64> = (0..s.ncols()).map(|j| s[(z, j)]).collect();
            rows.push(ramp_filter(&row));
        }
        filtered.push(rows);
    }

    let mut rec = vec![0.0_f64; nx * ny * nz];
    let trig: Vec<(f64, f64)> = angles.iter().map(|&theta| theta.sin_cos()).collect();
    let slice_len = nx * ny;
    // Each z slice is a contiguous, disjoint chunk of `rec` and depends only on
    // its own filtered rows, so slices are reconstructed independently. Under the
    // `rayon` feature they run in parallel; the per-slice arithmetic is identical,
    // so the output does not depend on the feature.
    let fill_slice = |iz: usize, out: &mut [f64]| {
        for (a, &(sin, cos)) in trig.iter().enumerate() {
            for iy in 0..ny {
                let y = iy as f64 - cy;
                for ix in 0..nx {
                    let x = ix as f64 - cx;
                    let t = -sin * x + cos * y;
                    out[ix + iy * nx] += sample_1d(&filtered[a][iz], t + c);
                }
            }
        }
    };
    #[cfg(feature = "rayon")]
    rec.par_chunks_mut(slice_len)
        .enumerate()
        .for_each(|(iz, out)| fill_slice(iz, out));
    #[cfg(not(feature = "rayon"))]
    rec.chunks_mut(slice_len)
        .enumerate()
        .for_each(|(iz, out)| fill_slice(iz, out));

    // Same empirical FBP normalisation as the 2-D API: `4.0 / (nb · n_angles)`
    // matches the discrete ramp filter's DC gain to the continuous kernel and
    // absorbs the Δθ / Δs pixel-area factors (Kak & Slaney, *Principles of
    // Computerized Tomographic Imaging*, §3.3). Each `z` slice is reconstructed
    // independently, so the 1-D detector-bin count `nb` is the slice width.
    let scale = 4.0 / nb as f64 / angles.len() as f64;
    for v in &mut rec {
        *v *= scale;
    }
    Ok(Volume {
        nx,
        ny,
        nz,
        data: rec,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn radon_3d_dimensions() {
        let v = Volume::from_fn(16, 16, 8, |ix, iy, iz| {
            if ix == 8 && iy == 8 && iz == 4 {
                1.0
            } else {
                0.0
            }
        });
        let angles = crate::linspace(0.0, std::f64::consts::PI, 16);
        let sino = radon_transform_3d(&v, &angles).unwrap();
        assert_eq!(sino.len(), 16);
        for s in &sino {
            assert_eq!(s.nrows(), 8);
            assert_eq!(s.ncols(), 16);
        }
    }

    #[test]
    fn fbp_3d_recovers_point_source() {
        let n = 16usize;
        let v = Volume::from_fn(n, n, n, |ix, iy, iz| {
            if ix == n / 2 && iy == n / 2 && iz == n / 2 {
                1.0
            } else {
                0.0
            }
        });
        let angles = crate::linspace(0.0, std::f64::consts::PI, 32);
        let sino = radon_transform_3d(&v, &angles).unwrap();
        let rec = filtered_back_projection_3d(&sino, &angles, n, n, n).unwrap();

        let c = rec.data[rec.index(n / 2, n / 2, n / 2)];
        assert!(c > 0.0, "centre should be positive");
        let mean = rec.data.iter().sum::<f64>() / rec.data.len() as f64;
        assert!(
            c >= mean,
            "centre should be at least the mean (c={c}, mean={mean})"
        );
    }

    #[test]
    fn fbp_3d_beats_naive_3d() {
        let n = 24usize;
        let sigma = 3.0_f64;
        let (cx, cy, cz) = (n as f64 / 2.0, n as f64 / 2.0, n as f64 / 2.0);
        let orig = Volume::from_fn(n, n, n, |ix, iy, iz| {
            let dx = ix as f64 - cx;
            let dy = iy as f64 - cy;
            let dz = iz as f64 - cz;
            (-(dx * dx + dy * dy + dz * dz) / (2.0 * sigma * sigma)).exp()
        });
        let angles = crate::linspace(0.0, std::f64::consts::PI, 40);
        let sino = radon_transform_3d(&orig, &angles).unwrap();
        let rec = filtered_back_projection_3d(&sino, &angles, n, n, n).unwrap();

        let naive = naive_back_projection_3d(&sino, &angles, n, n, n);
        let mut fbp_err = 0.0;
        let mut naive_err = 0.0;
        let mut count = 0;
        let b = 3;
        for iz in b..n - b {
            for iy in b..n - b {
                for ix in b..n - b {
                    let k = orig.index(ix, iy, iz);
                    fbp_err += (rec.data[k] - orig.data[k]).abs();
                    naive_err += (naive.data[k] - orig.data[k]).abs();
                    count += 1;
                }
            }
        }
        fbp_err /= count as f64;
        naive_err /= count as f64;
        assert!(
            fbp_err < naive_err,
            "FBP error {fbp_err} should be below naive error {naive_err}"
        );
    }

    #[test]
    fn radon_3d_rejects_empty() {
        let empty = Volume::new(0, 4, 4);
        let angles = crate::linspace(0.0, std::f64::consts::PI, 8);
        assert!(matches!(
            radon_transform_3d(&empty, &angles),
            Err(ImageError::EmptyImage { .. })
        ));
        let v = Volume::from_fn(4, 4, 4, |_, _, _| 1.0);
        assert!(matches!(
            radon_transform_3d(&v, &[]),
            Err(ImageError::EmptyAngles)
        ));
    }

    /// Unfiltered (naive) 3-D back-projection, used only to show that ramp
    /// filtering improves the reconstruction.
    fn naive_back_projection_3d(
        sinograms: &[DMatrix<f64>],
        angles: &[f64],
        nx: usize,
        ny: usize,
        nz: usize,
    ) -> Volume {
        let nb = nx.max(ny);
        let c = (nb - 1) as f64 / 2.0;
        let cx = (nx - 1) as f64 / 2.0;
        let cy = (ny - 1) as f64 / 2.0;
        let mut rec = vec![0.0_f64; nx * ny * nz];
        for (a, &theta) in angles.iter().enumerate() {
            let cos = theta.cos();
            let sin = theta.sin();
            for iz in 0..nz {
                let row: Vec<f64> = (0..sinograms[a].ncols())
                    .map(|j| sinograms[a][(iz, j)])
                    .collect();
                for iy in 0..ny {
                    let y = iy as f64 - cy;
                    for ix in 0..nx {
                        let x = ix as f64 - cx;
                        let t = -sin * x + cos * y;
                        let bin = t + c;
                        let val = sample_1d(&row, bin);
                        rec[ix + iy * nx + iz * nx * ny] += val;
                    }
                }
            }
        }
        let scale = 4.0 / nb as f64 / angles.len() as f64;
        for v in &mut rec {
            *v *= scale;
        }
        Volume {
            nx,
            ny,
            nz,
            data: rec,
        }
    }
}