tomoxide 0.14.0

GPU/CPU tomographic reconstruction toolkit (tomopy + tomocupy, in Rust)
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
//! # tomoxide-recon
//!
//! Backend-agnostic reconstruction. The single [`recon`] entry point dispatches
//! every [`Algorithm`] to backend capability traits, so the same code path runs
//! on CPU, CUDA, or wgpu. It depends on `tomoxide-core` only โ€” never on a
//! concrete backend.
//!
//! Analytic methods (`fbp`, `gridrec`, `fourierrec`, `lprec`, `linerec`) are a
//! filter + back-projection pass; iterative methods compose forward projection
//! and back-projection in a loop (see `docs/ARCHITECTURE.md` ยง3).
//!
//! Laminography ([`lamino`]) is intrinsically 3-D โ€” every tilted projection
//! contributes to every voxel โ€” so it has its own entry point
//! ([`lamino::lamino`]) rather than the per-slice [`recon`] dispatch.
#![forbid(unsafe_code)]

pub mod center;
pub(crate) mod fourierrec;
mod gridrec;
pub mod lamino;
pub(crate) mod lprec;
pub mod ring;
pub mod tilt_flow;
pub mod vector;

use crate::backend::{Backend, FilteredBackproject, ForwardProject, RayProject, RayRow};
use crate::data::{Layout, Tomo, Volume};
use crate::error::{Error, Result};
use crate::geometry::{Angles, Beam, Center, Geometry};
use crate::params::{Algorithm, ReconParams};
use ndarray::{Array3, Axis};

fn missing(capability: &'static str, backend: &dyn Backend) -> Error {
    Error::MissingCapability {
        backend: backend.name(),
        capability,
    }
}

/// Reconstruct a volume from a sinogram stack with the given algorithm.
///
/// `sino` is consumed by neither path (it is cloned where filtering mutates a
/// copy). The output volume is `[n_rows, n_grid, n_grid]`.
pub fn recon(
    sino: &Tomo<f32>,
    geom: &Geometry,
    algorithm: Algorithm,
    params: &ReconParams,
    backend: &dyn Backend,
) -> Result<Volume<f32>> {
    if algorithm.is_analytic() {
        analytic(sino, geom, algorithm, params, backend)
    } else {
        iterative(sino, geom, algorithm, params, backend)
    }
}

/// Grid size for the output slice (defaults to the detector width).
fn grid_size(sino: &Tomo<f32>, params: &ReconParams) -> usize {
    params.num_gridx.unwrap_or_else(|| sino.n_cols())
}

/// Starting iterate for an iterative solver: the warm-start `params.init` volume
/// when provided (validated to `[nz, n, n]`), else a constant-`default` volume
/// (SIRT/TV seed with 0, the EM methods with 1). This is the single site that
/// turns a caller's chained reconstruction into an initial guess.
fn init_volume(params: &ReconParams, nz: usize, n: usize, default: f32) -> Result<Volume<f32>> {
    match &params.init {
        Some(v) => {
            if v.dims() != (nz, n, n) {
                return Err(Error::ShapeMismatch {
                    expected: format!("init volume [{nz}, {n}, {n}]"),
                    found: format!("{:?}", v.dims()),
                });
            }
            Ok(v.clone())
        }
        None => Ok(Volume::new(Array3::from_elem((nz, n, n), default))),
    }
}

fn analytic(
    sino: &Tomo<f32>,
    geom: &Geometry,
    algorithm: Algorithm,
    params: &ReconParams,
    backend: &dyn Backend,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let nz = sino.n_rows();

    // gridrec is a Fourier-grid method that applies its own ramp internally
    // (needs only the Fft capability). Every other analytic method is a shared
    // FBP-filter pass followed by either a Fourier-grid gridding (fourierrec) or
    // a back-projection (fbp/linerec/lprec) โ€” tomocupy's
    // `fbp_filter_center(data)` โ†’ `cl_rec.backprojection`.
    if algorithm == Algorithm::Gridrec {
        let fft = backend.fft().ok_or_else(|| missing("Fft", backend))?;
        return Ok(Volume::new(gridrec::gridrec(sino, geom, n, fft)?));
    }
    // A backend with a fused on-device analytic path (CUDA) runs the whole
    // filter โ†’ back-projection / Fourier chain resident on the device โ€” one
    // upload, one download โ€” instead of host-roundtripping each capability.
    if matches!(
        algorithm,
        Algorithm::Fbp | Algorithm::Linerec | Algorithm::Fourierrec
    ) {
        if let Some(ar) = backend.analytic_reconstruct() {
            return ar.reconstruct(sino, geom, algorithm, params);
        }
    }
    let filt = backend
        .fbp_filter()
        .ok_or_else(|| missing("FbpFilter", backend))?;
    let kernel = filt.make_filter(params.filter_name, sino.n_cols())?;
    let mut filtered = sino.clone();
    filt.apply(&mut filtered, &kernel, geom)?;

    // fourierrec grids the filtered projections onto the Fourier plane with
    // tomocupy's Gaussian USFFT kernel. A backend with a monolithic Fourier
    // method (CUDA cfunc_fourierrec) handles it directly; otherwise it composes
    // from the generic Fft capability (CPU/wgpu).
    if algorithm == Algorithm::Fourierrec {
        if let Some(fr) = backend.fourier_reconstruct() {
            return fr.reconstruct(&filtered, geom, n);
        }
        let fft = backend.fft().ok_or_else(|| missing("Fft", backend))?;
        return Ok(Volume::new(fourierrec::fourierrec(
            &filtered, geom, n, fft,
        )?));
    }

    // lprec is the log-polar (Anderssonโ€“Carlssonโ€“Nikitin) method: it maps the
    // filtered sinogram into log-polar coordinates where back-projection is a 2-D
    // FFT convolution, then resamples to the Cartesian grid (needs only the Fft
    // capability). Faithful port of tomocupy `lprec`.
    if algorithm == Algorithm::Lprec {
        // A backend with a device-resident lprec (CUDA cuda/lprec.cu) runs the
        // gather/scatter + spline prefilter on the GPU; otherwise it composes
        // from the generic Fft capability (CPU/wgpu) with host interpolation.
        if let Some(lr) = backend.lprec_reconstruct() {
            return lr.reconstruct(&filtered, geom, n);
        }
        let fft = backend.fft().ok_or_else(|| missing("Fft", backend))?;
        return Ok(Volume::new(lprec::lprec(&filtered, geom, n, fft)?));
    }

    // fbp / linerec: filtered back-projection. linerec is genuinely a line
    // back-projection (tomocupy `cfunc_linerec` reduces to parallel-beam BP with
    // linear interpolation), so it shares this FBP path. `FbpFilter::apply` has
    // already shifted the rotation axis onto the detector midpoint, so the
    // back-projector runs against a centre = ncols/2 geometry โ€” matching
    // tomocupy, whose back-projection kernels assume n/2 after fbp_filter_center.
    // (The iterative path keeps `geom.center`; only this analytic path recenters.)
    let bp = backend
        .backprojector()
        .ok_or_else(|| missing("FilteredBackproject", backend))?;
    let centered = Geometry {
        center: Center::Scalar(sino.n_cols() as f32 / 2.0),
        ..geom.clone()
    };
    let mut vol = Volume::new(Array3::zeros((nz, n, n)));
    bp.backproject(&filtered, &centered, &mut vol)?;
    // FBP angular quadrature: the back-projection integral โˆซโ‚€^ฯ€ โ€ฆ dฮธ discretizes
    // to a sum weighted by dฮธ = ฯ€/nang. `FilteredBackproject` is the *pure*
    // adjoint Wแต€ (the iterative solvers need it unweighted), so the analytic
    // path owns this weight โ€” matching the fused CUDA/wgpu analytic paths, which
    // pass the same ฯ€/nproj gain to their kernels.
    let dtheta = std::f32::consts::PI / sino.n_angles() as f32;
    vol.array.mapv_inplace(|v| v * dtheta);
    Ok(vol)
}

fn iterative(
    sino: &Tomo<f32>,
    geom: &Geometry,
    algorithm: Algorithm,
    params: &ReconParams,
    backend: &dyn Backend,
) -> Result<Volume<f32>> {
    // Every iterative method consumes an initial iterate except the row-action
    // pair (ART/BART), which sweep single rays and have no whole-volume seed.
    // Reject a warm-start there rather than silently dropping the caller's seed.
    if params.init.is_some() && matches!(algorithm, Algorithm::Art | Algorithm::Bart) {
        return Err(Error::InvalidParam(
            "warm-start `init` is not supported for row-action ART/BART".into(),
        ));
    }

    // Truncated-projection support extension: solve on an edge-replicate
    // extended lane + wider grid, return the central crop. Sits above the
    // backend dispatch so CPU, CUDA, and wgpu all see the identical extended
    // problem (see `ReconParams::ext_pad`).
    if params.ext_pad {
        return ext_pad_solve(sino, geom, algorithm, params, backend);
    }

    // ART/BART are row-action (Kaczmarz) โ€” they consume the single-ray rows, not
    // the whole-sinogram forward/back-projectors the other methods compose.
    if matches!(algorithm, Algorithm::Art | Algorithm::Bart) {
        let rp = backend
            .ray_projector()
            .ok_or_else(|| missing("RayProject", backend))?;
        return match algorithm {
            Algorithm::Art => art(sino, geom, params, rp),
            _ => bart(sino, geom, params, rp),
        };
    }

    // Device-resident fast path: a backend that keeps the volume/sinogram on the
    // device across all iterations (CUDA) runs the whole loop with no per-iteration
    // hostโ†”device transfers. It returns `None` for algorithms it does not
    // device-implement, so those fall through to the generic host solvers below. A
    // warm-start `init` is uploaded once by the device solver, so it is honoured
    // here too (ART/BART were already rejected above and never reach this path).
    if let Some(it) = backend.iterative_reconstruct() {
        if let Some(vol) = it.solve(sino, geom, algorithm, params)? {
            return Ok(vol);
        }
    }

    // Laminography is not slice-separable โ€” the tilted axis couples every
    // detector row into every output voxel. The generic solvers whose step size
    // is a per-slice scalar (CGLS/GRAD/TIKH treat each detector row โ†” its own
    // independent output slice, a parallel-beam optimization) therefore do not
    // converge for a tilted axis. Reject them explicitly rather than returning a
    // silently-wrong volume; the structurally-global solvers (SIRT/MLEM/OSEM/
    // OSPML/PML/TV โ€” per-voxel/per-ray diagonal weights) handle laminography.
    if matches!(geom.beam, Beam::Laminography { .. })
        && matches!(
            algorithm,
            Algorithm::Cgls | Algorithm::Grad | Algorithm::Tikh
        )
    {
        return Err(Error::InvalidParam(format!(
            "laminography iterative reconstruction does not support {algorithm:?}: its \
             per-slice step size assumes parallel-beam slice-separability; use \
             SIRT/MLEM/OSEM/OSPML/PML/TV"
        )));
    }
    let proj = backend
        .projector()
        .ok_or_else(|| missing("ForwardProject", backend))?;
    let bp = backend
        .backprojector()
        .ok_or_else(|| missing("FilteredBackproject", backend))?;
    match algorithm {
        Algorithm::Sirt => sirt(sino, geom, params, proj, bp),
        Algorithm::Mlem => mlem(sino, geom, params, proj, bp),
        Algorithm::Osem => osem(sino, geom, params, proj, bp),
        // pml_* are ospml_* with a single block (tomopy extern/recon.py). The
        // quadratic prior is delta=None; the hybrid prior uses reg_par[1] as the
        // edge threshold (None if absent โ‡’ degenerates to the quadratic prior).
        Algorithm::OspmlQuad => ospml(sino, geom, params, proj, bp, params.num_block, None),
        Algorithm::PmlQuad => ospml(sino, geom, params, proj, bp, 1, None),
        Algorithm::OspmlHybrid => ospml(
            sino,
            geom,
            params,
            proj,
            bp,
            params.num_block,
            params.reg_par.get(1).copied(),
        ),
        Algorithm::PmlHybrid => ospml(
            sino,
            geom,
            params,
            proj,
            bp,
            1,
            params.reg_par.get(1).copied(),
        ),
        Algorithm::Grad => grad(sino, geom, params, proj, bp),
        Algorithm::Tikh => tikh(sino, geom, params, proj, bp),
        Algorithm::Cgls => cgls(sino, geom, params, proj, bp),
        Algorithm::Tv => tv(sino, geom, params, proj, bp),
        // Vector tomography reconstructs a vector field from one to three tilt
        // datasets, so it can't fit the scalar (one sinogram โ†’ one volume)
        // signature here. It lives in [`vector`] with its own multi-dataset API.
        Algorithm::Vector => Err(Error::InvalidParam(
            "vector tomography is not a scalar reconstruction; call \
             crate::recon::vector::{vector,vector2,vector3} directly"
                .into(),
        )),
        // Analytic methods are dispatched by `recon()` โ†’ `analytic()`, and
        // Art/Bart by the ray-projector path above, so they never reach here.
        _ => unreachable!("non-iterative algorithm reached iterative dispatch"),
    }
}

/// Truncated-projection support extension (`ReconParams::ext_pad`).
///
/// Edge-replicate extends every projection by `pad = ncols/4` columns per
/// side, shifts the rotation center by `pad`, solves the same algorithm on
/// the `n + 2ยทpad` grid, and returns the central `n ร— n` crop. The extension
/// gives out-of-view mass a support region to land in, so the least-squares
/// fit stops dumping the truncation inconsistency into a FOV-edge ring โ€” the
/// iterative analog of the edge-replicate padding the analytic filter step
/// (`FbpFilter::apply`) and gridrec already apply. A warm-start `init` and a
/// Tikhonov `reg_data` prior are embedded centered (zero ring); the pad-ring
/// state is not part of the caller-visible volume, so a split warm-started
/// run is *approximately* โ€” not bit โ€” equal to a continuous one under
/// `ext_pad`.
fn ext_pad_solve(
    sino: &Tomo<f32>,
    geom: &Geometry,
    algorithm: Algorithm,
    params: &ReconParams,
    backend: &dyn Backend,
) -> Result<Volume<f32>> {
    let b = sino.as_layout(Layout::Sinogram);
    let (nz, nang, ncols) = (b.n_rows(), b.n_angles(), b.n_cols());
    let n = grid_size(sino, params);
    let pad = (ncols / 4).max(1);
    let ncols_ext = ncols + 2 * pad;
    let n_ext = n + 2 * pad;

    // Edge-replicate extended sinogram, [nz, nang, ncols_ext].
    let mut ext = Array3::<f32>::zeros((nz, nang, ncols_ext));
    for iz in 0..nz {
        for ia in 0..nang {
            let src = b.array.index_axis(Axis(0), iz);
            let row = src.index_axis(Axis(0), ia);
            let mut dst = ext.index_axis_mut(Axis(0), iz);
            let mut dst = dst.index_axis_mut(Axis(0), ia);
            let (first, last) = (row[0], row[ncols - 1]);
            for j in 0..pad {
                dst[j] = first;
                dst[pad + ncols + j] = last;
            }
            for j in 0..ncols {
                dst[pad + j] = row[j];
            }
        }
    }
    let sino_ext = Tomo::new(ext, Layout::Sinogram);

    // Same geometry on the wider lane: rotation center shifts with the pad.
    let mut geom_ext = geom.clone();
    geom_ext.detector.width = ncols_ext;
    geom_ext.center = match &geom.center {
        Center::Scalar(c) => Center::Scalar(c + pad as f32),
        Center::PerRow(v) => Center::PerRow(v.iter().map(|c| c + pad as f32).collect()),
    };

    // Embed an `[nz, n, n]` volume centered in the `[nz, n_ext, n_ext]` grid.
    // (`slice_axis`, not the `s![]` macro โ€” the macro expands with an
    // `allow(unsafe_code)` that this module's `forbid` rejects.)
    let core = ndarray::Slice::from(pad..pad + n);
    let embed = |src: &Array3<f32>| -> Array3<f32> {
        let mut out = Array3::<f32>::zeros((nz, n_ext, n_ext));
        let mut view = out.slice_axis_mut(Axis(1), core);
        view.slice_axis_mut(Axis(2), core).assign(src);
        out
    };
    let mut params_ext = params.clone();
    params_ext.ext_pad = false; // solve the extended problem plainly
    params_ext.num_gridx = Some(n_ext);
    params_ext.num_gridy = params.num_gridy.map(|_| n_ext);
    if let Some(v) = &params.init {
        if v.dims() != (nz, n, n) {
            return Err(Error::ShapeMismatch {
                expected: format!("init volume [{nz}, {n}, {n}]"),
                found: format!("{:?}", v.dims()),
            });
        }
        params_ext.init = Some(Volume::new(embed(&v.array)));
    }
    if params.reg_data.len() == nz * n * n {
        let prior =
            Array3::from_shape_vec((nz, n, n), params.reg_data.clone()).expect("len checked above");
        params_ext.reg_data = embed(&prior).into_raw_vec_and_offset().0;
    }

    let vol = iterative(&sino_ext, &geom_ext, algorithm, &params_ext, backend)?;
    Ok(Volume::new(
        vol.array
            .slice_axis(Axis(1), core)
            .slice_axis(Axis(2), core)
            .to_owned(),
    ))
}

/// Simultaneous Iterative Reconstruction Technique.
///
/// R/C-weighted update `x โ† x + C โˆ˜ Aแต€(R โˆ˜ (b โˆ’ A x))` with `R = 1/A(1)`
/// (per-ray length) and `C = 1/Aแต€(1)` (per-pixel sensitivity). This is the
/// parameter-free, convergent form of tomopy's rotation-based SIRT (which
/// distributes the per-ray residual by `1/nx` and averages over angles โ€”
/// exactly `R` and `C` here). `A` = forward projector, `Aแต€` = back-projector.
fn sirt(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let nz = sino.n_rows();
    let b = sino.as_layout(Layout::Sinogram);
    let nang = b.n_angles();
    let ncols = b.n_cols();

    // Ray-length weights R = 1 / A(1).
    let ones_img = Volume::new(Array3::from_elem((nz, n, n), 1.0));
    let mut ray = Tomo::new(Array3::zeros((nz, nang, ncols)), Layout::Sinogram);
    proj.project(&ones_img, geom, &mut ray)?;
    let rw = ray
        .array
        .mapv(|v| if v.abs() > 1e-6 { 1.0 / v } else { 0.0 });

    // Sensitivity weights C = 1 / Aแต€(1).
    let ones_sino = Tomo::new(Array3::from_elem((nz, nang, ncols), 1.0), Layout::Sinogram);
    let mut sens = Volume::new(Array3::zeros((nz, n, n)));
    bp.backproject(&ones_sino, geom, &mut sens)?;
    let cw = sens
        .array
        .mapv(|v| if v.abs() > 1e-6 { 1.0 / v } else { 0.0 });

    let mut vol = init_volume(params, nz, n, 0.0)?;
    let mut ax = Tomo::new(Array3::zeros((nz, nang, ncols)), Layout::Sinogram);
    let mut corr = Volume::new(Array3::zeros((nz, n, n)));
    for _ in 0..params.num_iter.max(1) {
        proj.project(&vol, geom, &mut ax)?; // A x
        let mut resid = &b.array - &ax.array; // b โˆ’ A x
        resid *= &rw; // R โˆ˜ (b โˆ’ A x)
        bp.backproject(&Tomo::new(resid, Layout::Sinogram), geom, &mut corr)?;
        vol.array += &(&cw * &corr.array); // x += C โˆ˜ Aแต€(โ€ฆ)
    }
    Ok(vol)
}

/// Maximum-Likelihood Expectation-Maximization.
///
/// Multiplicative update `x โ† x โˆ˜ Aแต€(b โŠ˜ A x) โŠ˜ Aแต€(1)`, positivity-preserving
/// from a positive initial guess; requires a non-negative sinogram. Ports the
/// EM update of tomopy `accel/cxx/mlem.cc`. `A` = forward projector,
/// `Aแต€` = back-projector.
fn mlem(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let nz = sino.n_rows();
    let b = sino.as_layout(Layout::Sinogram);
    let nang = b.n_angles();
    let ncols = b.n_cols();

    // Sensitivity Aแต€(1).
    let ones_sino = Tomo::new(Array3::from_elem((nz, nang, ncols), 1.0), Layout::Sinogram);
    let mut sens = Volume::new(Array3::zeros((nz, n, n)));
    bp.backproject(&ones_sino, geom, &mut sens)?;

    let mut vol = init_volume(params, nz, n, 1.0)?; // positive init (or warm-start)
    let mut ax = Tomo::new(Array3::zeros((nz, nang, ncols)), Layout::Sinogram);
    let mut corr = Volume::new(Array3::zeros((nz, n, n)));
    for _ in 0..params.num_iter.max(1) {
        proj.project(&vol, geom, &mut ax)?; // A x
        let mut ratio = b.array.clone();
        ndarray::Zip::from(&mut ratio)
            .and(&ax.array)
            .for_each(|r, &a| {
                *r = if a.abs() > 1e-6 { *r / a } else { 0.0 }; // b โŠ˜ A x
            });
        bp.backproject(&Tomo::new(ratio, Layout::Sinogram), geom, &mut corr)?;
        ndarray::Zip::from(&mut vol.array)
            .and(&corr.array)
            .and(&sens.array)
            .for_each(|x, &c, &s| {
                if s.abs() > 1e-6 {
                    *x = *x * c / s; // x โˆ˜ Aแต€(ratio) โŠ˜ sens
                }
            });
    }
    Ok(vol)
}

/// Partition the `nang` angle indices into ordered subsets, matching tomopy
/// `osem.c`: each subset is a contiguous slice of the angle *ordering* โ€” the
/// caller's `ind_block` permutation when it has length `nang`, else the identity
/// `0..nang`. Subset `os` has `nang/num_block + (os < nang % num_block)` angles,
/// so the blocks tile `0..nang` exactly. `num_block` is clamped to `1..=nang`,
/// and `1` yields the single full-angle subset (i.e. plain MLEM).
pub(crate) fn ordered_subsets(nang: usize, params: &ReconParams) -> Vec<Vec<usize>> {
    let num_block = params.num_block.clamp(1, nang.max(1));
    let order: Vec<usize> = if params.ind_block.len() == nang {
        params.ind_block.iter().map(|&i| i as usize).collect()
    } else {
        (0..nang).collect()
    };
    let blocksize = nang / num_block;
    let remainder = nang % num_block;
    let mut subsets = Vec::with_capacity(num_block);
    let mut start = 0;
    for os in 0..num_block {
        let len = blocksize + usize::from(os < remainder);
        subsets.push(order[start..start + len].to_vec());
        start += len;
    }
    subsets
}

/// One ordered subset: its sub-geometry, measured sinogram slice `[nz, len,
/// ncols]`, and the iteration-invariant sensitivity `Aโ‚›แต€(1)` `[nz, n, n]`.
struct OsSubset {
    geom: Geometry,
    b: Array3<f32>,
    sens: Array3<f32>,
}

/// Build the ordered subsets for a sinogram: each carries its sub-geometry, the
/// gathered sinogram slice, and the precomputed (geometry-only) sensitivity
/// `Aโ‚›แต€(1)`. Single owner of subset construction for OSEM and the OS-penalized
/// methods. `block_params` supplies `num_block`/`ind_block` to [`ordered_subsets`].
fn build_subsets(
    b: &Tomo<f32>,
    geom: &Geometry,
    n: usize,
    block_params: &ReconParams,
    bp: &dyn FilteredBackproject,
) -> Result<Vec<OsSubset>> {
    let nz = b.n_rows();
    let ncols = b.n_cols();
    let nang = b.n_angles();
    let mut subsets = Vec::new();
    for idx in ordered_subsets(nang, block_params) {
        let len = idx.len();
        let mut sub_geom = geom.clone();
        sub_geom.angles = Angles(idx.iter().map(|&p| geom.angles.0[p]).collect());
        // `select` returns a non-standard-layout owned array; the recon backends
        // consume the subset sinogram via `as_slice()` (CPU back-projection errors
        // on a non-contiguous input), so make it C-contiguous once here โ€” the
        // single owner of subset construction, so every consumer sees contiguous.
        let sub_b = b
            .array
            .select(Axis(1), &idx)
            .as_standard_layout()
            .into_owned();
        let ones = Tomo::new(Array3::from_elem((nz, len, ncols), 1.0), Layout::Sinogram);
        let mut sens = Volume::new(Array3::zeros((nz, n, n)));
        bp.backproject(&ones, &sub_geom, &mut sens)?;
        subsets.push(OsSubset {
            geom: sub_geom,
            b: sub_b,
            sens: sens.array,
        });
    }
    Ok(subsets)
}

/// `corr โ† Aโ‚›แต€(b_s โŠ˜ Aโ‚› x)`, the EM correction backprojected over one subset's
/// rays. Shared by OSEM (multiplicative update) and the OS-penalized methods
/// (where it feeds the data term `E`).
fn subset_em_correction(
    vol: &Volume<f32>,
    sub: &OsSubset,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
    corr: &mut Volume<f32>,
) -> Result<()> {
    let nz = vol.dims().0;
    let len = sub.geom.angles.0.len();
    let ncols = sub.b.shape()[2];
    let mut ax = Tomo::new(Array3::zeros((nz, len, ncols)), Layout::Sinogram);
    proj.project(vol, &sub.geom, &mut ax)?; // Aโ‚› x
    let mut ratio = sub.b.clone();
    ndarray::Zip::from(&mut ratio)
        .and(&ax.array)
        .for_each(|r, &a| {
            *r = if a.abs() > 1e-6 { *r / a } else { 0.0 }; // b โŠ˜ Aโ‚› x
        });
    bp.backproject(&Tomo::new(ratio, Layout::Sinogram), &sub.geom, corr)
}

/// Ordered-Subset Expectation-Maximization.
///
/// MLEM restricted to ordered angle-subsets: each subset `s` applies one
/// multiplicative `x โ† x โˆ˜ Aโ‚›แต€(b โŠ˜ Aโ‚› x) โŠ˜ Aโ‚›แต€(1)` update over only its own
/// angles, so a single outer iteration performs `num_block` updates (faster
/// early convergence than MLEM). With `num_block โ‰ค 1` it is exactly [`mlem`].
/// The per-subset sensitivity `Aโ‚›แต€(1)` is geometry-only, so it is precomputed
/// once. Ports tomopy `libtomo/recon/osem.c`. `Aโ‚›` = forward projector over
/// subset `s`'s angles, `Aโ‚›แต€` = its back-projector.
fn osem(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let b = sino.as_layout(Layout::Sinogram);
    let nz = b.n_rows();
    let subsets = build_subsets(&b, geom, n, params, bp)?;

    let mut vol = init_volume(params, nz, n, 1.0)?; // positive init (or warm-start)
    let mut corr = Volume::new(Array3::zeros((nz, n, n)));
    for _ in 0..params.num_iter.max(1) {
        for sub in &subsets {
            subset_em_correction(&vol, sub, proj, bp, &mut corr)?;
            ndarray::Zip::from(&mut vol.array)
                .and(&corr.array)
                .and(&sub.sens)
                .for_each(|x, &c, &s| {
                    if s.abs() > 1e-6 {
                        *x = *x * c / s; // x โˆ˜ Aโ‚›แต€(ratio) โŠ˜ Aโ‚›แต€(1)
                    }
                });
        }
    }
    Ok(vol)
}

/// One penalized-ML, quadratic-prior pixel update over a slice (tomopy
/// `ospml_quad.c`). With `corr = Aโ‚›แต€(b โŠ˜ Aโ‚› x)` and `sens = Aโ‚›แต€(1)`, each pixel
/// solves the De Pierro quadratic `2Fยทxสนยฒ + Gยทxสน + E = 0` (positive root), where
///
/// - `E = โˆ’xยทcorr`            (data term),
/// - `F = ฮฃ_g 2ยทregยทw_gยทฮณ_g`,
/// - `G = sens โˆ’ ฮฃ_g 2ยทregยทw_gยทฮณ_gยท(x + x_g)`,
///
/// over the in-grid 8-neighbours `g`, where `w_g` is `1` (cardinal) / `1/โˆš2`
/// (diagonal) normalized by the present-weight sum โ€” the uniform form of
/// tomopy's separate interior/edge/corner weight tables (each already sums to
/// one). The edge factor `ฮณ_g` selects the prior:
///
/// - `delta = None` โ†’ `ฮณ_g = 1`: the plain quadratic prior (`ospml_quad`), where
///   `F` collapses to `2ยทreg` and `G` to `sens โˆ’ 2ยทregยท(x + โŸจneighboursโŸฉ)`.
/// - `delta = Some(ฮด)` โ†’ `ฮณ_g = 1/(1 + |x โˆ’ x_g|/ฮด)`: the edge-preserving hybrid
///   prior (`ospml_hybrid`), which down-weights smoothing across large jumps.
///
/// At `reg = 0` (`F = 0`) the quadratic degenerates to the linear root
/// `xยทcorr/sens`, i.e. exactly the MLEM/OSEM step (tomopy instead leaves
/// `reg = 0` pixels untouched; taking the correct limit makes `reg = 0` reduce
/// to [`osem`]). All reads use the pre-update slice `old`, matching tomopy's
/// read-then-write ordering.
fn penalized_ml_update(
    x: &mut ndarray::ArrayViewMut2<f32>,
    corr: &ndarray::ArrayView2<f32>,
    sens: &ndarray::ArrayView2<f32>,
    reg: f32,
    delta: Option<f32>,
) {
    const S: f32 = std::f32::consts::FRAC_1_SQRT_2;
    const NEIGHBORS: [(isize, isize, f32); 8] = [
        (-1, 0, 1.0),
        (1, 0, 1.0),
        (0, -1, 1.0),
        (0, 1, 1.0),
        (-1, -1, S),
        (-1, 1, S),
        (1, -1, S),
        (1, 1, S),
    ];
    let (h, w) = x.dim();
    let old = x.to_owned();
    for i in 0..h {
        for j in 0..w {
            let xij = old[[i, j]];
            let e = -xij * corr[[i, j]];
            let (mut f, mut g) = (0.0f32, sens[[i, j]]);
            if reg != 0.0 {
                // Normalize the neighbour weights by the present-weight sum.
                let mut wtot = 0.0f32;
                for (di, dj, raw) in NEIGHBORS {
                    let (ni, nj) = (i as isize + di, j as isize + dj);
                    if ni >= 0 && ni < h as isize && nj >= 0 && nj < w as isize {
                        wtot += raw;
                    }
                }
                for (di, dj, raw) in NEIGHBORS {
                    let (ni, nj) = (i as isize + di, j as isize + dj);
                    if ni >= 0 && ni < h as isize && nj >= 0 && nj < w as isize {
                        let xg = old[[ni as usize, nj as usize]];
                        let gamma = match delta {
                            Some(d) => 1.0 / (1.0 + ((xij - xg) / d).abs()),
                            None => 1.0,
                        };
                        let coef = 2.0 * reg * (raw / wtot) * gamma;
                        f += coef;
                        g -= coef * (xij + xg);
                    }
                }
            }
            x[[i, j]] = if f != 0.0 {
                (-g + (g * g - 8.0 * f * e).sqrt()) / (4.0 * f)
            } else if g.abs() > 1e-6 {
                -e / g // reg = 0 โŸน MLEM/OSEM step
            } else {
                xij
            };
        }
    }
}

/// Ordered-Subset Penalized Maximum-Likelihood (quadratic or hybrid prior).
///
/// OSEM with a smoothness penalty applied at each subset update via
/// [`penalized_ml_update`] (the De Pierro one-step-late form). Ports tomopy
/// `libtomo/recon/ospml_quad.c` (`delta = None`) and `ospml_hybrid.c`
/// (`delta = Some`); tomopy's `pml_quad`/`pml_hybrid` are these with `num_block
/// = 1` (`extern/recon.py`), so the caller passes `block_count`. The penalty
/// strength is `reg_par[0]` (0 โ‡’ reduces to [`osem`]); the hybrid edge threshold
/// is `reg_par[1]` (passed in as `delta`).
fn ospml(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
    block_count: usize,
    delta: Option<f32>,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let b = sino.as_layout(Layout::Sinogram);
    let nz = b.n_rows();
    let reg = params.reg_par.first().copied().unwrap_or(0.0);

    // Reuse the ordering rule but force the requested block count (pml_* โ‡’ 1).
    let block_params = ReconParams {
        num_block: block_count,
        ..params.clone()
    };
    let subsets = build_subsets(&b, geom, n, &block_params, bp)?;

    let mut vol = init_volume(params, nz, n, 1.0)?; // positive init (or warm-start)
    let mut corr = Volume::new(Array3::zeros((nz, n, n)));
    for _ in 0..params.num_iter.max(1) {
        for sub in &subsets {
            subset_em_correction(&vol, sub, proj, bp, &mut corr)?; // Aโ‚›แต€(b โŠ˜ Aโ‚› x)
            for z in 0..nz {
                penalized_ml_update(
                    &mut vol.array.index_axis_mut(Axis(0), z),
                    &corr.array.index_axis(Axis(0), z),
                    &sub.sens.index_axis(Axis(0), z),
                    reg,
                    delta,
                );
            }
        }
    }
    Ok(vol)
}

/// Least-squares gradient descent (tomopy `grad.c`) and its Tikhonov variant
/// (`tikh.c`).
///
/// Minimizes โ€–rยทR x โˆ’ bโ€–ยฒ (plus the Tikhonov term below) by gradient descent: the
/// data gradient is `g = 2rยทRแต€(rยทR x โˆ’ b)`, the step `x โ† x โˆ’ ฮป g`. The step `ฮป`
/// is either fixed (`reg_par[0] โ‰ฅ 0`) or Barzilaiโ€“Borwein adaptive
/// (`reg_par[0] < 0`, `ฮป = โŸจฮ”x, ฮ”gโŸฉ / โŸจฮ”g, ฮ”gโŸฉ`, first step `1e-3`). `x` iterates
/// in the r-scaled domain (tomopy scales the initial guess by `1/r`; from a zero
/// start that is a no-op) and is multiplied by `r` on return. `R` = the plain
/// line-integral forward projector, `Rแต€` = the back-projector, its exact
/// unweighted adjoint. Unlike the EM methods this imposes no positivity.
///
/// `tikhonov = Some((reg1, prior))` adds the Tikhonov gradient
/// `2ยทreg1ยท(x โˆ’ prior)` (penalizing โ€–x โˆ’ priorโ€–ยฒ, a ridge term pulling the
/// r-scaled iterate toward `prior`); `None` is plain `grad`. tomopy's `tikh`
/// likewise adds the term in the scaled domain and does *not* rescale `reg_data`,
/// so `prior` is compared to the scaled iterate as-is.
///
/// The operator normalization `r = 1/โˆš(ncolsยทnang/2)` is tomopy's heuristic,
/// tuned so `2rยฒยทฮปmax(Rแต€R) โ‰ˆ 2` (step-1 stability boundary) for *its* Siddon
/// projector. This crate's linear-interp adjoint pair has a larger operator norm,
/// so a unit fixed step diverges; use a smaller fixed step or the projector-
/// agnostic Barzilaiโ€“Borwein path (`reg_par[0] < 0`). The numeric result differs
/// from tomopy for the same reason FBP does โ€” the projector model, not a porting
/// error.
fn gradient_descent(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
    tikhonov: Option<(f32, Array3<f32>)>,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let b = sino.as_layout(Layout::Sinogram);
    let nz = b.n_rows();
    let nang = b.n_angles();
    let ncols = b.n_cols();

    let r = 1.0 / ((ncols * nang) as f32 / 2.0).sqrt();
    let fixed_step = params.reg_par.first().copied().unwrap_or(1.0);

    // r-scaled domain (physical = r ยท iterate); a warm-start seed enters as init / r.
    let mut vol = init_volume(params, nz, n, 0.0)?;
    vol.array.mapv_inplace(|v| v / r);
    let mut recon0 = vol.array.clone();
    let mut grad0 = Array3::<f32>::zeros((nz, n, n));
    let mut ax = Tomo::new(Array3::zeros((nz, nang, ncols)), Layout::Sinogram);
    let mut bpv = Volume::new(Array3::zeros((nz, n, n)));
    let mut lambda = vec![0.0f32; nz];

    for it in 0..params.num_iter.max(1) {
        proj.project(&vol, geom, &mut ax)?; // R x
        let mut prox1 = ax.array.clone();
        ndarray::Zip::from(&mut prox1)
            .and(&b.array)
            .for_each(|p, &d| *p = *p * r - d); // rยทR x โˆ’ b
        bp.backproject(&Tomo::new(prox1, Layout::Sinogram), geom, &mut bpv)?;
        let mut grad = bpv.array.mapv(|v| 2.0 * r * v); // 2rยทRแต€(โ€ฆ)

        // Tikhonov gradient 2ยทreg1ยท(x โˆ’ prior), added in the scaled domain.
        if let Some((reg1, ref prior)) = tikhonov {
            ndarray::Zip::from(&mut grad)
                .and(&vol.array)
                .and(prior)
                .for_each(|g, &x, &p0| *g += 2.0 * reg1 * (x - p0));
        }

        // Step size per slice (computed from the previous iterate before saving).
        for (z, lam) in lambda.iter_mut().enumerate() {
            *lam = if fixed_step >= 0.0 {
                fixed_step
            } else if it == 0 {
                1e-3
            } else {
                let (mut num, mut den) = (0.0f32, 0.0f32);
                ndarray::Zip::from(vol.array.index_axis(Axis(0), z))
                    .and(recon0.index_axis(Axis(0), z))
                    .and(grad.index_axis(Axis(0), z))
                    .and(grad0.index_axis(Axis(0), z))
                    .for_each(|&x, &x0, &g, &g0| {
                        let dg = g - g0;
                        num += (x - x0) * dg;
                        den += dg * dg;
                    });
                if den != 0.0 {
                    num / den
                } else {
                    1e-3
                }
            };
        }

        recon0 = vol.array.clone();
        grad0 = grad.clone();
        for (z, &l) in lambda.iter().enumerate() {
            ndarray::Zip::from(vol.array.index_axis_mut(Axis(0), z))
                .and(grad.index_axis(Axis(0), z))
                .for_each(|x, &g| *x -= l * g); // x โ† x โˆ’ ฮป g
        }
    }

    vol.array.mapv_inplace(|v| v * r); // back to the unscaled domain
    Ok(vol)
}

/// Least-squares gradient descent (tomopy `grad.c`): [`gradient_descent`] with no
/// Tikhonov term.
fn grad(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
) -> Result<Volume<f32>> {
    gradient_descent(sino, geom, params, proj, bp, None)
}

/// Tikhonov-regularized gradient descent (tomopy `tikh.c`): [`gradient_descent`]
/// with the term `2ยทreg_par[1]ยท(x โˆ’ reg_data)`. `reg_data` is the prior image
/// `[nz, n, n]` flattened (tomopy defaults it to zeros, a ridge term toward 0);
/// an empty `reg_data` is that zero prior. With `reg_par[1] = 0` (or absent) the
/// term vanishes and this is bit-identical to `grad`.
fn tikh(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let nz = sino.n_rows();
    let reg1 = params.reg_par.get(1).copied().unwrap_or(0.0);
    let prior = if params.reg_data.is_empty() {
        Array3::zeros((nz, n, n))
    } else {
        Array3::from_shape_vec((nz, n, n), params.reg_data.clone()).map_err(|_| {
            Error::ShapeMismatch {
                expected: format!("reg_data of {nz}ยท{n}ยท{n} = {} elements", nz * n * n),
                found: format!("{} elements", params.reg_data.len()),
            }
        })?
    };
    gradient_descent(sino, geom, params, proj, bp, Some((reg1, prior)))
}

/// Conjugate-Gradient Least Squares (CGLS).
///
/// A Krylov-subspace solver of the normal equations `Aแต€A x = Aแต€b`, i.e.
/// `min_x โ€–A x โˆ’ bโ€–ยฒ`, the same least-squares objective as [`grad`]/[`sirt`] but
/// with the optimal per-iteration step and conjugate search directions, so it
/// reaches a given residual in far fewer iterations than gradient descent. `A` =
/// forward projector, `Aแต€` = back-projector (an exact adjoint pair, which CGLS
/// requires). This is the standard algorithm (Bjรถrck, *Numerical Methods for
/// Least Squares Problems*); the recurrence below was cross-checked for exact
/// step-for-step agreement against ASTRA's `CglsAlgorithm`, but is an
/// independent implementation on tomoxide's own projector pair (ASTRA is
/// GPL-3.0; no ASTRA code is used here).
///
/// Every scalar (`alpha`, `beta`, `gamma`) is computed **per z-slice**: each
/// slice is an independent 2-D problem, so coupling their step sizes through a
/// whole-volume dot product would let one slice's conditioning drive another's.
/// The recurrence, per slice:
///
/// ```text
/// r = b โˆ’ A x0 ;  z = Aแต€ r ;  p = z ;  gamma = โŸจz,zโŸฉ       (init)
/// w = A p ;  alpha = gamma / โŸจw,wโŸฉ
/// x += alphaยทp ;  r โˆ’= alphaยทw ;  z = Aแต€ r
/// beta = โŸจz,zโŸฉ / gamma ;  gamma = โŸจz,zโŸฉ ;  p = z + betaยทp  (repeat)
/// ```
///
/// The warm-start `init` (`x0`) enters through the initial residual `b โˆ’ A x0`
/// (ASTRA starts from `x0 = 0`, i.e. `r = b`; this generalizes it). No
/// positivity clamp is applied โ€” plain CGLS, matching ASTRA's default (its
/// optional min/max clamp on the gradient is flagged "CHECKME" upstream and is
/// not part of the algorithm).
fn cgls(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let b = sino.as_layout(Layout::Sinogram);
    let nz = b.n_rows();
    let nang = b.n_angles();
    let ncols = b.n_cols();

    // Per-slice sum over a 2-D view (an [nz]-length accumulator lives one entry
    // per independent slice problem).
    fn slice_dot(a: &ndarray::ArrayView2<f32>, c: &ndarray::ArrayView2<f32>) -> f32 {
        let mut acc = 0.0f32;
        ndarray::Zip::from(a).and(c).for_each(|&x, &y| acc += x * y);
        acc
    }

    let mut vol = init_volume(params, nz, n, 0.0)?; // x = x0 (0, or warm-start)

    // r = b โˆ’ A x0.
    let mut ax = Tomo::new(Array3::zeros((nz, nang, ncols)), Layout::Sinogram);
    proj.project(&vol, geom, &mut ax)?;
    let mut r = Tomo::new(&b.array - &ax.array, Layout::Sinogram);

    // z = Aแต€ r ;  p = z ;  gamma = โŸจz,zโŸฉ per slice.
    let mut z = Volume::new(Array3::zeros((nz, n, n)));
    bp.backproject(&r, geom, &mut z)?;
    let mut p = z.clone();
    let mut gamma: Vec<f32> = (0..nz)
        .map(|s| {
            let zs = z.array.index_axis(Axis(0), s);
            slice_dot(&zs, &zs)
        })
        .collect();

    let mut w = Tomo::new(Array3::zeros((nz, nang, ncols)), Layout::Sinogram);
    for _ in 0..params.num_iter.max(1) {
        proj.project(&p, geom, &mut w)?; // w = A p
        for (s, ws) in w.array.outer_iter().enumerate() {
            let wdot = slice_dot(&ws, &ws);
            // A p = 0 โ‡’ p is in the null space (or gamma already 0): this slice
            // has converged, leave x/r/p untouched (alpha would be 0/0). The
            // `<= 0 || NaN` guard is exactly "not strictly positive".
            if wdot <= 0.0 || wdot.is_nan() {
                continue;
            }
            let alpha = gamma[s] / wdot;
            // x += alphaยทp ;  r โˆ’= alphaยทw.
            ndarray::Zip::from(vol.array.index_axis_mut(Axis(0), s))
                .and(p.array.index_axis(Axis(0), s))
                .for_each(|x, &pv| *x += alpha * pv);
            ndarray::Zip::from(r.array.index_axis_mut(Axis(0), s))
                .and(ws)
                .for_each(|rv, &wv| *rv -= alpha * wv);
        }

        bp.backproject(&r, geom, &mut z)?; // z = Aแต€ r
        for (s, zs) in z.array.outer_iter().enumerate() {
            let gamma_new = slice_dot(&zs, &zs);
            let beta = if gamma[s] > 0.0 {
                gamma_new / gamma[s]
            } else {
                0.0
            };
            gamma[s] = gamma_new;
            // p = z + betaยทp.
            ndarray::Zip::from(p.array.index_axis_mut(Axis(0), s))
                .and(zs)
                .for_each(|pv, &zv| *pv = zv + beta * *pv);
        }
    }
    Ok(vol)
}

/// Total-variation regularized least squares (tomopy `tv.c`), a Chambolleโ€“Pock
/// primalโ€“dual solver of `min_x ยฝโ€–rยทR x โˆ’ bโ€–ยฒ + ฮปยทTV(x)`.
///
/// Per iteration: ascend the two dual variables from the extrapolated primal
/// point `xฬ„` โ€” the isotropic TV dual `pแต€แต› โ† ฮ _{โ€–ยทโ€–โ‰คฮป}(pแต€แต› + cยทโˆ‡xฬ„)` (forward
/// differences, pointwise projection onto the ฮป-ball) and the data dual
/// `pแตˆ โ† (pแตˆ + c(rยทR xฬ„ โˆ’ b))/(1+c)` โ€” then a primal step
/// `xโ‚™ โ† x_old โˆ’ cยทrยทRแต€(pแตˆ) + cยทdiv(pแต€แต›)` and the ฮธ=1 over-relaxation
/// `xฬ„ โ† 2xโ‚™ โˆ’ x_old`. `ฮป = reg_par[0]` is the TV strength; `c = 0.35` is tomopy's
/// fixed primalโ€“dual step. As in `grad`, `R`/`Rแต€` are the unweighted
/// line-integral pair, `x` lives in the r-scaled domain
/// (`r = 1/โˆš(ncolsยทnang/2)`) and is rescaled by `r` on return, and the result is
/// the final extrapolated point `xฬ„` (matching tomopy, which returns `recon`).
/// No positivity constraint.
///
/// The projector-model caveat from `grad` applies: tomopy's `r` and the hardcoded
/// `c = 0.35` (the Chambolleโ€“Pock step, where convergence wants `cยฒยทโ€–Kโ€–ยฒ โ‰ค 1` for
/// `K = [rยทR; โˆ‡]`) are tuned for tomopy's Siddon projector. Unlike `grad`'s unit
/// fixed step, this iteration stays stable (finite) for this crate's linear-interp
/// adjoint pair across the tested `ฮป`/iteration range, but the numeric result
/// still differs from tomopy by the projector model.
fn tv(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    proj: &dyn ForwardProject,
    bp: &dyn FilteredBackproject,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let b = sino.as_layout(Layout::Sinogram);
    let nz = b.n_rows();
    let nang = b.n_angles();
    let ncols = b.n_cols();

    let r = 1.0 / ((ncols * nang) as f32 / 2.0).sqrt();
    let lambda = params.reg_par.first().copied().unwrap_or(1.0); // TV strength
    const C: f32 = 0.35; // tomopy's fixed primalโ€“dual step

    // The iterate lives in the r-scaled domain (physical = r ยท iterate; the final
    // `xbar ร— r` unscales), so a warm-start seed enters as init / r.
    let mut xbar = init_volume(params, nz, n, 0.0)?; // extrapolated primal (recon)
    xbar.array.mapv_inplace(|v| v / r);
    let mut x = xbar.array.clone(); // primal iterate (update)
    let mut p0x = Array3::<f32>::zeros((nz, n, n)); // TV dual, x-gradient
    let mut p0y = Array3::<f32>::zeros((nz, n, n)); // TV dual, y-gradient
    let mut pd = Tomo::new(Array3::zeros((nz, nang, ncols)), Layout::Sinogram); // data dual
    let mut ax = Tomo::new(Array3::zeros((nz, nang, ncols)), Layout::Sinogram);
    let mut bpv = Volume::new(Array3::zeros((nz, n, n)));

    for _ in 0..params.num_iter.max(1) {
        proj.project(&xbar, geom, &mut ax)?; // R xฬ„

        // Data dual: pแตˆ โ† (pแตˆ + cยทrยทR xฬ„ โˆ’ cยทb)/(1+c).
        ndarray::Zip::from(&mut pd.array)
            .and(&ax.array)
            .and(&b.array)
            .for_each(|q, &a, &d| *q = (*q + C * r * a - C * d) / (1.0 + C));
        bp.backproject(&pd, geom, &mut bpv)?; // Rแต€(pแตˆ)

        for z in 0..nz {
            // TV dual ascent on xฬ„, then project onto the ฮป-ball (interior stencil;
            // the last row/col of pแต€แต› stay 0, matching tomopy's loop bounds).
            let xb = xbar.array.index_axis(Axis(0), z);
            for iy in 0..n.saturating_sub(1) {
                for ix in 0..n.saturating_sub(1) {
                    let px = p0x[[z, iy, ix]] + C * (xb[[iy, ix + 1]] - xb[[iy, ix]]);
                    let py = p0y[[z, iy, ix]] + C * (xb[[iy + 1, ix]] - xb[[iy, ix]]);
                    let upd = ((px * px + py * py).sqrt() / lambda).max(1.0);
                    p0x[[z, iy, ix]] = px / upd;
                    p0y[[z, iy, ix]] = py / upd;
                }
            }
            // Primal step xโ‚™ = x_old โˆ’ cยทrยทRแต€(pแตˆ) + cยทdiv(pแต€แต›), then xฬ„ = 2xโ‚™ โˆ’ x_old.
            for iy in 0..n {
                for ix in 0..n {
                    let x_old = x[[z, iy, ix]];
                    let mut u = x_old - C * r * bpv.array[[z, iy, ix]];
                    u += if ix == 0 {
                        C * p0x[[z, iy, 0]]
                    } else {
                        C * (p0x[[z, iy, ix]] - p0x[[z, iy, ix - 1]])
                    };
                    u += if iy == 0 {
                        C * p0y[[z, 0, ix]]
                    } else {
                        C * (p0y[[z, iy, ix]] - p0y[[z, iy - 1, ix]])
                    };
                    x[[z, iy, ix]] = u;
                    xbar.array[[z, iy, ix]] = 2.0 * u - x_old;
                }
            }
        }
    }

    xbar.array.mapv_inplace(|v| v * r); // back to the unscaled domain
    Ok(xbar)
}

/// Squared row norms `โ€–aโ€–ยฒ` for every ray, matching the `rows` layout. Computed
/// once and reused across all ART/BART iterations (geometry-invariant).
fn ray_norms(rows: &[Vec<RayRow>]) -> Vec<Vec<f32>> {
    rows.iter()
        .map(|ang| {
            ang.iter()
                .map(|r| r.weights.iter().map(|w| w * w).sum())
                .collect()
        })
        .collect()
}

/// Algebraic Reconstruction Technique (tomopy `art.c`), a row-action Kaczmarz
/// solver of `R x = b`.
///
/// For each ray (angle `p`, detector `d`) in natural order, project onto the
/// ray's hyperplane `โŸจa, xโŸฉ = b`: `x โ† x + (b โˆ’ โŸจa, xโŸฉ)/โ€–aโ€–ยฒ ยท a`, where `a` is
/// the ray's sparse row of `R`. The reconstruction is updated immediately, so the
/// next ray sees it โ€” this sequential per-ray update is what distinguishes ART
/// from the simultaneous methods and is why it consumes the [`RayProject`]
/// single-ray rows. Rows (and their `โ€–aโ€–ยฒ`) are geometry-only, so they are built
/// once and reused across iterations. No positivity constraint.
fn art(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    rp: &dyn RayProject,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let b = sino.as_layout(Layout::Sinogram);
    let nz = b.n_rows();
    let nang = b.n_angles();
    let ncols = b.n_cols();

    let rows = rp.ray_rows(geom, n)?;
    let norms = ray_norms(&rows);
    let bslab = b
        .array
        .as_slice()
        .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;

    let npix = n * n;
    let mut recon = vec![0.0f32; nz * npix];
    for _ in 0..params.num_iter.max(1) {
        for ia in 0..nang {
            for d in 0..ncols {
                let row = &rows[ia][d];
                let norm2 = norms[ia][d];
                if norm2 == 0.0 {
                    continue;
                }
                for s in 0..nz {
                    let sl = &mut recon[s * npix..(s + 1) * npix];
                    let mut sim = 0.0f32;
                    for (k, &pix) in row.pixels.iter().enumerate() {
                        sim += sl[pix as usize] * row.weights[k];
                    }
                    let upd = (bslab[(s * nang + ia) * ncols + d] - sim) / norm2;
                    for (k, &pix) in row.pixels.iter().enumerate() {
                        sl[pix as usize] += upd * row.weights[k];
                    }
                }
            }
        }
    }
    let array = Array3::from_shape_vec((nz, n, n), recon)
        .map_err(|e| Error::InvalidParam(format!("art shape: {e}")))?;
    Ok(Volume::new(array))
}

/// Block Algebraic Reconstruction Technique (tomopy `bart.c`), ordered-subset
/// SART.
///
/// Like [`art`] but block-simultaneous: within an ordered subset every ray reads
/// the same (subset-start) reconstruction, the per-ray corrections accumulate
/// into `update[pix]` and the per-pixel total weights into `sum_dist[pix]`, and
/// the block is applied once at the subset end as
/// `x[pix] += update[pix] / sum_dist[pix]`. The subsets use the same `num_block`/
/// `ind_block` tiling as OSEM ([`ordered_subsets`]); `num_block = 1` is one
/// full-angle simultaneous update. No positivity constraint.
fn bart(
    sino: &Tomo<f32>,
    geom: &Geometry,
    params: &ReconParams,
    rp: &dyn RayProject,
) -> Result<Volume<f32>> {
    let n = grid_size(sino, params);
    let b = sino.as_layout(Layout::Sinogram);
    let nz = b.n_rows();
    let nang = b.n_angles();
    let ncols = b.n_cols();

    let rows = rp.ray_rows(geom, n)?;
    let norms = ray_norms(&rows);
    let subsets = ordered_subsets(nang, params);
    let bslab = b
        .array
        .as_slice()
        .ok_or_else(|| Error::InvalidParam("non-contiguous sinogram".into()))?;

    let npix = n * n;
    let mut recon = vec![0.0f32; nz * npix];
    let mut update = vec![0.0f32; npix];
    let mut sum_dist = vec![0.0f32; npix];
    for _ in 0..params.num_iter.max(1) {
        for s in 0..nz {
            let sl = &mut recon[s * npix..(s + 1) * npix];
            for subset in &subsets {
                update.iter_mut().for_each(|u| *u = 0.0);
                sum_dist.iter_mut().for_each(|u| *u = 0.0);
                for &p in subset {
                    for d in 0..ncols {
                        let row = &rows[p][d];
                        let mut sim = 0.0f32;
                        for (k, &pix) in row.pixels.iter().enumerate() {
                            let pix = pix as usize;
                            sim += sl[pix] * row.weights[k];
                            sum_dist[pix] += row.weights[k]; // accumulated for every ray
                        }
                        let norm2 = norms[p][d];
                        if norm2 != 0.0 {
                            let upd = (bslab[(s * nang + p) * ncols + d] - sim) / norm2;
                            for (k, &pix) in row.pixels.iter().enumerate() {
                                update[pix as usize] += upd * row.weights[k];
                            }
                        }
                    }
                }
                for pix in 0..npix {
                    if sum_dist[pix] != 0.0 {
                        sl[pix] += update[pix] / sum_dist[pix];
                    }
                }
            }
        }
    }
    let array = Array3::from_shape_vec((nz, n, n), recon)
        .map_err(|e| Error::InvalidParam(format!("bart shape: {e}")))?;
    Ok(Volume::new(array))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::{Backend, DeviceKind};
    use crate::data::Layout;
    use crate::dtype::Dtype;
    use crate::geometry::Angles;

    /// A backend that advertises no capabilities, to exercise dispatch.
    struct NullBackend;
    impl Backend for NullBackend {
        fn name(&self) -> &'static str {
            "null"
        }
        fn device(&self) -> DeviceKind {
            DeviceKind::Cpu
        }
        fn supports(&self, _dt: Dtype) -> bool {
            false
        }
    }

    fn tiny_sino() -> (Tomo<f32>, Geometry) {
        let s = Tomo::new(Array3::<f32>::zeros((2, 4, 8)), Layout::Sinogram); // [row,angle,col]
        let g = Geometry::parallel(Angles::uniform(4, 0.0, std::f32::consts::PI), 8, 2, 1.0);
        (s, g)
    }

    #[test]
    fn analytic_without_capabilities_reports_missing_capability() {
        // FBP is filter-then-back-project, and the dispatcher acquires the FBP
        // filter first (so fourierrec, which needs no back-projector, can branch
        // before it). A capability-less backend therefore surfaces the filter as
        // the first missing capability.
        let (s, g) = tiny_sino();
        let err = recon(
            &s,
            &g,
            Algorithm::Fbp,
            &ReconParams::default(),
            &NullBackend,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            Error::MissingCapability {
                capability: "FbpFilter",
                ..
            }
        ));
    }

    #[test]
    fn iterative_without_projector_reports_missing_capability() {
        let (s, g) = tiny_sino();
        let err = recon(
            &s,
            &g,
            Algorithm::Sirt,
            &ReconParams::default(),
            &NullBackend,
        )
        .unwrap_err();
        assert!(matches!(
            err,
            Error::MissingCapability {
                capability: "ForwardProject",
                ..
            }
        ));
    }
}