deconvolution 0.2.1

Rust image deconvolution and restoration library.
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
//! Microscopy PSF models for 3D deconvolution.
//!
//! Use parameter builders such as [`BornWolfParams`] and [`GibsonLanniParams`]
//! to generate normalized `(depth, height, width)` PSFs.

use std::f32::consts::PI;

use ndarray::{Array2, Array3};

use crate::{Error, Kernel2D, Kernel3D, Result};

#[derive(Debug, Clone, Copy, PartialEq)]
/// Parameters for a scalar Born-Wolf 3D microscopy PSF.
///
/// Dimensions use `(depth, height, width)` order. Optical distances are in
/// micrometers.
pub struct BornWolfParams {
    dims: (usize, usize, usize),
    wavelength_um: f32,
    numerical_aperture: f32,
    refractive_index: f32,
    axial_step_um: f32,
}

impl Default for BornWolfParams {
    fn default() -> Self {
        Self {
            dims: (33, 33, 33),
            wavelength_um: 0.55,
            numerical_aperture: 1.2,
            refractive_index: 1.33,
            axial_step_um: 0.2,
        }
    }
}

impl BornWolfParams {
    /// Create Born-Wolf parameters with default dimensions and optical values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set output dimensions in `(depth, height, width)` order.
    pub fn dims(mut self, value: (usize, usize, usize)) -> Self {
        self.dims = value;
        self
    }

    /// Set emission wavelength in micrometers.
    pub fn wavelength_um(mut self, value: f32) -> Self {
        self.wavelength_um = value;
        self
    }

    /// Set the objective numerical aperture.
    pub fn numerical_aperture(mut self, value: f32) -> Self {
        self.numerical_aperture = value;
        self
    }

    /// Set the sample refractive index.
    pub fn refractive_index(mut self, value: f32) -> Self {
        self.refractive_index = value;
        self
    }

    /// Set axial sample spacing in micrometers per z slice.
    pub fn axial_step_um(mut self, value: f32) -> Self {
        self.axial_step_um = value;
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
/// Parameters for a Gibson-Lanni 3D microscopy PSF.
///
/// Dimensions use `(depth, height, width)` order. Wavelength, coverslip
/// thickness, and axial step values are in micrometers.
pub struct GibsonLanniParams {
    dims: (usize, usize, usize),
    wavelength_um: f32,
    numerical_aperture: f32,
    immersion_index: f32,
    specimen_index: f32,
    coverslip_index: f32,
    design_coverslip_index: f32,
    coverslip_thickness_um: f32,
    design_coverslip_thickness_um: f32,
    axial_step_um: f32,
}

impl Default for GibsonLanniParams {
    fn default() -> Self {
        Self {
            dims: (33, 33, 33),
            wavelength_um: 0.55,
            numerical_aperture: 1.3,
            immersion_index: 1.515,
            specimen_index: 1.33,
            coverslip_index: 1.52,
            design_coverslip_index: 1.52,
            coverslip_thickness_um: 170.0,
            design_coverslip_thickness_um: 170.0,
            axial_step_um: 0.2,
        }
    }
}

impl GibsonLanniParams {
    /// Create Gibson-Lanni parameters with default dimensions and optical values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set output dimensions in `(depth, height, width)` order.
    pub fn dims(mut self, value: (usize, usize, usize)) -> Self {
        self.dims = value;
        self
    }

    /// Set emission wavelength in micrometers.
    pub fn wavelength_um(mut self, value: f32) -> Self {
        self.wavelength_um = value;
        self
    }

    /// Set the objective numerical aperture.
    pub fn numerical_aperture(mut self, value: f32) -> Self {
        self.numerical_aperture = value;
        self
    }

    /// Set immersion medium refractive index.
    pub fn immersion_index(mut self, value: f32) -> Self {
        self.immersion_index = value;
        self
    }

    /// Set specimen refractive index.
    pub fn specimen_index(mut self, value: f32) -> Self {
        self.specimen_index = value;
        self
    }

    /// Set actual coverslip refractive index.
    pub fn coverslip_index(mut self, value: f32) -> Self {
        self.coverslip_index = value;
        self
    }

    /// Set design coverslip refractive index.
    pub fn design_coverslip_index(mut self, value: f32) -> Self {
        self.design_coverslip_index = value;
        self
    }

    /// Set actual coverslip thickness in micrometers.
    pub fn coverslip_thickness_um(mut self, value: f32) -> Self {
        self.coverslip_thickness_um = value;
        self
    }

    /// Set design coverslip thickness in micrometers.
    pub fn design_coverslip_thickness_um(mut self, value: f32) -> Self {
        self.design_coverslip_thickness_um = value;
        self
    }

    /// Set axial sample spacing in micrometers per z slice.
    pub fn axial_step_um(mut self, value: f32) -> Self {
        self.axial_step_um = value;
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
/// Parameters for a Gibson-Lanni PSF with depth-varying refractive index.
///
/// The refractive index transitions from `refractive_index_start` to
/// `refractive_index_end` across the axial dimension.
pub struct VariableRiGibsonLanniParams {
    dims: (usize, usize, usize),
    wavelength_um: f32,
    numerical_aperture: f32,
    immersion_index: f32,
    refractive_index_start: f32,
    refractive_index_end: f32,
    profile_exponent: f32,
    coverslip_index: f32,
    design_coverslip_index: f32,
    coverslip_thickness_um: f32,
    design_coverslip_thickness_um: f32,
    axial_step_um: f32,
}

impl Default for VariableRiGibsonLanniParams {
    fn default() -> Self {
        Self {
            dims: (33, 33, 33),
            wavelength_um: 0.55,
            numerical_aperture: 1.3,
            immersion_index: 1.515,
            refractive_index_start: 1.33,
            refractive_index_end: 1.40,
            profile_exponent: 1.0,
            coverslip_index: 1.52,
            design_coverslip_index: 1.52,
            coverslip_thickness_um: 170.0,
            design_coverslip_thickness_um: 170.0,
            axial_step_um: 0.2,
        }
    }
}

impl VariableRiGibsonLanniParams {
    /// Create variable-RI Gibson-Lanni parameters with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set output dimensions in `(depth, height, width)` order.
    pub fn dims(mut self, value: (usize, usize, usize)) -> Self {
        self.dims = value;
        self
    }

    /// Set emission wavelength in micrometers.
    pub fn wavelength_um(mut self, value: f32) -> Self {
        self.wavelength_um = value;
        self
    }

    /// Set the objective numerical aperture.
    pub fn numerical_aperture(mut self, value: f32) -> Self {
        self.numerical_aperture = value;
        self
    }

    /// Set immersion medium refractive index.
    pub fn immersion_index(mut self, value: f32) -> Self {
        self.immersion_index = value;
        self
    }

    /// Set the refractive index at the first z slice.
    pub fn refractive_index_start(mut self, value: f32) -> Self {
        self.refractive_index_start = value;
        self
    }

    /// Set the refractive index at the last z slice.
    pub fn refractive_index_end(mut self, value: f32) -> Self {
        self.refractive_index_end = value;
        self
    }

    /// Set the exponent used to interpolate the axial refractive-index profile.
    pub fn profile_exponent(mut self, value: f32) -> Self {
        self.profile_exponent = value;
        self
    }

    /// Set actual coverslip refractive index.
    pub fn coverslip_index(mut self, value: f32) -> Self {
        self.coverslip_index = value;
        self
    }

    /// Set design coverslip refractive index.
    pub fn design_coverslip_index(mut self, value: f32) -> Self {
        self.design_coverslip_index = value;
        self
    }

    /// Set actual coverslip thickness in micrometers.
    pub fn coverslip_thickness_um(mut self, value: f32) -> Self {
        self.coverslip_thickness_um = value;
        self
    }

    /// Set design coverslip thickness in micrometers.
    pub fn design_coverslip_thickness_um(mut self, value: f32) -> Self {
        self.design_coverslip_thickness_um = value;
        self
    }

    /// Set axial sample spacing in micrometers per z slice.
    pub fn axial_step_um(mut self, value: f32) -> Self {
        self.axial_step_um = value;
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
/// Parameters for a vectorial Richards-Wolf 3D microscopy PSF.
///
/// `polarization_weight` blends the vectorial polarization terms and should be
/// in `[0, 1]`.
pub struct RichardsWolfParams {
    dims: (usize, usize, usize),
    wavelength_um: f32,
    numerical_aperture: f32,
    immersion_index: f32,
    specimen_index: f32,
    polarization_weight: f32,
    axial_step_um: f32,
}

impl Default for RichardsWolfParams {
    fn default() -> Self {
        Self {
            dims: (33, 33, 33),
            wavelength_um: 0.55,
            numerical_aperture: 1.3,
            immersion_index: 1.515,
            specimen_index: 1.33,
            polarization_weight: 0.5,
            axial_step_um: 0.2,
        }
    }
}

impl RichardsWolfParams {
    /// Create Richards-Wolf parameters with default dimensions and optical values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set output dimensions in `(depth, height, width)` order.
    pub fn dims(mut self, value: (usize, usize, usize)) -> Self {
        self.dims = value;
        self
    }

    /// Set emission wavelength in micrometers.
    pub fn wavelength_um(mut self, value: f32) -> Self {
        self.wavelength_um = value;
        self
    }

    /// Set the objective numerical aperture.
    pub fn numerical_aperture(mut self, value: f32) -> Self {
        self.numerical_aperture = value;
        self
    }

    /// Set immersion medium refractive index.
    pub fn immersion_index(mut self, value: f32) -> Self {
        self.immersion_index = value;
        self
    }

    /// Set specimen refractive index.
    pub fn specimen_index(mut self, value: f32) -> Self {
        self.specimen_index = value;
        self
    }

    /// Set vectorial polarization blend weight in `[0, 1]`.
    pub fn polarization_weight(mut self, value: f32) -> Self {
        self.polarization_weight = value;
        self
    }

    /// Set axial sample spacing in micrometers per z slice.
    pub fn axial_step_um(mut self, value: f32) -> Self {
        self.axial_step_um = value;
        self
    }
}

/// Generate a normalized scalar Born-Wolf 3D PSF.
///
/// The output dimensions are `params.dims` in `(depth, height, width)` order.
///
/// # Errors
///
/// Returns an error when dimensions are empty, optical parameters are not
/// positive and finite, numerical aperture is not below refractive index, or
/// generated kernel values are invalid.
pub fn born_wolf(params: &BornWolfParams) -> Result<Kernel3D> {
    validate_born_wolf_params(params)?;
    let (depth, height, width) = params.dims;
    let (lateral_scale, axial_scale, lateral_step) = diffraction_scales(
        params.wavelength_um,
        params.numerical_aperture,
        params.refractive_index,
    )?;
    let radial = radial_map((height, width), lateral_step)?;
    let center_z = center_coordinate(depth)?;

    let mut psf = Array3::zeros((depth, height, width));
    for z in 0..depth {
        let z_um = (z as f32 - center_z) * params.axial_step_um;
        let axial = gaussian(z_um, 0.0, axial_scale)?;
        for y in 0..height {
            for x in 0..width {
                let r_um = radial[[y, x]];
                let lateral = airy_like(
                    r_um,
                    lateral_scale,
                    params.wavelength_um,
                    params.numerical_aperture,
                )?;
                let value = lateral * axial;
                if !value.is_finite() || value < 0.0 {
                    return Err(Error::NonFiniteInput);
                }
                psf[[z, y, x]] = value;
            }
        }
    }

    to_normalized_kernel(psf)
}

/// Generate a normalized Gibson-Lanni 3D PSF.
///
/// Coverslip and refractive-index mismatches modulate the axial spread and
/// apodization. Dimensions use `(depth, height, width)` order.
///
/// # Errors
///
/// Returns an error when dimensions are empty, optical parameters are not
/// positive and finite, numerical aperture exceeds the refractive-index limit,
/// or generated kernel values are invalid.
pub fn gibson_lanni(params: &GibsonLanniParams) -> Result<Kernel3D> {
    validate_gibson_lanni_params(params)?;
    let (depth, height, width) = params.dims;
    let (lateral_scale, axial_scale_base, lateral_step) = diffraction_scales(
        params.wavelength_um,
        params.numerical_aperture,
        params.specimen_index,
    )?;
    let radial = radial_map((height, width), lateral_step)?;
    let center_z = center_coordinate(depth)?;
    let thickness_ratio = normalized_thickness_mismatch(
        params.coverslip_thickness_um,
        params.design_coverslip_thickness_um,
    )?;
    let index_mismatch = (params.immersion_index - params.specimen_index).abs()
        + (params.coverslip_index - params.design_coverslip_index).abs();

    let mut psf = Array3::zeros((depth, height, width));
    for z in 0..depth {
        let z_um = (z as f32 - center_z) * params.axial_step_um;
        for y in 0..height {
            for x in 0..width {
                let r_um = radial[[y, x]];
                let normalized_r = r_um / lateral_scale.max(1e-6);
                let aberration = index_mismatch * normalized_r * normalized_r
                    + thickness_ratio * normalized_r.abs();
                let axial_scale = axial_scale_base * (1.0 + 0.45 * aberration.abs());
                let axial_shift = axial_scale_base
                    * 0.18
                    * (params.immersion_index - params.specimen_index)
                    * normalized_r;
                let lateral = airy_like(
                    r_um,
                    lateral_scale,
                    params.wavelength_um,
                    params.numerical_aperture,
                )?;
                let axial = gaussian(z_um, axial_shift, axial_scale)?;
                let apodization = (-0.5 * aberration * aberration).exp();
                let value = lateral * axial * apodization;
                if !value.is_finite() || value < 0.0 {
                    return Err(Error::NonFiniteInput);
                }
                psf[[z, y, x]] = value;
            }
        }
    }

    to_normalized_kernel(psf)
}

/// Generate a normalized Gibson-Lanni 3D PSF with depth-varying refractive index.
///
/// The local refractive index is interpolated across z using
/// `profile_exponent`. Dimensions use `(depth, height, width)` order.
///
/// # Errors
///
/// Returns an error when dimensions are empty, optical parameters are not
/// positive and finite, numerical aperture exceeds the refractive-index limit,
/// or generated kernel values are invalid.
pub fn variable_ri_gibson_lanni(params: &VariableRiGibsonLanniParams) -> Result<Kernel3D> {
    validate_variable_ri_gibson_lanni_params(params)?;
    let (depth, height, width) = params.dims;
    let (lateral_scale, _, lateral_step) = diffraction_scales(
        params.wavelength_um,
        params.numerical_aperture,
        params
            .refractive_index_start
            .max(params.refractive_index_end),
    )?;
    let radial = radial_map((height, width), lateral_step)?;
    let center_z = center_coordinate(depth)?;
    let thickness_ratio = normalized_thickness_mismatch(
        params.coverslip_thickness_um,
        params.design_coverslip_thickness_um,
    )?;
    let depth_den = (depth.saturating_sub(1)).max(1) as f32;

    let mut psf = Array3::zeros((depth, height, width));
    for z in 0..depth {
        let z_um = (z as f32 - center_z) * params.axial_step_um;
        let t = (z as f32 / depth_den).clamp(0.0, 1.0);
        let local_index = params.refractive_index_start
            + (params.refractive_index_end - params.refractive_index_start)
                * t.powf(params.profile_exponent);
        let (_, local_axial_scale, _) =
            diffraction_scales(params.wavelength_um, params.numerical_aperture, local_index)?;
        let index_mismatch = (params.immersion_index - local_index).abs()
            + (params.coverslip_index - params.design_coverslip_index).abs();

        for y in 0..height {
            for x in 0..width {
                let r_um = radial[[y, x]];
                let normalized_r = r_um / lateral_scale.max(1e-6);
                let aberration = index_mismatch * normalized_r * normalized_r
                    + thickness_ratio * normalized_r.abs();
                let axial_scale = local_axial_scale * (1.0 + 0.4 * aberration.abs());
                let axial_shift = local_axial_scale * 0.12 * (params.immersion_index - local_index);
                let lateral = airy_like(
                    r_um,
                    lateral_scale,
                    params.wavelength_um,
                    params.numerical_aperture,
                )?;
                let axial = gaussian(z_um, axial_shift, axial_scale)?;
                let apodization = (-0.5 * aberration * aberration).exp();
                let value = lateral * axial * apodization;
                if !value.is_finite() || value < 0.0 {
                    return Err(Error::NonFiniteInput);
                }
                psf[[z, y, x]] = value;
            }
        }
    }

    to_normalized_kernel(psf)
}

/// Generate a normalized vectorial Richards-Wolf 3D PSF.
///
/// `polarization_weight` blends scalar-like and vectorial polarization terms.
/// Dimensions use `(depth, height, width)` order.
///
/// # Errors
///
/// Returns an error when dimensions are empty, optical parameters are not
/// positive and finite, `polarization_weight` is outside `[0, 1]`, numerical
/// aperture exceeds the refractive-index limit, or generated values are invalid.
pub fn richards_wolf(params: &RichardsWolfParams) -> Result<Kernel3D> {
    validate_richards_wolf_params(params)?;
    let (depth, height, width) = params.dims;
    let (lateral_scale, axial_scale, lateral_step) = diffraction_scales(
        params.wavelength_um,
        params.numerical_aperture,
        params.specimen_index,
    )?;
    let radial = radial_map((height, width), lateral_step)?;
    let center_z = center_coordinate(depth)?;
    let alpha = (params.numerical_aperture / params.immersion_index).clamp(0.0, 0.999_999);

    let mut psf = Array3::zeros((depth, height, width));
    for z in 0..depth {
        let z_um = (z as f32 - center_z) * params.axial_step_um;
        let axial = gaussian(z_um, 0.0, axial_scale)?;
        for y in 0..height {
            for x in 0..width {
                let r_um = radial[[y, x]];
                let normalized_r = (r_um / (3.0 * lateral_scale).max(1e-6)).clamp(0.0, 1.0);
                let cos_theta = (1.0 - normalized_r * normalized_r).sqrt();
                let vector_term =
                    ((1.0 - params.polarization_weight) * 0.5 * (1.0 + cos_theta * cos_theta)
                        + params.polarization_weight * cos_theta)
                        .max(0.0);
                let apodization = (1.0 - alpha * normalized_r * normalized_r).max(0.0).sqrt();
                let lateral = airy_like(
                    r_um,
                    lateral_scale,
                    params.wavelength_um,
                    params.numerical_aperture,
                )?;
                let value = lateral * axial * vector_term * apodization;
                if !value.is_finite() || value < 0.0 {
                    return Err(Error::NonFiniteInput);
                }
                psf[[z, y, x]] = value;
            }
        }
    }

    to_normalized_kernel(psf)
}

/// Generate a normalized 2D Lorentzian PSF.
///
/// `dims` is `(height, width)` and `gamma` is the width parameter in pixels.
///
/// # Errors
///
/// Returns an error when dimensions are empty, `gamma` is not positive and
/// finite, or generated values cannot be normalized.
pub fn lorentz2d(dims: (usize, usize), gamma: f32) -> Result<Kernel2D> {
    validate_dims_2d(dims)?;
    validate_positive(gamma)?;

    let (height, width) = dims;
    let cy = center_coordinate(height)?;
    let cx = center_coordinate(width)?;
    let gamma2 = gamma * gamma;
    if !gamma2.is_finite() || gamma2 <= 0.0 {
        return Err(Error::InvalidParameter);
    }

    let mut psf = Array2::zeros((height, width));
    for y in 0..height {
        let dy = y as f32 - cy;
        for x in 0..width {
            let dx = x as f32 - cx;
            let radius2 = dx * dx + dy * dy;
            let value = 1.0 / (1.0 + radius2 / gamma2);
            if !value.is_finite() || value < 0.0 {
                return Err(Error::NonFiniteInput);
            }
            psf[[y, x]] = value;
        }
    }

    to_normalized_kernel2d(psf)
}

/// Generate a normalized rotated astigmatic Gaussian PSF.
///
/// `sigma_major` and `sigma_minor` are measured in pixels. `angle_deg` rotates
/// the major axis in degrees.
///
/// # Errors
///
/// Returns an error when dimensions are empty, sigmas are not positive and
/// finite, `angle_deg` is non-finite, or generated values cannot be normalized.
pub fn astigmatic(
    dims: (usize, usize),
    sigma_major: f32,
    sigma_minor: f32,
    angle_deg: f32,
) -> Result<Kernel2D> {
    validate_dims_2d(dims)?;
    validate_positive(sigma_major)?;
    validate_positive(sigma_minor)?;
    if !angle_deg.is_finite() {
        return Err(Error::InvalidParameter);
    }

    let (height, width) = dims;
    let cy = center_coordinate(height)?;
    let cx = center_coordinate(width)?;
    let theta = angle_deg.to_radians();
    let cos_t = theta.cos();
    let sin_t = theta.sin();
    let major2 = sigma_major * sigma_major;
    let minor2 = sigma_minor * sigma_minor;
    if !major2.is_finite() || !minor2.is_finite() || major2 <= 0.0 || minor2 <= 0.0 {
        return Err(Error::InvalidParameter);
    }

    let mut psf = Array2::zeros((height, width));
    for y in 0..height {
        let dy = y as f32 - cy;
        for x in 0..width {
            let dx = x as f32 - cx;
            let xr = cos_t * dx + sin_t * dy;
            let yr = -sin_t * dx + cos_t * dy;
            let exponent = -0.5 * (xr * xr / major2 + yr * yr / minor2);
            let value = exponent.exp();
            if !value.is_finite() || value < 0.0 {
                return Err(Error::NonFiniteInput);
            }
            psf[[y, x]] = value;
        }
    }

    to_normalized_kernel2d(psf)
}

/// Generate a normalized double-helix 2D PSF.
///
/// `sigma` and `lobe_separation` are measured in pixels. `angle_deg` rotates
/// the lobe axis in degrees.
///
/// # Errors
///
/// Returns an error when dimensions are empty, `sigma` or `lobe_separation` is
/// not positive and finite, `angle_deg` is non-finite, or generated values
/// cannot be normalized.
pub fn double_helix(
    dims: (usize, usize),
    sigma: f32,
    lobe_separation: f32,
    angle_deg: f32,
) -> Result<Kernel2D> {
    validate_dims_2d(dims)?;
    validate_positive(sigma)?;
    validate_positive(lobe_separation)?;
    if !angle_deg.is_finite() {
        return Err(Error::InvalidParameter);
    }

    let (height, width) = dims;
    let cy = center_coordinate(height)?;
    let cx = center_coordinate(width)?;
    let theta = angle_deg.to_radians();
    let half_sep = 0.5 * lobe_separation;
    let lobe_dx = half_sep * theta.cos();
    let lobe_dy = half_sep * theta.sin();
    let sigma2 = sigma * sigma;
    if !sigma2.is_finite() || sigma2 <= 0.0 {
        return Err(Error::InvalidParameter);
    }

    let mut psf = Array2::zeros((height, width));
    for y in 0..height {
        let dy = y as f32 - cy;
        for x in 0..width {
            let dx = x as f32 - cx;
            let r1x = dx - lobe_dx;
            let r1y = dy - lobe_dy;
            let r2x = dx + lobe_dx;
            let r2y = dy + lobe_dy;

            let v1 = (-0.5 * (r1x * r1x + r1y * r1y) / sigma2).exp();
            let v2 = (-0.5 * (r2x * r2x + r2y * r2y) / sigma2).exp();
            let value = v1 + v2;
            if !value.is_finite() || value < 0.0 {
                return Err(Error::NonFiniteInput);
            }
            psf[[y, x]] = value;
        }
    }

    to_normalized_kernel2d(psf)
}

fn validate_born_wolf_params(params: &BornWolfParams) -> Result<()> {
    validate_dims_3d(params.dims)?;
    validate_positive(params.wavelength_um)?;
    validate_positive(params.numerical_aperture)?;
    validate_positive(params.refractive_index)?;
    validate_positive(params.axial_step_um)?;
    if params.numerical_aperture >= params.refractive_index {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn validate_gibson_lanni_params(params: &GibsonLanniParams) -> Result<()> {
    validate_dims_3d(params.dims)?;
    validate_positive(params.wavelength_um)?;
    validate_positive(params.numerical_aperture)?;
    validate_positive(params.immersion_index)?;
    validate_positive(params.specimen_index)?;
    validate_positive(params.coverslip_index)?;
    validate_positive(params.design_coverslip_index)?;
    validate_positive(params.coverslip_thickness_um)?;
    validate_positive(params.design_coverslip_thickness_um)?;
    validate_positive(params.axial_step_um)?;
    let na_limit = params
        .immersion_index
        .min(params.specimen_index)
        .min(params.coverslip_index)
        .min(params.design_coverslip_index);
    if params.numerical_aperture >= na_limit {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn validate_variable_ri_gibson_lanni_params(params: &VariableRiGibsonLanniParams) -> Result<()> {
    validate_dims_3d(params.dims)?;
    validate_positive(params.wavelength_um)?;
    validate_positive(params.numerical_aperture)?;
    validate_positive(params.immersion_index)?;
    validate_positive(params.refractive_index_start)?;
    validate_positive(params.refractive_index_end)?;
    validate_positive(params.profile_exponent)?;
    validate_positive(params.coverslip_index)?;
    validate_positive(params.design_coverslip_index)?;
    validate_positive(params.coverslip_thickness_um)?;
    validate_positive(params.design_coverslip_thickness_um)?;
    validate_positive(params.axial_step_um)?;
    let min_sample_index = params
        .refractive_index_start
        .min(params.refractive_index_end);
    let na_limit = params
        .immersion_index
        .min(min_sample_index)
        .min(params.coverslip_index)
        .min(params.design_coverslip_index);
    if params.numerical_aperture >= na_limit {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn validate_richards_wolf_params(params: &RichardsWolfParams) -> Result<()> {
    validate_dims_3d(params.dims)?;
    validate_positive(params.wavelength_um)?;
    validate_positive(params.numerical_aperture)?;
    validate_positive(params.immersion_index)?;
    validate_positive(params.specimen_index)?;
    validate_positive(params.axial_step_um)?;
    if !params.polarization_weight.is_finite()
        || params.polarization_weight < 0.0
        || params.polarization_weight > 1.0
    {
        return Err(Error::InvalidParameter);
    }
    let na_limit = params.immersion_index.min(params.specimen_index);
    if params.numerical_aperture >= na_limit {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn validate_dims_3d(dims: (usize, usize, usize)) -> Result<()> {
    if dims.0 == 0 || dims.1 == 0 || dims.2 == 0 {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn validate_dims_2d(dims: (usize, usize)) -> Result<()> {
    if dims.0 == 0 || dims.1 == 0 {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn validate_positive(value: f32) -> Result<()> {
    if !value.is_finite() || value <= 0.0 {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}

fn normalized_thickness_mismatch(actual: f32, design: f32) -> Result<f32> {
    validate_positive(actual)?;
    validate_positive(design)?;
    Ok((actual - design).abs() / design.max(1.0))
}

fn center_coordinate(length: usize) -> Result<f32> {
    if length == 0 {
        return Err(Error::InvalidParameter);
    }
    Ok((length as f32 - 1.0) * 0.5)
}

fn radial_map(dims: (usize, usize), lateral_step_um: f32) -> Result<Array2<f32>> {
    validate_positive(lateral_step_um)?;
    let (height, width) = dims;
    if height == 0 || width == 0 {
        return Err(Error::InvalidParameter);
    }

    let cy = center_coordinate(height)?;
    let cx = center_coordinate(width)?;
    let mut radial = Array2::zeros((height, width));
    for y in 0..height {
        let dy = (y as f32 - cy) * lateral_step_um;
        for x in 0..width {
            let dx = (x as f32 - cx) * lateral_step_um;
            let value = (dx * dx + dy * dy).sqrt();
            if !value.is_finite() {
                return Err(Error::NonFiniteInput);
            }
            radial[[y, x]] = value;
        }
    }
    Ok(radial)
}

fn diffraction_scales(
    wavelength_um: f32,
    numerical_aperture: f32,
    refractive_index: f32,
) -> Result<(f32, f32, f32)> {
    validate_positive(wavelength_um)?;
    validate_positive(numerical_aperture)?;
    validate_positive(refractive_index)?;
    if numerical_aperture >= refractive_index {
        return Err(Error::InvalidParameter);
    }

    let lateral_scale = 0.61 * wavelength_um / numerical_aperture.max(1e-6);
    let axial_scale = 2.0 * refractive_index * wavelength_um
        / (numerical_aperture * numerical_aperture).max(1e-6);
    let lateral_step = 0.5 * lateral_scale;
    if !lateral_scale.is_finite()
        || !axial_scale.is_finite()
        || !lateral_step.is_finite()
        || lateral_scale <= 0.0
        || axial_scale <= 0.0
        || lateral_step <= 0.0
    {
        return Err(Error::NonFiniteInput);
    }
    Ok((lateral_scale, axial_scale, lateral_step))
}

fn gaussian(z_um: f32, center_um: f32, sigma_um: f32) -> Result<f32> {
    validate_positive(sigma_um)?;
    if !z_um.is_finite() || !center_um.is_finite() {
        return Err(Error::InvalidParameter);
    }
    let normalized = (z_um - center_um) / sigma_um;
    let value = (-0.5 * normalized * normalized).exp();
    if !value.is_finite() || value < 0.0 {
        return Err(Error::NonFiniteInput);
    }
    Ok(value)
}

fn airy_like(
    radius_um: f32,
    lateral_scale_um: f32,
    wavelength_um: f32,
    numerical_aperture: f32,
) -> Result<f32> {
    validate_positive(lateral_scale_um)?;
    validate_positive(wavelength_um)?;
    validate_positive(numerical_aperture)?;
    if !radius_um.is_finite() || radius_um < 0.0 {
        return Err(Error::InvalidParameter);
    }

    let rho = 2.0 * PI * numerical_aperture * radius_um / wavelength_um.max(1e-6);
    let value = if rho.abs() <= 1e-4 {
        1.0
    } else {
        let j1 = bessel_j1(rho);
        let normalized = 2.0 * j1 / rho;
        normalized * normalized
    };
    if !value.is_finite() || value < 0.0 {
        return Err(Error::NonFiniteInput);
    }
    Ok(value)
}

fn to_normalized_kernel2d(psf: Array2<f32>) -> Result<Kernel2D> {
    if psf.iter().any(|value| !value.is_finite() || *value < 0.0) {
        return Err(Error::NonFiniteInput);
    }
    let sum = psf.sum();
    if !sum.is_finite() || sum <= f32::EPSILON {
        return Err(Error::InvalidPsf);
    }

    let mut kernel = Kernel2D::new(psf)?;
    kernel.normalize()?;
    Ok(kernel)
}

fn to_normalized_kernel(psf: Array3<f32>) -> Result<Kernel3D> {
    if psf.iter().any(|value| !value.is_finite() || *value < 0.0) {
        return Err(Error::NonFiniteInput);
    }
    let sum = psf.sum();
    if !sum.is_finite() || sum <= f32::EPSILON {
        return Err(Error::InvalidPsf);
    }

    let mut kernel = Kernel3D::new(psf)?;
    kernel.normalize()?;
    Ok(kernel)
}

fn bessel_j1(x: f32) -> f32 {
    let ax = x.abs();
    if ax < 8.0 {
        let y = x * x;
        let numerator = x
            * (72_362_610_000.0
                + y * (-7_895_059_000.0
                    + y * (242_396_860.0
                        + y * (-2_972_611.5 + y * (15_704.483 + y * -30.160366)))));
        let denominator = 144_725_230_000.0
            + y * (2_300_535_300.0 + y * (18_583_304.0 + y * (99_447.44 + y * (376.99915 + y))));
        numerator / denominator
    } else {
        let z = 8.0 / ax;
        let y = z * z;
        let xx = ax - 2.356_194_5;
        let ans1 = 1.0
            + y * (0.001_831_05
                + y * (-0.000_035_163_966 + y * (0.000_002_457_520_2 + y * -0.000_000_240_337)));
        let ans2 = 0.046_875
            + y * (-0.000_200_269_09
                + y * (0.000_008_449_199 + y * (-0.000_000_882_289_9 + y * 0.000_000_105_787_41)));
        let value = (0.636_619_75 / ax).sqrt() * (xx.cos() * ans1 - z * xx.sin() * ans2);
        if x < 0.0 { -value } else { value }
    }
}