engeom 0.5.0

Library for working with geometry with a focus on engineering metrology applications.
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
//! This module contains `PointAttrSet3`, the bundle of per-point attributes carried by any 3D
//! container which has a point domain.
//!
//! The bundle holds two kinds of data. A small set of first-class attributes are stored as typed
//! fields, and everything else lives in an open, name-keyed map of `Attr3` values. An attribute
//! earns a typed field if either of the following is true:
//!
//! 1. An algorithm in the library reads it in a hot loop, so it shouldn't pay for a hash lookup and
//!    a variant match.
//! 2. The container has to do something to it that it doesn't do to an arbitrary scalar, such as
//!    rotating it under a transform, scaling it, or negating it.
//!
//! # Naming and distributions
//!
//! `stdev` is named for the distribution parameter it holds, not for the general idea of
//! uncertainty, because the container's behavior depends on which one it is. A standard deviation
//! scales by `k` under a uniform scale of `k`, while a variance scales by `k²`. There is no way to
//! scale the value correctly (for example, when converting from mm to inches) without knowing which
//! is stored, so the name has to say.
//!
//! # The flat coordinates
//!
//! `flat` holds one 2D position per point: its location in a flattened chart of the associated
//! surface, such as the output of boundary first flattening. It is not a texture coordinate. It
//! receives a typed field under the second rule above because the container must treat it
//! differently from a generic vector. A rigid motion of the surface leaves its chart unchanged,
//! so `transform_in_place` does not touch it. A uniform scale changes the surface metric tracked by
//! the chart, so `scale_in_place` applies the magnitude of the factor. Because chart orientation is
//! arbitrary, a mirroring scale is not propagated into it. See `geom3::mesh::flat_domain` for the
//! queries built on this attribute.
//!
//! # Error message naming
//!
//! The typed fields report themselves as `point_normals`, `point_colors`, `point_stdev`, and
//! `point_flat` in error messages rather than by their bare field names. The mesh types hold this
//! set alongside a `FaceAttrSet3`, so naming the domain disambiguates the two. The added context is
//! also useful to callers working with point clouds.

use super::{
    Attr3, check_both_or_neither, check_keys_match, check_len, check_reserved, check_same_variant,
    clone_indexed, clone_masked, extend_option,
};
use crate::common::IndexMask;
use crate::{Iso3, Point2, Result, UnitVec3};
use std::collections::HashMap;

/// The set of per-point attributes attached to a container, holding both the first-class typed
/// attributes and an open, name-keyed map of everything else.
///
/// This type does not know the point count of the container it belongs to and so it can't enforce
/// that its arrays are the right length. Unfortunately that means that validation has to be the job
/// of the owner, which does know the count. To ease the pain somewhat there is a `validate(n)`
/// method, and the setters take the count as an argument.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PointAttrSet3 {
    normals: Option<Vec<UnitVec3>>,
    colors: Option<Vec<[u8; 3]>>,
    stdev: Option<Vec<f64>>,
    flat: Option<Vec<Point2>>,
    open: HashMap<String, Attr3>,
}

// ===============================================================================================
// Construction and access
// ===============================================================================================

impl PointAttrSet3 {
    /// Create an attribute set with no attributes of any kind.
    pub fn empty() -> Self {
        Self::default()
    }

    /// Returns true if no attributes of any kind are present.
    pub fn is_empty(&self) -> bool {
        self.normals.is_none()
            && self.colors.is_none()
            && self.stdev.is_none()
            && self.flat.is_none()
            && self.open.is_empty()
    }

    /// List the names of every per-point attribute which is present, typed fields included.
    ///
    /// This is what an operation which cannot supply values for a new point reports back, so the
    /// caller can see what is standing in the way.
    pub fn attr_labels(&self) -> Vec<&str> {
        let mut names = Vec::new();
        if self.normals.is_some() {
            names.push("point_normals");
        }
        if self.colors.is_some() {
            names.push("point_colors");
        }
        if self.stdev.is_some() {
            names.push("point_stdev");
        }
        if self.flat.is_some() {
            names.push("point_flat");
        }
        names.extend(self.open.keys().map(|k| k.as_str()));
        names
    }

    /// Get the per-point unit normals, if present.
    pub fn normals(&self) -> Option<&[UnitVec3]> {
        self.normals.as_deref()
    }

    /// Get the per-point RGB colors, if present.
    pub fn colors(&self) -> Option<&[[u8; 3]]> {
        self.colors.as_deref()
    }

    /// Get the per-point standard deviations, if present.
    ///
    /// These are 1-sigma values expressed in the container's own length units, representing the
    /// spread of positions that would be expected if the point were measured repeatedly. They scale
    /// with the geometry under a uniform scale.
    pub fn stdev(&self) -> Option<&[f64]> {
        self.stdev.as_deref()
    }

    /// Get the per-point flat coordinates, if present.
    ///
    /// These are the positions of the points in a flattened 2D chart of their associated surface,
    /// expressed in the container's own length units. They are not texture coordinates.
    pub fn flat(&self) -> Option<&[Point2]> {
        self.flat.as_deref()
    }

    /// Get the open-map attribute stored under the given name, if present.
    pub fn attr(&self, name: &str) -> Option<&Attr3> {
        self.open.get(name)
    }

    /// Iterate over the names of the open-map attributes, in no particular order.
    pub fn attr_names(&self) -> impl Iterator<Item = &str> {
        self.open.keys().map(|k| k.as_str())
    }
}

// ===============================================================================================
// Mutation
// ===============================================================================================

impl PointAttrSet3 {
    /// Set or clear the per-point unit normals.
    ///
    /// # Arguments
    ///
    /// * `values`: the normals to store, or `None` to clear them
    /// * `n_points`: the point count of the owning container, which `values` must match
    ///
    /// returns: `Result<()>`
    pub fn set_normals(&mut self, values: Option<Vec<UnitVec3>>, n_points: usize) -> Result<()> {
        check_len(
            values.as_deref().map(|v| v.len()),
            n_points,
            "point_normals",
        )?;
        self.normals = values;
        Ok(())
    }

    /// Set or clear the per-point RGB colors.
    ///
    /// # Arguments
    ///
    /// * `values`: the colors to store, or `None` to clear them
    /// * `n_points`: the point count of the owning container, which `values` must match
    ///
    /// returns: `Result<()>`
    pub fn set_colors(&mut self, values: Option<Vec<[u8; 3]>>, n_points: usize) -> Result<()> {
        check_len(values.as_deref().map(|v| v.len()), n_points, "point_colors")?;
        self.colors = values;
        Ok(())
    }

    /// Set or clear the per-point standard deviations, which must be 1-sigma values in the
    /// container's own length units. Negative values are rejected.
    ///
    /// # Arguments
    ///
    /// * `values`: the standard deviations to store, or `None` to clear them
    /// * `n_points`: the point count of the owning container, which `values` must match
    ///
    /// returns: `Result<()>`
    pub fn set_stdev(&mut self, values: Option<Vec<f64>>, n_points: usize) -> Result<()> {
        check_len(values.as_deref().map(|v| v.len()), n_points, "point_stdev")?;

        if let Some(v) = &values
            && let Some(i) = v.iter().position(|s| *s < 0.0 || s.is_nan())
        {
            return Err(format!(
                "point_stdev[{}] is {}, but a standard deviation must be finite and non-negative",
                i, v[i]
            )
            .into());
        }

        self.stdev = values;
        Ok(())
    }

    /// Set or clear the per-point flat coordinates: the position of each point in a flattened 2D
    /// chart of the surface, such as the output of boundary first flattening.
    ///
    /// # Arguments
    ///
    /// * `values`: the flat coordinates to store, or `None` to clear them
    /// * `n_points`: the point count of the owning container, which `values` must match
    ///
    /// returns: `Result<()>`
    pub fn set_flat(&mut self, values: Option<Vec<Point2>>, n_points: usize) -> Result<()> {
        check_len(values.as_deref().map(|v| v.len()), n_points, "point_flat")?;
        self.flat = values;
        Ok(())
    }

    /// Insert an open-map attribute under the given name, replacing any attribute already stored
    /// there.
    ///
    /// # Arguments
    ///
    /// * `name`: the key to store under, which must not be one of the reserved names
    /// * `attr`: the attribute array to store
    /// * `n_points`: the point count of the owning container, which `attr` must match
    ///
    /// returns: `Result<()>`
    pub fn insert_attr(&mut self, name: &str, attr: Attr3, n_points: usize) -> Result<()> {
        check_reserved(name)?;
        check_len(Some(attr.len()), n_points, name)?;
        self.open.insert(name.to_string(), attr);
        Ok(())
    }

    /// Remove and return the open-map attribute stored under the given name.
    pub fn remove_attr(&mut self, name: &str) -> Option<Attr3> {
        self.open.remove(name)
    }
}

// ===============================================================================================
// Validation, subsetting, and combination
// ===============================================================================================

impl PointAttrSet3 {
    /// Verify that every attribute array present has a length matching the point count.
    ///
    /// # Arguments
    ///
    /// * `n_points`: the point count of the owning container
    ///
    /// returns: `Result<()>`
    pub fn validate(&self, n_points: usize) -> Result<()> {
        check_len(
            self.normals.as_ref().map(|v| v.len()),
            n_points,
            "point_normals",
        )?;
        check_len(
            self.colors.as_ref().map(|v| v.len()),
            n_points,
            "point_colors",
        )?;
        check_len(
            self.stdev.as_ref().map(|v| v.len()),
            n_points,
            "point_stdev",
        )?;
        check_len(self.flat.as_ref().map(|v| v.len()), n_points, "point_flat")?;

        for (name, attr) in self.open.iter() {
            check_len(Some(attr.len()), n_points, name)?;
        }

        Ok(())
    }

    /// Create a new attribute set containing only the points selected by the given mask, preserving
    /// their original order.
    ///
    /// # Arguments
    ///
    /// * `mask`: selects which points survive, and must match the owning container's point count
    ///
    /// returns: `Result<PointAttrSet3>`
    pub fn subset(&self, mask: &IndexMask) -> Result<Self> {
        let mut open = HashMap::with_capacity(self.open.len());
        for (name, attr) in self.open.iter() {
            open.insert(name.clone(), attr.clone_indices_of(mask)?);
        }

        Ok(Self {
            normals: clone_masked(self.normals.as_deref(), mask)?,
            colors: clone_masked(self.colors.as_deref(), mask)?,
            stdev: clone_masked(self.stdev.as_deref(), mask)?,
            flat: clone_masked(self.flat.as_deref(), mask)?,
            open,
        })
    }

    /// Create a new attribute set containing the points at the given indices, in the order the
    /// indices are given. Indices may repeat.
    ///
    /// # Arguments
    ///
    /// * `indices`: the points to take, each of which must be less than the owning container's
    ///   point count
    ///
    /// returns: `Result<PointAttrSet3>`
    pub fn subset_indices(&self, indices: &[usize]) -> Result<Self> {
        let mut open = HashMap::with_capacity(self.open.len());
        for (name, attr) in self.open.iter() {
            open.insert(name.clone(), attr.clone_indices(indices)?);
        }

        Ok(Self {
            normals: clone_indexed(self.normals.as_deref(), indices)?,
            colors: clone_indexed(self.colors.as_deref(), indices)?,
            stdev: clone_indexed(self.stdev.as_deref(), indices)?,
            flat: clone_indexed(self.flat.as_deref(), indices)?,
            open,
        })
    }

    /// Append the contents of another attribute set onto the end of this one.
    ///
    /// Attributes are all-or-nothing: a typed field or an open-map key which is present on one side
    /// and absent on the other is an error, because there is no correct value to pad the missing
    /// side with. The check runs over the whole set before anything is modified, so a failure
    /// leaves this attribute set untouched.
    ///
    /// # Arguments
    ///
    /// * `other`: the attribute set to append
    ///
    /// returns: `Result<()>`
    pub fn extend_from(&mut self, other: &Self) -> Result<()> {
        self.check_extend_from(other)?;
        self.apply_extend_from(other)
    }

    /// Run every check an append has to pass, without modifying anything.
    ///
    /// This is separate from the append itself so that a mesh can check both attribute domains
    /// before modifying either one. Otherwise, discovering a face-domain mismatch after extending
    /// the point domain would leave the mesh only partially appended.
    pub(crate) fn check_extend_from(&self, other: &Self) -> Result<()> {
        check_both_or_neither(
            self.normals.is_some(),
            other.normals.is_some(),
            "point_normals",
        )?;
        check_both_or_neither(
            self.colors.is_some(),
            other.colors.is_some(),
            "point_colors",
        )?;
        check_both_or_neither(self.stdev.is_some(), other.stdev.is_some(), "point_stdev")?;
        check_both_or_neither(self.flat.is_some(), other.flat.is_some(), "point_flat")?;

        check_keys_match(&self.open, &other.open, "point")?;

        // Variant mismatches between two attributes of the same name would fail partway through the
        // append, so they are checked up front as well.
        for (name, attr) in self.open.iter() {
            check_same_variant(attr, &other.open[name], name)?;
        }

        Ok(())
    }

    /// Perform the append. Only valid after `check_extend_from` has succeeded for the same pair.
    pub(crate) fn apply_extend_from(&mut self, other: &Self) -> Result<()> {
        extend_option(&mut self.normals, other.normals.as_deref());
        extend_option(&mut self.colors, other.colors.as_deref());
        extend_option(&mut self.stdev, other.stdev.as_deref());
        extend_option(&mut self.flat, other.flat.as_deref());

        for (name, attr) in self.open.iter_mut() {
            attr.extend_from(&other.open[name])?;
        }

        Ok(())
    }
}

// ===============================================================================================
// Geometric operations
// ===============================================================================================

impl PointAttrSet3 {
    /// Transform the spatial attributes in place by the given isometry.
    ///
    /// This rotates the normals and every `Attr3::Vector` attribute. Because all of these hold
    /// directions rather than positions, only the rotation component of the isometry has any
    /// effect. The flat coordinates remain unchanged because rigidly moving a surface does not
    /// change its chart.
    ///
    /// # Arguments
    ///
    /// * `iso`: the isometry to apply
    pub fn transform_in_place(&mut self, iso: &Iso3) {
        if let Some(normals) = &mut self.normals {
            for n in normals.iter_mut() {
                *n = iso * *n;
            }
        }

        for attr in self.open.values_mut() {
            attr.transform_in_place(iso);
        }
    }

    /// Scale the length-dimensioned attributes in place by the given uniform scale factor.
    ///
    /// `stdev` and `flat` are affected, both by the absolute value of the factor. A standard
    /// deviation is a magnitude and must remain non-negative even under a mirroring scale. Flat
    /// coordinates track the surface metric, so a change of units applies to them as well. However,
    /// chart orientation is arbitrary, so mirroring the surface is not propagated to the chart.
    /// Nothing else is changed: normals are directions and are unaffected by a uniform scale, and
    /// the container cannot know whether an open-map scalar carries length units.
    ///
    /// # Arguments
    ///
    /// * `scale`: the uniform scale factor which was applied to the points
    pub fn scale_in_place(&mut self, scale: f64) {
        let k = scale.abs();
        if let Some(stdev) = &mut self.stdev {
            for s in stdev.iter_mut() {
                *s *= k;
            }
        }
        if let Some(flat) = &mut self.flat {
            for f in flat.iter_mut() {
                *f = Point2::from(f.coords * k);
            }
        }
    }

    /// Flip the orientation-dependent attributes in place, to accompany a reversal of the surface
    /// the points belong to. Only the normals are negated.
    pub fn flip_in_place(&mut self) {
        if let Some(normals) = &mut self.normals {
            for n in normals.iter_mut() {
                *n = -*n;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Vector3;
    use crate::geom3::attributes3::RESERVED_ATTR_NAMES;
    use approx::assert_relative_eq;
    use std::f64::consts::FRAC_PI_2;

    const N: usize = 4;

    /// An attribute set carrying every typed field and one open attribute.
    fn full_attrs() -> PointAttrSet3 {
        let mut attrs = PointAttrSet3::empty();

        attrs
            .set_normals(
                Some(vec![
                    UnitVec3::new_normalize(Vector3::new(1.0, 0.0, 0.0)),
                    UnitVec3::new_normalize(Vector3::new(0.0, 1.0, 0.0)),
                    UnitVec3::new_normalize(Vector3::new(0.0, 0.0, 1.0)),
                    UnitVec3::new_normalize(Vector3::new(1.0, 1.0, 1.0)),
                ]),
                N,
            )
            .unwrap();

        attrs
            .set_colors(Some(vec![[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]), N)
            .unwrap();

        attrs.set_stdev(Some(vec![0.1, 0.2, 0.3, 0.4]), N).unwrap();

        attrs
            .set_flat(
                Some(vec![
                    Point2::new(0.0, 0.0),
                    Point2::new(1.0, 0.0),
                    Point2::new(1.0, 1.0),
                    Point2::new(0.0, 1.0),
                ]),
                N,
            )
            .unwrap();

        attrs
            .insert_attr("confidence", Attr3::Scalar(vec![0.5, 0.6, 0.7, 0.8]), N)
            .unwrap();

        attrs
    }

    #[test]
    fn empty_set_reports_empty() {
        let attrs = PointAttrSet3::empty();
        assert!(attrs.is_empty());
        assert!(attrs.normals().is_none());
        assert!(attrs.colors().is_none());
        assert!(attrs.stdev().is_none());
        assert!(attrs.flat().is_none());
        assert_eq!(attrs.attr_names().count(), 0);

        assert!(!full_attrs().is_empty());
    }

    #[test]
    fn attr_labels_names_every_present_attribute() {
        let attrs = full_attrs();
        let labels = attrs.attr_labels();

        for expected in [
            "point_normals",
            "point_colors",
            "point_stdev",
            "point_flat",
            "confidence",
        ] {
            assert!(
                labels.contains(&expected),
                "missing '{expected}' in {labels:?}"
            );
        }

        assert!(PointAttrSet3::empty().attr_labels().is_empty());
    }

    #[test]
    fn setters_reject_a_length_mismatch() {
        let mut attrs = PointAttrSet3::empty();

        assert!(attrs.set_colors(Some(vec![[0, 0, 0]]), N).is_err());
        assert!(attrs.set_normals(Some(Vec::new()), N).is_err());
        assert!(attrs.insert_attr("q", Attr3::Scalar(vec![1.0]), N).is_err());

        // A rejected set must not have stored anything.
        assert!(attrs.is_empty());
    }

    #[test]
    fn setters_accept_none_regardless_of_count() -> Result<()> {
        let mut attrs = full_attrs();
        attrs.set_colors(None, N)?;
        assert!(attrs.colors().is_none());
        Ok(())
    }

    #[test]
    fn stdev_rejects_negative_and_nan() {
        let mut attrs = PointAttrSet3::empty();

        assert!(attrs.set_stdev(Some(vec![0.1, -0.2, 0.3, 0.4]), N).is_err());
        assert!(
            attrs
                .set_stdev(Some(vec![0.1, f64::NAN, 0.3, 0.4]), N)
                .is_err()
        );
        assert!(attrs.set_stdev(Some(vec![0.0, 0.2, 0.3, 0.4]), N).is_ok());
    }

    #[test]
    fn open_map_rejects_reserved_names() {
        let mut attrs = PointAttrSet3::empty();

        for name in RESERVED_ATTR_NAMES {
            assert!(
                attrs
                    .insert_attr(name, Attr3::Scalar(vec![0.0; N]), N)
                    .is_err(),
                "expected '{name}' to be rejected as an attribute name"
            );
        }

        // A name which merely contains a reserved word is fine.
        assert!(
            attrs
                .insert_attr("scanner_color_temp", Attr3::Scalar(vec![0.0; N]), N)
                .is_ok()
        );
    }

    #[test]
    fn remove_attr_returns_what_was_stored() {
        let mut attrs = full_attrs();

        let taken = attrs.remove_attr("confidence").unwrap();
        assert_eq!(taken.as_scalar().unwrap(), &[0.5, 0.6, 0.7, 0.8]);
        assert!(attrs.attr("confidence").is_none());
        assert!(attrs.remove_attr("confidence").is_none());
    }

    #[test]
    fn validate_catches_a_mismatch() -> Result<()> {
        let attrs = full_attrs();
        attrs.validate(N)?;

        assert!(attrs.validate(N + 1).is_err());
        assert!(attrs.validate(0).is_err());

        // An empty set validates against any count.
        PointAttrSet3::empty().validate(0)?;
        PointAttrSet3::empty().validate(9999)?;

        Ok(())
    }

    #[test]
    fn subset_selects_the_masked_points() -> Result<()> {
        let attrs = full_attrs();
        let mask = IndexMask::try_from_indices(&[1, 3], N)?;

        let sub = attrs.subset(&mask)?;
        sub.validate(2)?;

        assert_eq!(sub.colors().unwrap(), &[[1, 1, 1], [3, 3, 3]]);
        assert_eq!(sub.stdev().unwrap(), &[0.2, 0.4]);
        assert_eq!(
            sub.flat().unwrap(),
            &[Point2::new(1.0, 0.0), Point2::new(0.0, 1.0)]
        );
        assert_eq!(
            sub.attr("confidence").unwrap().as_scalar().unwrap(),
            &[0.6, 0.8]
        );

        Ok(())
    }

    #[test]
    fn extend_from_unions_matching_sets() -> Result<()> {
        let mut attrs = full_attrs();
        attrs.extend_from(&full_attrs())?;

        attrs.validate(N * 2)?;
        assert_eq!(attrs.stdev().unwrap().len(), N * 2);
        assert_eq!(attrs.attr("confidence").unwrap().len(), N * 2);

        Ok(())
    }

    #[test]
    fn extend_from_rejects_a_typed_field_on_only_one_side() {
        let mut attrs = full_attrs();
        let mut other = full_attrs();
        other.set_stdev(None, N).unwrap();

        assert!(attrs.extend_from(&other).is_err());

        // The rejected append must have left the target untouched.
        assert_eq!(attrs, full_attrs());
    }

    #[test]
    fn extend_from_rejects_an_open_key_on_only_one_side() {
        let mut attrs = full_attrs();
        let mut other = full_attrs();
        other.remove_attr("confidence");

        assert!(attrs.extend_from(&other).is_err());
        assert_eq!(attrs, full_attrs());

        // And the reverse direction, where the other side has the extra key.
        let mut attrs = full_attrs();
        attrs.remove_attr("confidence");
        assert!(attrs.extend_from(&full_attrs()).is_err());
    }

    #[test]
    fn extend_from_rejects_a_variant_mismatch_under_the_same_name() {
        let mut attrs = full_attrs();
        let mut other = full_attrs();
        other.remove_attr("confidence");
        other
            .insert_attr("confidence", Attr3::Label(vec![1, 2, 3, 4]), N)
            .unwrap();

        assert!(attrs.extend_from(&other).is_err());
        assert_eq!(attrs, full_attrs());
    }

    #[test]
    fn transform_rotates_normals_and_vector_attrs() -> Result<()> {
        let mut attrs = full_attrs();
        attrs.insert_attr(
            "principal_dir",
            Attr3::Vector(vec![Vector3::new(1.0, 0.0, 0.0); N]),
            N,
        )?;

        // A quarter turn about +z with a translation, which maps +x onto +y.
        let iso = Iso3::new(Vector3::new(5.0, 6.0, 7.0), Vector3::z() * FRAC_PI_2);
        attrs.transform_in_place(&iso);

        assert_relative_eq!(
            attrs.normals().unwrap()[0].into_inner(),
            Vector3::new(0.0, 1.0, 0.0),
            epsilon = 1.0e-12
        );
        assert_relative_eq!(
            attrs.attr("principal_dir").unwrap().as_vector().unwrap()[0],
            Vector3::new(0.0, 1.0, 0.0),
            epsilon = 1.0e-12
        );

        // Scalars and the flat coordinates are untouched by a transform.
        assert_eq!(attrs.stdev().unwrap(), &[0.1, 0.2, 0.3, 0.4]);
        assert_eq!(attrs.flat(), full_attrs().flat());
        assert_eq!(
            attrs.attr("confidence").unwrap().as_scalar().unwrap(),
            &[0.5, 0.6, 0.7, 0.8]
        );

        Ok(())
    }

    #[test]
    fn scale_affects_the_standard_deviations_and_flat_coordinates() {
        let mut attrs = full_attrs();
        attrs.scale_in_place(25.4);

        for (actual, expected) in attrs
            .flat()
            .unwrap()
            .iter()
            .zip(full_attrs().flat().unwrap().iter())
        {
            assert_relative_eq!(actual.coords, expected.coords * 25.4, epsilon = 1.0e-12);
        }

        for (actual, expected) in attrs
            .stdev()
            .unwrap()
            .iter()
            .zip([0.1, 0.2, 0.3, 0.4].iter())
        {
            assert_relative_eq!(*actual, expected * 25.4, epsilon = 1.0e-12);
        }

        // An open-map scalar has no declared units, so it must not be scaled.
        assert_eq!(
            attrs.attr("confidence").unwrap().as_scalar().unwrap(),
            &[0.5, 0.6, 0.7, 0.8]
        );
    }

    #[test]
    fn scale_keeps_standard_deviations_positive_under_mirroring() {
        let mut attrs = full_attrs();
        attrs.scale_in_place(-2.0);

        for s in attrs.stdev().unwrap() {
            assert!(*s >= 0.0, "a standard deviation must not go negative");
        }
        assert_relative_eq!(attrs.stdev().unwrap()[1], 0.4, epsilon = 1.0e-12);

        // The chart is scaled by the magnitude but not mirrored.
        assert_relative_eq!(
            attrs.flat().unwrap()[1].coords,
            Point2::new(2.0, 0.0).coords,
            epsilon = 1.0e-12
        );
    }

    #[test]
    fn flip_negates_the_normals() {
        let original = full_attrs();
        let mut attrs = full_attrs();
        attrs.flip_in_place();

        for (flipped, source) in attrs
            .normals()
            .unwrap()
            .iter()
            .zip(original.normals().unwrap().iter())
        {
            assert_relative_eq!(
                flipped.into_inner(),
                -source.into_inner(),
                epsilon = 1.0e-12
            );
        }

        // Nothing else changes.
        assert_eq!(attrs.colors(), original.colors());
        assert_eq!(attrs.stdev(), original.stdev());
        assert_eq!(attrs.flat(), original.flat());
    }
}