sylva-rs 2.0.0

Terrestrial and airborne laser scanning processing for forest ecology and remote sensing research.
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
// Sylva: LiDAR processing for forest ecology and remote sensing research.
// Copyright (C) 2026 Tim Devereux, The University of Queensland.
// Follows AMAPVox (UMR AMAP); see THIRD_PARTY_NOTICES.md.
// Free software under the GNU General Public License v3.0 or later;
// see the LICENSE file. There is no warranty, to the extent permitted by law.
//! Per-voxel estimators: attenuation, projection functions, area densities.

use std::f64::consts::{FRAC_PI_2, PI};

use super::{Attenuation, RayVoxels, F, I};
use crate::error::{Error, Result};

const EPS: f64 = 1e-10;

/// Analytic leaf angle distribution (de Wit 1965 types and parametric ones).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Lad {
    /// Leaf normals spread evenly over the sphere (density `sin θ`); `G = 0.5` at every zenith.
    Spherical,
    /// Every inclination equally likely.
    Uniform,
    /// Mostly horizontal leaves (de Wit 1965).
    Planophile,
    /// Mostly vertical leaves.
    Erectophile,
    /// Mostly oblique leaves, around 45 degrees.
    Plagiophile,
    /// Horizontal and vertical leaves, few oblique.
    Extremophile,
    /// Campbell's (1990) ellipsoidal distribution with axis ratio `chi`.
    Ellipsoidal(f64),
    /// Two-parameter beta distribution of Goel & Strebel (1984) on `t = 2 theta / pi`:
    /// `f(t) ~ (1 - t)^(mu - 1) t^(nu - 1)`, so `mu > nu` leans towards horizontal
    /// leaves. Their fits: planophile (2.770, 1.172), erectophile (1.172, 2.770),
    /// plagiophile (3.326, 3.326), extremophile (0.433, 0.433), uniform (1, 1),
    /// spherical (1.101, 1.930).
    TwoParamBeta(f64, f64),
}

impl Lad {
    /// From a name and up to two parameters (`--lad` / `--lad_params`).
    pub fn parse(name: &str, p: &[f64]) -> Result<Self> {
        let need = |n: usize| if p.len() < n { Err(Error::invalid(format!("LAD {name:?} needs {n} parameter(s)"))) } else { Ok(()) };
        Ok(match name {
            "spherical" => Lad::Spherical,
            "uniform" => Lad::Uniform,
            "planophile" => Lad::Planophile,
            "erectophile" => Lad::Erectophile,
            "plagiophile" => Lad::Plagiophile,
            "extremophile" => Lad::Extremophile,
            "ellipsoidal" => {
                need(1)?;
                Lad::Ellipsoidal(p[0])
            }
            "twoParamBeta" => {
                need(2)?;
                if p[0] <= 0.0 || p[1] <= 0.0 {
                    return Err(Error::invalid("beta LAD parameters must be positive"));
                }
                Lad::TwoParamBeta(p[0], p[1])
            }
            other => return Err(Error::invalid(format!("unknown leaf angle distribution {other:?}"))),
        })
    }

    /// The `--lad` name.
    pub fn name(&self) -> &'static str {
        match self {
            Lad::Spherical => "spherical",
            Lad::Uniform => "uniform",
            Lad::Planophile => "planophile",
            Lad::Erectophile => "erectophile",
            Lad::Plagiophile => "plagiophile",
            Lad::Extremophile => "extremophile",
            Lad::Ellipsoidal(_) => "ellipsoidal",
            Lad::TwoParamBeta(..) => "twoParamBeta",
        }
    }

    /// Probability density of the leaf inclination `t` on `[0, π/2]` (the
    /// zenith angle of the leaf normal, 0 for a horizontal leaf).
    pub fn pdf(&self, t: f64) -> f64 {
        match *self {
            Lad::Spherical => t.sin(),
            Lad::Uniform => 2.0 / PI,
            Lad::Planophile => 2.0 / PI * (1.0 + (2.0 * t).cos()),
            Lad::Erectophile => 2.0 / PI * (1.0 - (2.0 * t).cos()),
            Lad::Plagiophile => 2.0 / PI * (1.0 - (4.0 * t).cos()),
            Lad::Extremophile => 2.0 / PI * (1.0 + (4.0 * t).cos()),
            Lad::Ellipsoidal(chi) => {
                if chi == 1.0 {
                    return t.sin();
                }
                let lambda = if chi < 1.0 {
                    let e = (1.0 - chi * chi).sqrt();
                    chi + e.asin() / e
                } else {
                    let e = (1.0 - 1.0 / (chi * chi)).sqrt();
                    chi + ((1.0 + e) / (1.0 - e)).ln() / (2.0 * e * chi)
                };
                2.0 * chi.powi(3) * t.sin() / (lambda * (t.cos().powi(2) + chi * chi * t.sin().powi(2)).powi(2))
            }
            Lad::TwoParamBeta(mu, nu) => {
                let x = 2.0 * t / PI;
                if !(0.0..=1.0).contains(&x) {
                    return 0.0;
                }
                let ln_b = ln_gamma(mu) + ln_gamma(nu) - ln_gamma(mu + nu);
                (1.0 - x).powf(mu - 1.0) * x.powf(nu - 1.0) / ln_b.exp() * (2.0 / PI)
            }
        }
    }
}

/// Lanczos approximation of `ln Γ(x)` for `x > 0`.
fn ln_gamma(x: f64) -> f64 {
    const G: [f64; 9] = [
        0.999_999_999_999_809_9,
        676.520_368_121_885_1,
        -1_259.139_216_722_402_8,
        771.323_428_777_653_1,
        -176.615_029_162_140_6,
        12.507_343_278_686_905,
        -0.138_571_095_265_720_12,
        9.984_369_578_019_572e-6,
        1.505_632_735_149_311_6e-7,
    ];
    if x < 0.5 {
        return (PI / (PI * x).sin()).ln() - ln_gamma(1.0 - x);
    }
    let x = x - 1.0;
    let t = x + 7.5;
    let s = G.iter().enumerate().skip(1).fold(G[0], |s, (i, g)| s + g / (x + i as f64));
    0.5 * (2.0 * PI).ln() + (x + 0.5) * t.ln() - t + s.ln()
}

/// Mean projection of a unit leaf at inclination `leaf` onto the plane normal
/// to a beam at zenith `beam`, for uniform leaf azimuth.
///
/// Where the leaf plane can turn edge-on to the beam, the kernel is
/// `cos b cos l (1 + 2/π (tan a - a))` with `cos a = cot b cot l`, written as
/// `cos b cos l (1 - 2a/π) + 2/π sin b sin l sin a` (the two are equal):
/// the first form takes `tan a` of an angle that rounds to π/2 when the
/// leaf is vertical, which is far from the limit `2/π sin b` there (0.34
/// instead of 0.54 for a beam at 1 rad).
fn projection_kernel(beam: f64, leaf: f64) -> f64 {
    let cotcot = 1.0 / (beam.tan() * leaf.tan());
    if cotcot.abs() > 1.0 || cotcot.is_infinite() {
        return beam.cos() * leaf.cos();
    }
    let a = cotcot.acos();
    beam.cos() * leaf.cos() * (1.0 - 2.0 * a / PI) + 2.0 / PI * beam.sin() * leaf.sin() * a.sin()
}

fn fold_beam_angle(theta: f64) -> f64 {
    let mut t = theta % PI;
    if t > FRAC_PI_2 {
        t = PI - t;
    }
    t.min(FRAC_PI_2 - 1e-9)
}

/// Projection function `G(θ)` of a leaf angle distribution for a beam at
/// zenith `theta` (rad). 180-step trapezoid; for the beta
/// distribution, the kernel at the middle of each of the 180 steps times the
/// exact probability of the step.
pub fn compute_g(theta: f64, lad: &Lad) -> f64 {
    if *lad == Lad::Spherical {
        return 0.5;
    }
    let theta = fold_beam_angle(theta);
    let n = 180;
    let h = FRAC_PI_2 / n as f64;
    if let Lad::TwoParamBeta(mu, nu) = *lad {
        // With a parameter below 1 the density is infinite at that end (and
        // steep near it for one a little above 1), which a trapezoid over the
        // density misses; the probability of each step is exact whatever the shape.
        // t = 2 theta / pi follows Beta(nu, mu) in the usual order.
        let cdf = |i: usize| crate::fusion::upscale::inc_beta(nu, mu, i as f64 / n as f64);
        return (0..n).map(|i| projection_kernel(theta, (i as f64 + 0.5) * h) * (cdf(i + 1) - cdf(i))).sum();
    }
    let f = |t: f64| projection_kernel(theta, t) * lad.pdf(t);
    let mut sum = 0.5 * (f(0.0) + f(FRAC_PI_2));
    for i in 1..n {
        sum += f(i as f64 * h);
    }
    h * sum
}

/// `G(θ)` against an empirical (normalised) inclination histogram.
pub fn compute_g_from_histogram(theta: f64, bin_centres: &[f64], hist: &[f64]) -> f64 {
    if bin_centres.is_empty() || bin_centres.len() != hist.len() {
        return 0.5;
    }
    let theta = fold_beam_angle(theta);
    bin_centres.iter().zip(hist).map(|(&c, &h)| projection_kernel(theta, c) * h).sum()
}

/// Closest de Wit distribution to an inclination histogram (L2 on the
/// normalised bins); `None` for an empty histogram.
pub fn classify_de_wit(bin_centres: &[f64], hist: &[f64]) -> Option<&'static str> {
    let total: f64 = hist.iter().sum();
    if bin_centres.is_empty() || hist.len() != bin_centres.len() || total <= 0.0 {
        return None;
    }
    let mut best = (f64::INFINITY, None);
    for lad in [Lad::Planophile, Lad::Erectophile, Lad::Plagiophile, Lad::Extremophile, Lad::Spherical, Lad::Uniform] {
        let reference: Vec<f64> = bin_centres.iter().map(|&c| lad.pdf(c)).collect();
        let ref_sum: f64 = reference.iter().sum();
        if ref_sum <= 0.0 {
            continue;
        }
        let d2: f64 = hist.iter().zip(&reference).map(|(h, r)| (h / total - r / ref_sum).powi(2)).sum();
        if d2 < best.0 {
            best = (d2, Some(lad.name()));
        }
    }
    best.1
}

/// `(beam diameter at exit [m], divergence [rad])` of a known scanner.
pub fn laser_spec(name: &str) -> Option<(f64, f64)> {
    Some(match name.to_ascii_uppercase().replace('_', "-").as_str() {
        "LMS-Q560" => (0.0003, 0.0005),
        "LMS-Q780" => (0.005, 0.00025),
        "VZ-400" | "VZ-400I" => (0.007, 0.00035),
        "LEICA-SCANSTATION-P30-40" => (0.0035, 0.00023),
        "LEICA-SCANSTATION-C10" => (0.004, 0.0001),
        "FARO-FOCUS-X330" => (0.0025, 0.00019),
        "MINIVUX-1UAV" => (0.0145, 0.00105),
        "TRIMBLE-X7" => (0.0026, 0.0008),
        "UNITARY-BEAM-SECTION" => (0.0, 0.0),
        _ => return None,
    })
}

/// Bailey & Mahaffee (2017) eq. 10: area density from the mean gap
/// probability `1 − hits / beams` over the mean path, by the secant method.
pub fn solve_bailey_pad(path_length: f64, beams_weighted: f64, hits: f64, g: f64) -> f64 {
    if g <= 0.0 || beams_weighted < 1.0 {
        return 0.0;
    }
    let r_bar = path_length / beams_weighted;
    if r_bar <= 0.0 {
        return 0.0;
    }
    let p_bar = (1.0 - hits / beams_weighted).clamp(1e-12, 1.0 - 1e-12);
    let residual = |a: f64| p_bar - (-a * g * r_bar).exp();
    let mut a0 = -p_bar.ln() / (g * r_bar);
    let mut a1 = a0 * 1.0001 + 1e-6;
    let (mut f0, mut f1) = (residual(a0), residual(a1));
    for _ in 0..50 {
        if f1.abs() < 1e-9 || (f1 - f0).abs() < 1e-18 {
            break;
        }
        let a2 = a1 - f1 * (a1 - a0) / (f1 - f0);
        (a0, f0) = (a1, f1);
        a1 = a2;
        f1 = residual(a1);
    }
    a1.max(0.0)
}

/// Area densities of one voxel for one attenuation method.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct AreaDensity {
    pub pad: f64,
    pub lad: f64,
    pub wad: f64,
}

impl RayVoxels {
    /// Attenuation coefficient λ (m⁻¹). `Bailey` has no λ of its own and
    /// falls back to `hits / path_length`.
    ///
    /// * FPL: intercepted beam section over the effective free path
    ///   (hits over free path without beam metrics) — the biased MLE of
    ///   Pimont et al. (2018), with the beam footprint of Pimont et al. (2019).
    /// * Transmittance: `−ln(1 − intercepted / entering) / mean chord`, the mean chord (m)
    ///   being `path_length / num_beams`; without beam metrics, the weighted hits over the
    ///   weighted beams take the place of the beam sections.
    /// * PPL: the exact solve where available, otherwise the mean-chord form
    ///   (Pimont et al. 2018).
    pub fn attenuation(&self, idx: usize, method: Attenuation) -> f64 {
        let f = |fld: F| self.get_f(fld, idx) as f64;
        // Share-weighted: the free path and beam counts below carry each
        // segment's share of the pulse, so the hits must too.
        let hits_w = self.get_f(F::HitsWeighted, idx) as f64;
        // −ln of a transmittance is an optical depth (dimensionless); over the
        // mean length of the pulses' paths across the voxel it is an
        // attenuation coefficient, which does not depend on the voxel size.
        let beams = self.get_i(I::NumBeams, idx) as f64;
        let mean_chord = if beams > 0.0 { f(F::PathLength) / beams } else { 0.0 };
        let per_metre = |depth: f64| if mean_chord > EPS { depth / mean_chord } else { 0.0 };
        let transmittance = || {
            if f(F::BsEntering) > EPS {
                return Some(per_metre(-((f(F::BsEntering) - f(F::BsIntercepted)) / f(F::BsEntering)).max(EPS).ln()));
            }
            None
        };
        match method {
            Attenuation::Fpl => {
                if f(F::BsEffectiveFreePath) > EPS {
                    f(F::BsIntercepted) / f(F::BsEffectiveFreePath)
                } else if f(F::FreePathLength) > EPS {
                    hits_w / f(F::FreePathLength)
                } else {
                    0.0
                }
            }
            Attenuation::Transmittance => transmittance().unwrap_or_else(|| {
                if f(F::NumBeamsWeighted) > EPS {
                    per_metre(-(1.0 - (hits_w / f(F::NumBeamsWeighted)).min(1.0 - EPS)).ln())
                } else {
                    0.0
                }
            }),
            Attenuation::Ppl => {
                let hits = self.get_i(I::NumHits, idx) as f64;
                if let Some(k) = self.ppl_lambda.as_ref().map(|v| v[idx]).filter(|&k| k >= 0.0) {
                    return k as f64;
                }
                let n = hits;
                let m = (self.get_i(I::NumBeams, idx) as f64 - hits).max(0.0);
                let d_n = if n > EPS { f(F::SumHitDelta) / n } else { 0.0 };
                let d_m = if m > EPS { f(F::SumMissDelta) / m } else { 0.0 };
                if n < EPS || d_n < EPS {
                    return transmittance().unwrap_or(0.0);
                }
                if m < EPS || d_m < EPS {
                    return 50.0 / d_n;
                }
                // m δ_m = n δ_n e^{−λ δ_n} / (1 − e^{−λ δ_n})
                let (mut lo, mut hi) = (EPS, 50.0 / d_n.min(d_m));
                for _ in 0..60 {
                    let mid = 0.5 * (lo + hi);
                    let e = (-mid * d_n).exp();
                    if 1.0 - e < EPS {
                        hi = mid;
                    } else if m * d_m < n * d_n * e / (1.0 - e) {
                        lo = mid;
                    } else {
                        hi = mid;
                    }
                }
                0.5 * (lo + hi)
            }
            Attenuation::Bailey => {
                if f(F::PathLength) > EPS {
                    hits_w / f(F::PathLength)
                } else {
                    0.0
                }
            }
        }
    }

    /// λ with the Pimont et al. (2018) bias term taken off the FPL estimate;
    /// the other methods have no correction. This is the λ behind the area
    /// densities and the `attenuation_fpl` column, so a poorly sampled voxel
    /// can come out slightly negative: the term is subtracted from a noisy
    /// estimate near zero. That is the unbiased estimator working as it
    /// should, and dropping only those voxels would bias every mean upward.
    pub fn attenuation_corrected(&self, idx: usize, method: Attenuation) -> f64 {
        let lambda = self.attenuation(idx, method);
        if method == Attenuation::Fpl { lambda - self.fpl_bias(idx) } else { lambda }
    }

    /// Pimont et al. (2018) bias correction of the FPL estimate.
    pub fn fpl_bias(&self, idx: usize) -> f64 {
        let w_eff = self.get_f(F::BsEffectiveFreePath, idx) as f64;
        let beams = self.get_i(I::NumBeams, idx);
        if w_eff > EPS && beams > 0 {
            self.get_f(F::BsEffFreePathHits, idx) as f64 * self.get_f(F::BsEntering, idx) as f64 / (w_eff * w_eff * beams as f64)
        } else {
            0.0
        }
    }

    /// Bias-corrected contact-frequency density for a spherical leaf angle
    /// distribution: `2 (N − 1) / N · hits / path_length`, with each echo
    /// counted as its share of the pulse (a pulse is intercepted at most once).
    pub fn pad_g0_5(&self, idx: usize) -> f64 {
        let n = self.get_f(F::NumBeamsWeighted, idx) as f64;
        if n < 2.0 {
            return 0.0;
        }
        2.0 * (n - 1.0) * self.get_f(F::HitsWeighted, idx) as f64 / (EPS + n * self.get_f(F::PathLength, idx) as f64)
    }

    /// Beam-section transmittance over one metre of path (0–1), as AMAPVox normalises it:
    /// `exp(−bs_intercepted / bs_free_path)`, the gap probability of a 1 m path through
    /// vegetation like the voxel's. It is not the gap probability of the voxel itself, which
    /// is this to the power of the path length across it (m), so values compare between grids
    /// of different voxel sizes. Where the beams have no free path to divide by, the share of
    /// the entering section that was not intercepted; 1 where no beam entered or beam metrics
    /// are off.
    pub fn transmittance(&self, idx: usize) -> f64 {
        let f = |fld: F| self.get_f(fld, idx) as f64;
        if f(F::BsFreePath) > EPS {
            (-f(F::BsIntercepted) / f(F::BsFreePath)).exp()
        } else if f(F::BsEntering) > EPS {
            ((f(F::BsEntering) - f(F::BsIntercepted)) / f(F::BsEntering)).max(0.0)
        } else {
            1.0
        }
    }

    /// Weighted mean angle of the beams from the vertical (rad, 0 to π/2): beams travelling
    /// down count as the upward beams along the same line, so beams from above and below do
    /// not average to a horizontal one. 0 where no beam entered.
    pub fn mean_zenith(&self, idx: usize) -> f64 {
        let n = self.get_f(F::NumBeamsWeighted, idx);
        if n > 0.0 { (self.get_f(F::SumOfAngles, idx) / n) as f64 } else { 0.0 }
    }

    /// Circular mean beam azimuth (rad, `atan2(x, y)` in `[0, 2π)`) and its
    /// concentration (mean resultant length).
    pub fn mean_azimuth(&self, idx: usize) -> (f64, f64) {
        let n = self.get_f(F::NumBeamsWeighted, idx) as f64;
        if n <= 0.0 {
            return (0.0, 0.0);
        }
        let (s, c) = (self.get_f(F::SumSinAzimuth, idx) as f64 / n, self.get_f(F::SumCosAzimuth, idx) as f64 / n);
        (s.atan2(c).rem_euclid(2.0 * PI), s.hypot(c))
    }

    /// Weighted mean distance from the scanner to the voxel centre (m); 0 where no beam entered.
    pub fn mean_laser_distance(&self, idx: usize) -> f64 {
        let n = self.get_f(F::NumBeamsWeighted, idx);
        if n > 0.0 { (self.get_f(F::SumOfLaserDistances, idx) / n) as f64 } else { 0.0 }
    }

    /// Standard deviation of the chords of the beams crossing the voxel.
    pub fn sd_path_length(&self, idx: usize) -> f64 {
        let n = self.get_i(I::NumBeams, idx) as f64;
        if n <= 1.0 {
            return 0.0;
        }
        let mean = self.get_f(F::PathLength, idx) as f64 / n;
        (self.get_f(F::PathLengthSq, idx) as f64 / n - mean * mean).max(0.0).sqrt()
    }

    /// Centre height above the terrain (NaN without a DTM).
    pub fn distance_from_ground(&self, idx: usize) -> f64 {
        match &self.ground_height {
            Some(g) => self.center(idx)[2] - g[idx % (self.shape[0] * self.shape[1])],
            None => f64::NAN,
        }
    }

    /// Fraction of sub-voxel cells crossed by enough beams, and their bitmap.
    pub fn exploration(&self, idx: usize) -> (f64, u64) {
        let n_sub = self.params.subvoxel_split.pow(3);
        let Some(counts) = self.subvoxel_counts.as_ref().filter(|_| n_sub > 0) else { return (0.0, 0) };
        let mut bits = 0u64;
        for (b, &c) in counts[idx * n_sub..(idx + 1) * n_sub].iter().enumerate() {
            if c >= self.params.subvoxel_min_beams {
                bits |= 1 << b;
            }
        }
        (bits.count_ones() as f64 / n_sub as f64, bits)
    }

    /// `G` at the voxel's mean beam zenith for the analytic [`Lad`].
    pub fn g_analytic(&self, idx: usize) -> f64 {
        compute_g(self.mean_zenith(idx), &self.params.lad)
    }

    /// Plant area density `λ / G(mean zenith)` with the first attenuation
    /// method and the analytic leaf angle distribution.
    pub fn pad_g_corrected(&self, idx: usize) -> f64 {
        if self.get_f(F::PathLength, idx) <= 0.0 {
            return 0.0;
        }
        let g = self.g_analytic(idx);
        if g > 0.0 { self.attenuation_corrected(idx, self.params.attenuation[0]) / g } else { 0.0 }
    }

    /// The inclination distribution governing a voxel (its predominant tree's).
    pub fn voxel_iad(&self, idx: usize) -> Option<&super::TreeIad> {
        let tid = *self.predominant_tree.as_ref()?.get(idx)?;
        self.tree_iad.get(&tid)
    }

    /// Plant / leaf / wood area density. With an inclination distribution the
    /// `G` values are the tree's angle-integrated ones (Vicari et al. 2019),
    /// FPL is taken per class from the class free paths, and Bailey solves
    /// eq. 10 per class; otherwise `G` comes from the analytic [`Lad`] and
    /// leaf / wood split λ by their share of the hits.
    pub fn area_density(&self, idx: usize, method: Attenuation) -> AreaDensity {
        let mut out = AreaDensity::default();
        let path = self.get_f(F::PathLength, idx) as f64;
        if path <= 0.0 {
            return out;
        }
        let hits = self.get_i(I::NumHits, idx) as f64;
        let hit_total = hits.max(EPS);
        let leaf = self.get_i(I::NumHitLeaf, idx) as f64;
        let wood = self.get_i(I::NumHitWood, idx) as f64;
        let Some(iad) = self.voxel_iad(idx) else {
            let g = self.g_analytic(idx);
            if g > 0.0 {
                let lambda = self.attenuation_corrected(idx, method);
                out.pad = lambda / g;
                if self.has_leaf {
                    out.lad = lambda * leaf / hit_total / g;
                }
                if self.has_wood {
                    out.wad = lambda * wood / hit_total / g;
                }
            }
            return out;
        };
        match method {
            Attenuation::Bailey => {
                let beams = self.get_f(F::NumBeamsWeighted, idx) as f64;
                if iad.bailey_g_leaf > 0.0 && leaf > 0.0 {
                    out.lad = solve_bailey_pad(path, beams, leaf, iad.bailey_g_leaf);
                }
                if iad.bailey_g_wood > 0.0 && wood > 0.0 {
                    out.wad = solve_bailey_pad(path, beams, wood, iad.bailey_g_wood);
                }
                out.pad = match (leaf > 0.0, wood > 0.0) {
                    (false, true) => out.wad,
                    (true, false) => out.lad,
                    (true, true) if iad.g_plant > 0.0 => solve_bailey_pad(path, beams, hits, iad.g_plant),
                    _ => 0.0,
                };
            }
            Attenuation::Fpl => {
                // The per-class count estimator (hits over the class free
                // path); the beam-section bias term does not apply to it.
                let class = |n: i32, fp: f32, g: f64| if g > 0.0 && fp as f64 > EPS { n as f64 / (fp as f64 * g) } else { 0.0 };
                // Plant hits count every vegetation echo, so pair them with the free
                // path of every vegetation segment (the unclassified ones alone would
                // give 0 for a fully leaf / wood labelled cloud).
                let plant_path = self.get_f(F::FreePathLengthPlant, idx) + self.get_f(F::FreePathLengthLeaf, idx) + self.get_f(F::FreePathLengthWood, idx);
                out.pad = class(self.get_i(I::NumHitPlant, idx), plant_path, iad.g_plant);
                out.lad = class(self.get_i(I::NumHitLeaf, idx), self.get_f(F::FreePathLengthLeaf, idx), iad.g_leaf);
                out.wad = class(self.get_i(I::NumHitWood, idx), self.get_f(F::FreePathLengthWood, idx), iad.g_wood);
            }
            _ => {
                let lambda = self.attenuation_corrected(idx, method);
                if iad.g_plant > 0.0 {
                    out.pad = lambda / iad.g_plant;
                }
                if iad.g_leaf > 0.0 {
                    out.lad = lambda * leaf / hit_total / iad.g_leaf;
                }
                if iad.g_wood > 0.0 {
                    out.wad = lambda * wood / hit_total / iad.g_wood;
                }
            }
        }
        out
    }

    /// A derived quantity for every voxel, by name. See [`RayVoxels::METRICS`];
    /// `pad_<method>`, `lad_<method>`, `wad_<method>` and
    /// `attenuation_<method>` are accepted for any attenuation method.
    pub fn metric(&self, name: &str) -> Result<Vec<f64>> {
        use rayon::prelude::*;
        let n = self.n_voxels();
        let map = |f: &(dyn Fn(usize) -> f64 + Sync)| Ok((0..n).into_par_iter().map(f).collect());
        let volume = self.voxel_size.powi(3);
        match name {
            "state" => map(&|i| self.state(i) as u8 as f64),
            "pad_g0_5" => map(&|i| self.pad_g0_5(i)),
            "surface_area" => map(&|i| self.pad_g0_5(i) * volume),
            "pad_g_corrected" => map(&|i| self.pad_g_corrected(i)),
            "transmittance" => map(&|i| self.transmittance(i)),
            "mean_zenith_angle" => map(&|i| self.mean_zenith(i).to_degrees()),
            "mean_azimuth_angle" => map(&|i| self.mean_azimuth(i).0.to_degrees()),
            "azimuth_concentration" => map(&|i| self.mean_azimuth(i).1),
            "mean_laser_dist" => map(&|i| self.mean_laser_distance(i)),
            "sd_path_length" => map(&|i| self.sd_path_length(i)),
            "distance_from_ground" => map(&|i| self.distance_from_ground(i)),
            "exploration_rate" => map(&|i| self.exploration(i).0),
            "attenuation_fpl_biased" => map(&|i| self.attenuation(i, Attenuation::Fpl)),
            "attenuation_fpl_correction" => map(&|i| self.fpl_bias(i)),
            "attenuation_fpl" => map(&|i| self.attenuation_corrected(i, Attenuation::Fpl)),
            "g_plant" => map(&|i| self.voxel_iad(i).map_or_else(|| self.g_analytic(i), |t| t.g_plant)),
            "g_leaf" => map(&|i| self.voxel_iad(i).map_or(0.0, |t| t.g_leaf)),
            "g_wood" => map(&|i| self.voxel_iad(i).map_or(0.0, |t| t.g_wood)),
            "wood_volume_density" => match &self.wood_volume {
                Some(w) => map(&|i| w[i] as f64 / volume),
                None => Err(Error::invalid("no wood volume has been added")),
            },
            other => {
                let (kind, method) = other.split_once('_').ok_or_else(|| Error::invalid(format!("unknown voxel metric {other:?}")))?;
                let m = Attenuation::parse(method).map_err(|_| Error::invalid(format!("unknown voxel metric {other:?}")))?;
                match kind {
                    "attenuation" => map(&|i| self.attenuation(i, m)),
                    "pad" => map(&|i| self.area_density(i, m).pad),
                    "lad" => map(&|i| self.area_density(i, m).lad),
                    "wad" => map(&|i| self.area_density(i, m).wad),
                    _ => Err(Error::invalid(format!("unknown voxel metric {other:?}"))),
                }
            }
        }
    }

    /// Names [`RayVoxels::metric`] accepts besides `pad_`, `lad_`, `wad_` and `attenuation_<method>`.
    pub const METRICS: [&'static str; 19] = [
        "state", "pad_g0_5", "surface_area", "pad_g_corrected", "transmittance", "mean_zenith_angle",
        "mean_azimuth_angle", "azimuth_concentration", "mean_laser_dist", "sd_path_length", "distance_from_ground",
        "exploration_rate", "attenuation_fpl_biased", "attenuation_fpl_correction", "attenuation_fpl", "g_plant",
        "g_leaf", "g_wood", "wood_volume_density",
    ];
}

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

    fn all_lads() -> Vec<Lad> {
        vec![Lad::Spherical, Lad::Uniform, Lad::Planophile, Lad::Erectophile, Lad::Plagiophile, Lad::Extremophile, Lad::Ellipsoidal(0.6), Lad::Ellipsoidal(1.0), Lad::Ellipsoidal(2.5), Lad::TwoParamBeta(2.0, 3.0), Lad::TwoParamBeta(0.8, 1.4), Lad::TwoParamBeta(0.433, 0.433)]
    }

    /// Simpson's rule on `[a, b]` with `n` (even) intervals.
    fn simpson(f: impl Fn(f64) -> f64, a: f64, b: f64, n: usize) -> f64 {
        let h = (b - a) / n as f64;
        let inner: f64 = (1..n).map(|i| f(a + i as f64 * h) * if i % 2 == 1 { 4.0 } else { 2.0 }).sum();
        (f(a) + f(b) + inner) * h / 3.0
    }

    #[test]
    fn every_distribution_is_a_density() {
        for lad in all_lads() {
            // Midpoints, as a beta density with a parameter below 1 is infinite at that end.
            let n = 2_000_000;
            let h = FRAC_PI_2 / n as f64;
            let total: f64 = (0..n).map(|i| lad.pdf((i as f64 + 0.5) * h)).sum::<f64>() * h;
            let tol = if matches!(lad, Lad::TwoParamBeta(m, n) if m < 1.0 || n < 1.0) { 5e-3 } else { 1e-9 };
            assert!((total - 1.0).abs() < tol, "{} integrates to {total}", lad.name());
        }
        assert_eq!(Lad::TwoParamBeta(2.0, 3.0).pdf(-0.1), 0.0);
        // Goel & Strebel's order: (1 - t)^(mu - 1) t^(nu - 1) / B(mu, nu), t = 2 theta / pi.
        let t: f64 = 0.3;
        let want = (1.0 - t) * t * t * 12.0 * 2.0 / PI; // B(2, 3) = 1 / 12
        assert!((Lad::TwoParamBeta(2.0, 3.0).pdf(t * FRAC_PI_2) - want).abs() < 1e-9);
        assert!((Lad::TwoParamBeta(1.0, 1.0).pdf(0.7) - 2.0 / PI).abs() < 1e-12);
    }

    #[test]
    fn names_and_parameters_round_trip() {
        for lad in all_lads() {
            let p = match lad {
                Lad::Ellipsoidal(chi) => vec![chi],
                Lad::TwoParamBeta(m, n) => vec![m, n],
                _ => vec![],
            };
            assert_eq!(Lad::parse(lad.name(), &p).unwrap(), lad);
        }
        let err = |name: &str, p: &[f64]| Lad::parse(name, p).unwrap_err().to_string();
        assert_eq!(err("ellipsoidal", &[]), "LAD \"ellipsoidal\" needs 1 parameter(s)");
        assert_eq!(err("twoParamBeta", &[1.0]), "LAD \"twoParamBeta\" needs 2 parameter(s)");
        assert_eq!(err("twoParamBeta", &[1.0, 0.0]), "beta LAD parameters must be positive");
        assert_eq!(err("conical", &[]), "unknown leaf angle distribution \"conical\"");
    }

    #[test]
    fn projection_functions_integrate_to_one_half() {
        // Ross (1981): the integral of G(theta) sin(theta) over the hemisphere is 1/2 for any LAD.
        for lad in all_lads() {
            let g0 = compute_g(0.3, &lad);
            assert!(g0 > 0.0 && g0 < 1.0, "{}", lad.name());
            let integral = simpson(|t| compute_g(t, &lad) * t.sin(), 0.0, FRAC_PI_2, 360);
            assert!((integral - 0.5).abs() < 5e-3, "{}: {integral}", lad.name());
        }
        // A horizontal leaf presents cos(theta), a vertical one (2/pi) sin(theta).
        let flat = [1.0, 0.0, 0.0];
        let upright = [0.0, 0.0, 1.0];
        let centres = [0.0, 0.8, FRAC_PI_2];
        for theta in [0.2f64, 1.0, 1.4] {
            assert!((compute_g_from_histogram(theta, &centres, &flat) - theta.cos()).abs() < 1e-12);
            assert!((compute_g_from_histogram(theta, &centres, &upright) - 2.0 / PI * theta.sin()).abs() < 1e-6);
            // Beams from below see the same leaves.
            assert!((compute_g_from_histogram(PI - theta, &centres, &flat) - theta.cos()).abs() < 1e-9);
        }
        // Goel & Strebel's (1984) beta fits of the de Wit types give their G.
        for (beta, de_wit) in [(Lad::TwoParamBeta(2.770, 1.172), Lad::Planophile), (Lad::TwoParamBeta(1.172, 2.770), Lad::Erectophile), (Lad::TwoParamBeta(3.326, 3.326), Lad::Plagiophile), (Lad::TwoParamBeta(0.433, 0.433), Lad::Extremophile), (Lad::TwoParamBeta(1.0, 1.0), Lad::Uniform), (Lad::TwoParamBeta(1.101, 1.930), Lad::Spherical)] {
            for theta in [0.1f64, 0.6, 1.0, 1.4] {
                let (b, d) = (compute_g(theta, &beta), compute_g(theta, &de_wit));
                assert!((b - d).abs() < 0.03, "{} at {theta}: {b} vs {d}", de_wit.name());
            }
        }
        assert_eq!(compute_g_from_histogram(0.5, &[], &[]), 0.5);
        assert_eq!(compute_g_from_histogram(0.5, &centres, &[1.0]), 0.5);
    }

    #[test]
    fn kernel_is_continuous_at_a_vertical_leaf() {
        // The limit as the leaf turns vertical is (2 / pi) sin(beam), and the
        // kernel just short of it agrees.
        for beam in [0.05f64, 0.2, 0.6, 1.0, 1.4, FRAC_PI_2 - 1e-9] {
            let limit = 2.0 / PI * beam.sin();
            assert!((projection_kernel(beam, FRAC_PI_2) - limit).abs() < 1e-12, "{beam}");
            assert!((projection_kernel(beam, FRAC_PI_2 - 1e-7) - limit).abs() < 1e-6, "{beam}");
            // Both forms of the kernel agree away from the vertical.
            for leaf in [0.3f64, 0.9, 1.3] {
                let c = 1.0 / (beam.tan() * leaf.tan());
                // (The old form loses precision as the beam nears the horizon.)
                if c.abs() <= 1.0 && beam < 1.5 {
                    let a = c.acos();
                    let old = beam.cos() * leaf.cos() * (1.0 + 2.0 / PI * (a.tan() - a));
                    assert!((projection_kernel(beam, leaf) - old).abs() < 1e-12);
                }
            }
        }
    }

    #[test]
    fn ln_gamma_matches_known_values() {
        for (x, want) in [(5.0, 24f64.ln()), (0.5, PI.sqrt().ln()), (0.25, 3.625_609_908_221_908_f64.ln()), (1.0, 0.0), (10.5, 1_133_278.388_948_785_4_f64.ln())] {
            assert!((ln_gamma(x) - want).abs() < 1e-10, "ln_gamma({x})");
        }
    }

    #[test]
    fn de_wit_types_are_recognised() {
        let centres: Vec<f64> = (0..18).map(|b| (b as f64 + 0.5) * FRAC_PI_2 / 18.0).collect();
        for lad in [Lad::Planophile, Lad::Erectophile, Lad::Plagiophile, Lad::Extremophile, Lad::Spherical, Lad::Uniform] {
            let hist: Vec<f64> = centres.iter().map(|&c| lad.pdf(c)).collect();
            assert_eq!(classify_de_wit(&centres, &hist), Some(lad.name()));
        }
        assert_eq!(classify_de_wit(&centres, &[0.0; 18]), None);
        assert_eq!(classify_de_wit(&centres, &[1.0; 3]), None);
    }

    #[test]
    fn bailey_equation_inverts_beer_lambert() {
        // With P = 1 - hits / beams over a mean path r: P = exp(-a G r).
        let (path, beams, hits, g) = (30.0, 20.0, 5.0, 0.6);
        let a = solve_bailey_pad(path, beams, hits, g);
        let r = path / beams;
        assert!(((1.0 - hits / beams) - (-a * g * r).exp()).abs() < 1e-9);
        assert!((a - -(0.75f64).ln() / (g * r)).abs() < 1e-9);
        assert!(solve_bailey_pad(path, beams, 0.0, g).abs() < 1e-10, "no hits");
        assert_eq!(solve_bailey_pad(path, beams, hits, 0.0), 0.0, "no G");
        assert_eq!(solve_bailey_pad(path, 0.5, hits, g), 0.0, "under one beam");
        assert_eq!(solve_bailey_pad(0.0, beams, hits, g), 0.0, "no path");
        let saturated = solve_bailey_pad(path, beams, beams, g);
        assert!(saturated.is_finite() && saturated > 10.0 * a);
    }

    #[test]
    fn scanners_known_to_amapvox() {
        assert_eq!(laser_spec("vz_400i"), Some((0.007, 0.00035)));
        assert_eq!(laser_spec("Trimble-X7"), Some((0.0026, 0.0008)));
        assert_eq!(laser_spec("VZ-2000"), None);
    }
}