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
// Sylva: LiDAR processing for forest ecology and remote sensing research.
// Copyright (C) 2026 Tim Devereux, The University of Queensland.
// 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.
//! Core point cloud container.
//!
//! A [`PointCloud`] is the shape almost every function in the core takes or
//! returns: coordinates in one list, named attribute columns beside them. It
//! is columnar, like a data frame and like the NumPy arrays it becomes on the
//! Python side, not a list of point objects - a cloud of ten million points
//! is a handful of long arrays, so a pass over one attribute reads only that
//! attribute.
//!
//! It is plain data and holds no indexes, no spatial structure and no opinion
//! about what the attributes mean. Anything that needs a neighbour search
//! builds a tree over the coordinates and drops it afterwards.

use std::collections::BTreeMap;

use crate::error::{Error, Result};
use crate::transform::Transform;
use crate::Point;

/// A typed per-point attribute column.
///
/// Types mirror what LAS and numpy commonly carry so files round-trip
/// without silent widening.
///
/// An `enum` in Rust is a value that is exactly one of its listed cases, and
/// here each case carries a whole column: an `Attr` is one of nine kinds of
/// array, not a struct with nine fields. Code that handles every type writes
/// one `match`, and the compiler refuses any `match` that forgets a case -
/// which is why `attr_dispatch!` below can write the same body once for all
/// nine. Reading a value of unknown type is [`Attr::get_f64`], and a whole
/// column as f64 is [`Attr::to_f64`]; both widen, so use them where the
/// stored type does not matter and the variant directly where it does.
#[derive(Debug, Clone, PartialEq)]
pub enum Attr {
    /// 64-bit floats (numpy float64): heights, distances, GPS time.
    F64(Vec<f64>),
    /// 32-bit floats (numpy float32): reflectance, amplitude and other measured scalars.
    F32(Vec<f32>),
    /// 64-bit signed integers (numpy int64).
    I64(Vec<i64>),
    /// 32-bit signed integers (numpy int32).
    I32(Vec<i32>),
    /// 32-bit unsigned integers (numpy uint32): tree and cluster identifiers.
    U32(Vec<u32>),
    /// 16-bit unsigned integers (numpy uint16): LAS intensity and point source id.
    U16(Vec<u16>),
    /// 8-bit unsigned integers (numpy uint8): LAS classification, return number, number of returns.
    U8(Vec<u8>),
    /// 8-bit signed integers (numpy int8): the LAS scan angle rank.
    I8(Vec<i8>),
    /// Booleans (numpy bool): keep-masks and per-point flags.
    Bool(Vec<bool>),
}

macro_rules! attr_dispatch {
    ($self:expr, $v:ident => $body:expr) => {
        match $self {
            Attr::F64($v) => $body,
            Attr::F32($v) => $body,
            Attr::I64($v) => $body,
            Attr::I32($v) => $body,
            Attr::U32($v) => $body,
            Attr::U16($v) => $body,
            Attr::U8($v) => $body,
            Attr::I8($v) => $body,
            Attr::Bool($v) => $body,
        }
    };
}

impl Attr {
    /// Number of values in the column, the point count of the cloud it belongs to.
    pub fn len(&self) -> usize {
        attr_dispatch!(self, v => v.len())
    }

    /// Whether the column holds no values.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Short dtype name (numpy style).
    pub fn dtype(&self) -> &'static str {
        match self {
            Attr::F64(_) => "float64",
            Attr::F32(_) => "float32",
            Attr::I64(_) => "int64",
            Attr::I32(_) => "int32",
            Attr::U32(_) => "uint32",
            Attr::U16(_) => "uint16",
            Attr::U8(_) => "uint8",
            Attr::I8(_) => "int8",
            Attr::Bool(_) => "bool",
        }
    }

    /// Value at `i` widened to f64.
    pub fn get_f64(&self, i: usize) -> f64 {
        match self {
            Attr::F64(v) => v[i],
            Attr::F32(v) => v[i] as f64,
            Attr::I64(v) => v[i] as f64,
            Attr::I32(v) => v[i] as f64,
            Attr::U32(v) => v[i] as f64,
            Attr::U16(v) => v[i] as f64,
            Attr::U8(v) => v[i] as f64,
            Attr::I8(v) => v[i] as f64,
            Attr::Bool(v) => v[i] as u8 as f64,
        }
    }

    /// Whole column widened to f64.
    pub fn to_f64(&self) -> Vec<f64> {
        (0..self.len()).map(|i| self.get_f64(i)).collect()
    }

    /// Select rows by index.
    pub fn take(&self, idx: &[usize]) -> Attr {
        attr_dispatch!(self, v => {
            let out: Vec<_> = idx.iter().map(|&i| v[i].clone()).collect();
            out.into()
        })
    }

    /// Rows `r` as a column of the same type.
    pub fn slice(&self, r: std::ops::Range<usize>) -> Attr {
        attr_dispatch!(self, v => v[r].to_vec().into())
    }

    /// Append another column of the same type.
    pub fn extend(&mut self, other: &Attr) -> Result<()> {
        match (self, other) {
            (Attr::F64(a), Attr::F64(b)) => a.extend_from_slice(b),
            (Attr::F32(a), Attr::F32(b)) => a.extend_from_slice(b),
            (Attr::I64(a), Attr::I64(b)) => a.extend_from_slice(b),
            (Attr::I32(a), Attr::I32(b)) => a.extend_from_slice(b),
            (Attr::U32(a), Attr::U32(b)) => a.extend_from_slice(b),
            (Attr::U16(a), Attr::U16(b)) => a.extend_from_slice(b),
            (Attr::U8(a), Attr::U8(b)) => a.extend_from_slice(b),
            (Attr::I8(a), Attr::I8(b)) => a.extend_from_slice(b),
            (Attr::Bool(a), Attr::Bool(b)) => a.extend_from_slice(b),
            (a, b) => {
                return Err(Error::invalid(format!(
                    "cannot concatenate {} with {}",
                    a.dtype(),
                    b.dtype()
                )))
            }
        }
        Ok(())
    }
}

macro_rules! attr_from {
    ($($t:ty => $variant:ident),* $(,)?) => {
        $(impl From<Vec<$t>> for Attr {
            fn from(v: Vec<$t>) -> Self { Attr::$variant(v) }
        })*
    };
}
attr_from!(f64 => F64, f32 => F32, i64 => I64, i32 => I32, u32 => U32, u16 => U16, u8 => U8,
           i8 => I8, bool => Bool);

/// A set of 3-D points with optional per-point attributes.
///
/// `xyz[i]` is point `i` as `[x, y, z]`, and every column in `attrs` has one
/// value per point in the same order, so point `i` is row `i` everywhere. A
/// function that drops or reorders points must do the same to every
/// attribute, which is what [`PointCloud::take`] is for.
///
/// `attrs` is a `BTreeMap`, a map kept sorted by name rather than hashed, so
/// walking the attributes gives the same order on every run and in every
/// process - which matters because that order reaches written files and
/// recorded test output.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PointCloud {
    /// Coordinates, one `[x, y, z]` per point (m), in whatever frame the cloud was read or transformed into.
    pub xyz: Vec<Point>,
    /// Named per-point columns, each as long as `xyz`, kept sorted by name.
    pub attrs: BTreeMap<String, Attr>,
}

impl PointCloud {
    /// A cloud of these coordinates and no attributes.
    pub fn new(xyz: Vec<Point>) -> Self {
        PointCloud { xyz, attrs: BTreeMap::new() }
    }

    /// Build from coordinates and attributes, checking lengths.
    pub fn with_attrs(xyz: Vec<Point>, attrs: BTreeMap<String, Attr>) -> Result<Self> {
        for (name, a) in &attrs {
            if a.len() != xyz.len() {
                return Err(Error::invalid(format!(
                    "attribute {name:?} has length {}, expected {}",
                    a.len(),
                    xyz.len()
                )));
            }
        }
        Ok(PointCloud { xyz, attrs })
    }

    /// Number of points.
    pub fn len(&self) -> usize {
        self.xyz.len()
    }

    /// Whether the cloud has no points.
    pub fn is_empty(&self) -> bool {
        self.xyz.is_empty()
    }

    /// Insert or replace an attribute.
    pub fn set_attr(&mut self, name: impl Into<String>, attr: impl Into<Attr>) -> Result<()> {
        let attr = attr.into();
        if attr.len() != self.len() {
            return Err(Error::invalid(format!(
                "attribute has length {}, expected {}",
                attr.len(),
                self.len()
            )));
        }
        self.attrs.insert(name.into(), attr);
        Ok(())
    }

    /// The column called `name`, or `None` if the cloud has no such column.
    ///
    /// `Option` is how Rust says "there may be nothing here"; there is no
    /// null, so the caller has to say what happens when the attribute is
    /// absent - usually `?`, or an error naming it. The returned `&Attr`
    /// borrows this cloud's column rather than copying it.
    pub fn attr(&self, name: &str) -> Option<&Attr> {
        self.attrs.get(name)
    }

    /// Attribute widened to f64, if present.
    pub fn attr_f64(&self, name: &str) -> Option<Vec<f64>> {
        self.attrs.get(name).map(Attr::to_f64)
    }

    /// Heights: the `height` attribute if present, otherwise z.
    pub fn heights(&self, attr: &str) -> Vec<f64> {
        self.attr_f64(attr).unwrap_or_else(|| self.xyz.iter().map(|p| p[2]).collect())
    }

    /// Every point's x coordinate (m), as a lazy sequence like [`PointCloud::z`].
    pub fn x(&self) -> impl Iterator<Item = f64> + '_ {
        self.xyz.iter().map(|p| p[0])
    }

    /// Every point's y coordinate (m), as a lazy sequence like [`PointCloud::z`].
    pub fn y(&self) -> impl Iterator<Item = f64> + '_ {
        self.xyz.iter().map(|p| p[1])
    }

    /// Every point's height, as a sequence computed on demand.
    ///
    /// Nothing is allocated: `impl Iterator` is a lazy sequence that produces
    /// one value at a time, so `cloud.z().sum()` walks the coordinates
    /// without building a column of them. Call `.collect()` for a `Vec` when
    /// one is genuinely needed.
    pub fn z(&self) -> impl Iterator<Item = f64> + '_ {
        self.xyz.iter().map(|p| p[2])
    }

    /// `(min, max)` corners; `None` for an empty cloud.
    pub fn bounds(&self) -> Option<(Point, Point)> {
        if self.xyz.is_empty() {
            return None;
        }
        let mut lo = [f64::INFINITY; 3];
        let mut hi = [f64::NEG_INFINITY; 3];
        for p in &self.xyz {
            for k in 0..3 {
                lo[k] = lo[k].min(p[k]);
                hi[k] = hi[k].max(p[k]);
            }
        }
        Some((lo, hi))
    }

    /// Subset by explicit row indices.
    ///
    /// The one way to keep a subset of the points: the coordinates and every
    /// attribute are indexed together, so rows cannot fall out of step. `idx`
    /// may repeat an index or give them in any order, so this also reorders
    /// and duplicates - the result has one point per entry of `idx`, in that
    /// order. It is the core's equivalent of `cloud[idx]` on a NumPy array.
    pub fn take(&self, idx: &[usize]) -> PointCloud {
        PointCloud {
            xyz: idx.iter().map(|&i| self.xyz[i]).collect(),
            attrs: self.attrs.iter().map(|(k, a)| (k.clone(), a.take(idx))).collect(),
        }
    }

    /// Subset by boolean mask.
    pub fn filter(&self, mask: &[bool]) -> PointCloud {
        let idx: Vec<usize> = mask.iter().enumerate().filter(|(_, &m)| m).map(|(i, _)| i).collect();
        self.take(&idx)
    }

    /// Apply a rigid/affine transform, returning a new cloud.
    pub fn transformed(&self, t: &Transform) -> PointCloud {
        PointCloud { xyz: self.xyz.iter().map(|p| t.apply(p)).collect(), attrs: self.attrs.clone() }
    }

    /// Apply a transform in place.
    pub fn transform_in_place(&mut self, t: &Transform) {
        for p in &mut self.xyz {
            *p = t.apply(p);
        }
    }

    /// Concatenate clouds; only attributes present in all inputs are kept.
    pub fn concatenate(clouds: &[PointCloud]) -> Result<PointCloud> {
        let Some(first) = clouds.first() else {
            return Ok(PointCloud::default());
        };
        let mut out = PointCloud::new(Vec::with_capacity(clouds.iter().map(|c| c.len()).sum()));
        let common: Vec<String> = first
            .attrs
            .keys()
            .filter(|k| clouds.iter().all(|c| c.attrs.contains_key(*k)))
            .cloned()
            .collect();
        for c in clouds {
            out.xyz.extend_from_slice(&c.xyz);
        }
        for name in common {
            let mut col = first.attrs[&name].clone();
            for c in &clouds[1..] {
                col.extend(&c.attrs[&name])?;
            }
            out.attrs.insert(name, col);
        }
        Ok(out)
    }

    /// Centroid of the cloud.
    pub fn centroid(&self) -> Point {
        let n = self.len().max(1) as f64;
        let mut c = [0.0; 3];
        for p in &self.xyz {
            for k in 0..3 {
                c[k] += p[k];
            }
        }
        [c[0] / n, c[1] / n, c[2] / n]
    }
}

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

    fn every_type() -> Vec<Attr> {
        vec![
            Attr::F64(vec![1.5, -2.0, 3.0]),
            Attr::F32(vec![1.5, -2.0, 3.0]),
            Attr::I64(vec![1, -2, 3]),
            Attr::I32(vec![1, -2, 3]),
            Attr::U32(vec![1, 2, u32::MAX]),
            Attr::U16(vec![1, 2, 3]),
            Attr::U8(vec![1, 2, 255]),
            Attr::I8(vec![1, -2, -128]),
            Attr::Bool(vec![true, false, true]),
        ]
    }

    #[test]
    fn attributes_of_every_type() {
        let names: Vec<&str> = every_type().iter().map(Attr::dtype).collect();
        assert_eq!(names, ["float64", "float32", "int64", "int32", "uint32", "uint16", "uint8", "int8", "bool"]);
        let widened: Vec<Vec<f64>> = every_type().iter().map(Attr::to_f64).collect();
        assert_eq!(widened[2], [1.0, -2.0, 3.0]);
        assert_eq!(widened[4], [1.0, 2.0, u32::MAX as f64]);
        assert_eq!(widened[7], [1.0, -2.0, -128.0]);
        assert_eq!(widened[8], [1.0, 0.0, 1.0]);
        for a in every_type() {
            assert_eq!((a.len(), a.is_empty()), (3, false));
            let t = a.take(&[2, 0]);
            assert_eq!(t.dtype(), a.dtype());
            assert_eq!(t.to_f64(), [a.get_f64(2), a.get_f64(0)]);
            assert!(a.take(&[]).is_empty());
            let mut twice = a.clone();
            twice.extend(&a).unwrap();
            assert_eq!(twice.len(), 6);
            assert_eq!(twice.to_f64()[3..], a.to_f64()[..]);
        }
        let mut a = Attr::U8(vec![1]);
        let e = a.extend(&Attr::I8(vec![1])).unwrap_err().to_string();
        assert_eq!(e, "cannot concatenate uint8 with int8");
    }

    fn cloud() -> PointCloud {
        let xyz = vec![[0.0, 0.0, 0.0], [2.0, 4.0, 6.0], [1.0, -2.0, 3.0]];
        let mut c = PointCloud::new(xyz);
        c.set_attr("height", vec![0.5f32, 1.5, 2.5]).unwrap();
        c.set_attr("class", vec![2u8, 5, 5]).unwrap();
        c
    }

    #[test]
    fn lengths_are_checked() {
        let mut c = cloud();
        assert_eq!(c.set_attr("bad", vec![1.0f64]).unwrap_err().to_string(), "attribute has length 1, expected 3");
        let mut attrs = BTreeMap::new();
        attrs.insert("a".to_string(), Attr::F64(vec![1.0]));
        let e = PointCloud::with_attrs(vec![[0.0; 3]; 2], attrs).unwrap_err().to_string();
        assert_eq!(e, "attribute \"a\" has length 1, expected 2");
        assert!(c.attr("bad").is_none() && c.attr_f64("missing").is_none());
    }

    #[test]
    fn coordinates_heights_bounds_and_centroid() {
        let c = cloud();
        assert_eq!(c.x().collect::<Vec<_>>(), [0.0, 2.0, 1.0]);
        assert_eq!(c.y().collect::<Vec<_>>(), [0.0, 4.0, -2.0]);
        assert_eq!(c.z().collect::<Vec<_>>(), [0.0, 6.0, 3.0]);
        assert_eq!(c.heights("height"), [0.5, 1.5, 2.5]);
        assert_eq!(c.heights("nope"), [0.0, 6.0, 3.0], "falls back to z");
        assert_eq!(c.bounds(), Some(([0.0, -2.0, 0.0], [2.0, 4.0, 6.0])));
        assert_eq!(c.centroid(), [1.0, 2.0 / 3.0, 3.0]);
        let empty = PointCloud::default();
        assert!(empty.is_empty() && empty.bounds().is_none());
        assert_eq!(empty.centroid(), [0.0; 3]);
    }

    #[test]
    fn subsets_keep_attributes_in_step() {
        let c = cloud();
        let f = c.filter(&[true, false, true]);
        assert_eq!(f.xyz, [c.xyz[0], c.xyz[2]]);
        assert_eq!(f.attr_f64("height").unwrap(), [0.5, 2.5]);
        assert_eq!(f.attr("class"), Some(&Attr::U8(vec![2, 5])));
        assert!(c.filter(&[false; 3]).is_empty());
    }

    #[test]
    fn transforms_move_points_not_attributes() {
        let c = cloud();
        let t = Transform::rotation_z(90.0).compose(&Transform::translation(1.0, 2.0, 3.0));
        let moved = c.transformed(&t);
        let mut in_place = c.clone();
        in_place.transform_in_place(&t);
        assert_eq!(moved, in_place);
        assert_eq!(moved.attrs, c.attrs);
        for (p, q) in c.xyz.iter().zip(&moved.xyz) {
            assert_eq!(*q, t.apply(p));
        }
        // A quarter turn about z after the shift: (x, y, z) -> (-(y + 2), x + 1, z + 3).
        let q = moved.xyz[1];
        assert!((q[0] + 6.0).abs() < 1e-12 && (q[1] - 3.0).abs() < 1e-12 && (q[2] - 9.0).abs() < 1e-12);
    }

    #[test]
    fn concatenate_keeps_the_common_attributes() {
        let a = cloud();
        let mut b = PointCloud::new(vec![[9.0, 9.0, 9.0]]);
        b.set_attr("height", vec![7.0f32]).unwrap();
        let c = PointCloud::concatenate(&[a.clone(), b.clone()]).unwrap();
        assert_eq!(c.len(), 4);
        assert_eq!(c.xyz[3], [9.0, 9.0, 9.0]);
        assert_eq!(c.attrs.keys().collect::<Vec<_>>(), ["height"], "class is not in both");
        assert_eq!(c.attr_f64("height").unwrap(), [0.5, 1.5, 2.5, 7.0]);
        b.set_attr("height", vec![7.0f64]).unwrap();
        assert_eq!(PointCloud::concatenate(&[a, b]).unwrap_err().to_string(), "cannot concatenate float32 with float64");
        assert_eq!(PointCloud::concatenate(&[]).unwrap(), PointCloud::default());
    }
}