prettypretty 0.12.0

Applying 2020s color science to 1970s terminal user interfaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
//! Optional module implementing the traversal of the human visual gamut.
//!
#![cfg_attr(
    feature = "pyffi",
    doc = "This module reflects a somewhat unsatisfactory compromise between what's
        possible in Rust and what's necessary for PyO3. In particular, PyO3 requires
        monomorphic enums/structs with monomorphic method implementations and does not
        support generic anything. The PyO3 guide justifies this restriction with the
        fact that the Rust compiler produces monomorphic code only. While correct, PyO3
        complicates matters significantly by not supporting trait methods, its
        `#[pymethods]` macro disallowing item-level macros, and its error checking
        ignoring `#[cfg]` attributes. The impact is noticeable: Whereas Rust code
        might get by with four different implementations of [`SpectralDistribution`]'s
        methods, Python integration necessitates another three."
)]
//!
//! The [`SpectralDistribution`] trait defines an interface for mapping a fixed,
//! nanometer-aligned range of wavelengths at 1nm resolution to values. With
//! wavelengths restricted to integral nanometers, the interfaces uses `usize`
//! for their representation. Meanwhile, values are represented by an associated
//! type, which is `Float` for illuminants and `[Float; 3]` for observers.
//!
//! This module includes the following implementations of the trait:
//!
//!   * [`Observer`] is a table-driven implementation of
//!     `SpectralDistribution<Value=[Float;3]>`.
//!   * [`TabularDistribution`] is a table-driven implementation of
//!     `SpectralDistribution<Value=Float>`.
//!   * [`FixedDistribution`] is an implementation of
//!     `SpectralDistribution<Value=Float>` with a fixed value.
#![cfg_attr(
    feature = "pyffi",
    doc = "  * [`Illuminant`] is an implementation of
        `SpectralDistribution<Value=Float>` that wraps a `Box<dyn
         SpectralDistribution<Value=Float> + Send + Sync>`."
)]
//!   * [`IlluminatedObserver`] is a table-driven implementation of
//!     `SpectralDistribution<Value=[Float;3]>`. Its data is the
//!     result of the per-wavelength multiplication of a
//!     `SpectralDistribution<Value=Float>` and a
//!     `SpectralDistribution<Value=[Float;3]>`, i.e., an illuminant
//!     and an observer.
//!
#![cfg_attr(
    feature = "pyffi",
    doc = "To play nice with PyO3 and Python, `Observer` and `IlluminatedObserver`
        reimplement all but one trait method in their `impl` blocks. `Illuminant`
        does the same, but is only defined if the `pyffi` feature is enabled. It
        makes two different trait implementations appear as the same type type in
        Python and allows instances to be passed back to Rust."
)]
//!
//! Using the above trait implementations, this module exports the following concrete
//! illuminants and observers, with data directly sourced from the CIE.
//!
//!   * [`CIE_ILLUMINANT_D50`] approximates daylight near sunrise and sunset.
//!   * [`CIE_ILLUMINANT_D65`] approximates daylight around noon.
//!   * [`CIE_ILLUMINANT_E`] has equal energy.
//!   * [`CIE_OBSERVER_2DEG_1931`] is the 1931 2º color matching function.
//!   * [`CIE_OBSERVER_10DEG_1964`] is the 1964 10º color matching function.
//!
//! A submodule provides [`std_observer::x()`], [`std_observer::y()`], and
//! [`std_observer::z()`] as analytical approximations for the 1931 2º observer.
//! As such, all three functions accept floating point arguments for
//! wavelengths.
//!
//! Finally, [`SpectrumTraversal`] is an iterator for tracing the spectral locus
//! or the human visual gamut. It is instantiated with
//! [`IlluminatedObserver::visual_gamut`].
#![cfg_attr(
    feature = "pyffi",
    doc = "In Python, the constructor accepts `&Illuminant` and `&Observer`
        arguments only, which makes it monomorphic. While that is insufficient
        for generally overcoming PyO3's prohibition against polymorphic anything,
        in this particular case it suffices because spectrum traversal's
        constructors do not retain their inputs and instead keep the result of
        premultiplying the two spectral distributions. In other words, the rest
        of [`SpectrumTraversal`]'s implementation is strictly monomophic itself."
)]
//!

extern crate alloc;
use alloc::sync::Arc;
use core::num::NonZeroUsize;

#[cfg(feature = "pyffi")]
use pyo3::prelude::*;

use crate::{
    core::{GamutTraversalStep, ThreeSum},
    Color, ColorSpace, Float,
};

/// A spectral distribution at nanometer resolution.
///
/// A concrete implementation of this trait must provide methods that return a
/// descriptive label, a start wavelength, a length, and the spectral
/// distribution's values.
///
/// This trait requires implementation of `start()` and `len()` instead of just
/// `range()` because the former two methods allow for more performant default
/// implementations.
pub trait SpectralDistribution {
    /// The spectral distribution's value type.
    type Value;

    /// Get a descriptive label for this spectral distribution.
    fn label(&self) -> String;

    /// Get the starting wavelength for this spectral distribution.
    fn start(&self) -> usize;

    /// Get the ending wavelength for this spectral distribution.
    #[inline]
    fn end(&self) -> usize {
        self.start() + self.len()
    }

    /// Get the range of this spectral distribution.
    #[inline]
    fn range(&self) -> core::ops::Range<usize> {
        self.start()..self.end()
    }

    /// Determine whether this distribution is empty.
    #[inline]
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get the length of this spectral distribution.
    fn len(&self) -> usize;

    /// Get this spectral distribution's value for the given wavelength.
    ///
    /// # Panics
    ///
    /// If the given index is outside this distribution's rang of wavelengths.
    fn at(&self, wavelength: usize) -> &Self::Value;

    /// Get this spectral distribution's value for the given wavelength.
    fn get(&self, wavelength: usize) -> Option<&Self::Value> {
        if self.range().contains(&wavelength) {
            Some(self.at(wavelength))
        } else {
            None
        }
    }

    /// Get the checksum for this spectral distribution.
    ///
    /// The checksum is the componentwise sum of all values contained in the
    /// distribution. It must not be computed on the fly.
    fn checksum(&self) -> Self::Value;
}

// --------------------------------------------------------------------------------------------------------------------

/// An illuminant at nanometer resolution. <i class=python-only>Python only!</i>
///
/// In addition to implementing the [`SpectralDistribution`] trait, this struct
/// reimplements the trait's methods (other than `range`, which returns a
/// standard library type that is not supported by PyO3) as well as `__len__`,
/// `__getitem__`, and `__repr__` as regular methods for better Python
/// integration. It forwards all invocations to a `dyn
/// SpectralDistribution<Value=Float>`.
#[cfg(feature = "pyffi")]
#[pyclass(frozen, module = "prettypretty.color.trans")]
pub struct Illuminant {
    distribution: Box<dyn SpectralDistribution<Value = Float> + Send + Sync>,
}

#[cfg(feature = "pyffi")]
impl Illuminant {
    /// Create a new illuminant.
    pub fn new(distribution: Box<dyn SpectralDistribution<Value = Float> + Send + Sync>) -> Self {
        Self { distribution }
    }
}

#[cfg(feature = "pyffi")]
#[pymethods]
impl Illuminant {
    /// Get a descriptive label for this spectral distribution.
    pub fn label(&self) -> String {
        self.distribution.label()
    }

    /// Get this spectral distribution's starting wavelength.
    pub fn start(&self) -> usize {
        self.distribution.start()
    }

    /// Get this spectral distribution's ending wavelength.
    pub fn end(&self) -> usize {
        self.distribution.end()
    }

    /// Determine whether this distribution is empty.
    pub fn is_empty(&self) -> bool {
        self.distribution.is_empty()
    }

    /// Determine the number of entries in this distribution.
    pub fn len(&self) -> usize {
        self.distribution.len()
    }

    /// Get this spectral distribution's value for the given wavelength.
    pub fn at(&self, wavelength: usize) -> &Float {
        self.distribution.at(wavelength)
    }

    /// Get this spectral distribution's checksum.
    pub fn checksum(&self) -> Float {
        self.distribution.checksum()
    }

    /// Get the number of entries.
    pub fn __len__(&self) -> usize {
        self.distribution.len()
    }

    /// Get the entry at the given index.
    pub fn __getitem__(&self, index: usize) -> PyResult<Float> {
        self.distribution.get(index).copied().ok_or_else(|| {
            pyo3::exceptions::PyIndexError::new_err(format!(
                "{} <= {} < {} doesn't hold for {}",
                self.distribution.start(),
                index,
                self.distribution.end(),
                self.distribution.label()
            ))
        })
    }

    /// Get a debug representation.
    pub fn __repr__(&self) -> String {
        format!("Illuminant({})", self.label())
    }
}

#[cfg(feature = "pyffi")]
impl SpectralDistribution for Illuminant {
    type Value = Float;

    fn label(&self) -> String {
        self.distribution.label()
    }

    fn start(&self) -> usize {
        self.distribution.start()
    }

    fn end(&self) -> usize {
        self.distribution.end()
    }

    fn range(&self) -> core::ops::Range<usize> {
        self.distribution.range()
    }

    fn is_empty(&self) -> bool {
        self.distribution.is_empty()
    }

    fn len(&self) -> usize {
        self.distribution.len()
    }

    fn at(&self, wavelength: usize) -> &Self::Value {
        self.distribution.at(wavelength)
    }

    fn checksum(&self) -> Self::Value {
        self.distribution.checksum()
    }
}

#[cfg(feature = "pyffi")]
impl core::ops::Index<usize> for Illuminant {
    type Output = <Self as SpectralDistribution>::Value;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        self.at(index)
    }
}

// --------------------------------------------------------------------------------------------------------------------

/// A table-driven spectral distribution over floating point values.
#[derive(Clone, Debug)]
pub struct TabularDistribution {
    label: &'static str,
    start: usize,
    checksum: Float,
    data: &'static [Float],
}

impl TabularDistribution {
    /// Create a new tabular distribution.
    pub const fn new(
        label: &'static str,
        start: usize,
        checksum: Float,
        data: &'static [Float],
    ) -> Self {
        Self {
            label,
            checksum,
            start,
            data,
        }
    }
}

impl SpectralDistribution for TabularDistribution {
    type Value = Float;

    fn label(&self) -> String {
        self.label.to_string()
    }

    fn start(&self) -> usize {
        self.start
    }

    fn len(&self) -> usize {
        self.data.len()
    }

    fn at(&self, wavelength: usize) -> &Self::Value {
        &self.data[wavelength.saturating_sub(self.start)]
    }

    fn checksum(&self) -> Self::Value {
        self.checksum
    }
}

impl core::ops::Index<usize> for TabularDistribution {
    type Output = <Self as SpectralDistribution>::Value;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        self.at(index)
    }
}

// --------------------------------------------------------------------------------------------------------------------

/// A spectral distribution with a fixed floating point value.
#[derive(Clone, Debug)]
pub struct FixedDistribution {
    label: &'static str,
    start: usize,
    len: usize,
    checksum: Float,
    value: Float,
}

impl FixedDistribution {
    /// Create a new spectral distribution with a fixed value.
    pub const fn new(
        label: &'static str,
        start: usize,
        len: usize,
        checksum: Float,
        value: Float,
    ) -> Self {
        Self {
            label,
            start,
            len,
            checksum,
            value,
        }
    }
}

impl SpectralDistribution for FixedDistribution {
    type Value = Float;

    fn label(&self) -> String {
        self.label.to_string()
    }

    fn start(&self) -> usize {
        self.start
    }

    fn len(&self) -> usize {
        self.len
    }

    fn at(&self, _wavelength: usize) -> &Self::Value {
        &self.value
    }

    fn checksum(&self) -> Self::Value {
        self.checksum
    }
}

impl core::ops::Index<usize> for FixedDistribution {
    type Output = <Self as SpectralDistribution>::Value;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        self.at(index)
    }
}

// --------------------------------------------------------------------------------------------------------------------

/// A standard observer at nanometer resolution.
///
/// The CIE's standard observers, or color matching functions, model human color
/// perception. Since humans are trichromatic, the per-wavelength values of
/// standard observers are triples of floating point numbers.
#[cfg_attr(
    feature = "pyffi",
    pyclass(frozen, module = "prettypretty.color.spectrum")
)]
#[derive(Clone, Debug)]
pub struct Observer {
    label: &'static str,
    start: usize,
    checksum: [Float; 3],
    data: &'static [[Float; 3]],
}

impl Observer {
    /// Create a new observer.
    pub const fn new(
        label: &'static str,
        start: usize,
        checksum: [Float; 3],
        data: &'static [[Float; 3]],
    ) -> Self {
        Self {
            label,
            start,
            checksum,
            data,
        }
    }
}

#[cfg_attr(feature = "pyffi", pymethods)]
impl Observer {
    /// Get a descriptive label for this observer.
    #[inline]
    pub fn label(&self) -> String {
        self.label.to_string()
    }

    /// Get this observer's starting wavelength.
    #[inline]
    pub fn start(&self) -> usize {
        self.start
    }

    /// Get this observer's ending wavelength.
    #[inline]
    pub fn end(&self) -> usize {
        self.start + self.data.len()
    }

    /// Determine whether this observer is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.len() == 0
    }

    /// Determine the number of entries for this observer.
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Get this observer's value for the given wavelength.
    #[inline]
    pub fn at(&self, wavelength: usize) -> &[Float; 3] {
        &self.data[wavelength.saturating_sub(self.start)]
    }

    /// Get this observer's checksum.
    #[inline]
    pub fn checksum(&self) -> [Float; 3] {
        self.checksum
    }

    /// Get the number of entries. <i class=python-only>Python only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __len__(&self) -> usize {
        self.data.len()
    }

    /// Get the entry at the given index. <i class=python-only>Python
    /// only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __getitem__(&self, index: usize) -> PyResult<[Float; 3]> {
        self.get(index).copied().ok_or_else(|| {
            pyo3::exceptions::PyIndexError::new_err(format!(
                "{} <= {} < {} doesn't hold for {}",
                self.start(),
                index,
                self.end(),
                self.label()
            ))
        })
    }

    /// Get a debug representation. <i class=python-only>Python only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __repr__(&self) -> String {
        format!("{:?}", self)
    }
}

impl SpectralDistribution for Observer {
    type Value = [Float; 3];

    fn label(&self) -> String {
        self.label.to_string()
    }

    fn start(&self) -> usize {
        self.start
    }

    fn len(&self) -> usize {
        self.data.len()
    }

    fn at(&self, wavelength: usize) -> &Self::Value {
        &self.data[wavelength.saturating_sub(self.start)]
    }

    fn checksum(&self) -> Self::Value {
        self.checksum
    }
}

impl core::ops::Index<usize> for Observer {
    type Output = <Self as SpectralDistribution>::Value;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        self.at(index)
    }
}

// --------------------------------------------------------------------------------------------------------------------

/// An illuminated observer at nanometer resolution.
///
/// An illuminated observer is a spectral distribution representing a choice of
/// illuminant and observer when computing tristimulus values. Its
/// per-wavelength values are computed by premultiplying the illuminant's and
/// observer's per-wavelength values. As a result, an illuminated observer, just
/// like an observer, has three floating point numbers as values.
///
/// When compared to [`SpectralDistribution`] and [`Observer`], this spectral
/// distribution provides additional functionality through the
/// [`IlluminatedObserver::minimum`], [`IlluminatedObserver::maximum`],
/// [`IlluminatedObserver::luminosity`], [`IlluminatedObserver::white_point`],
/// and [`IlluminatedObserver::visual_gamut`] methods.
///
/// ASTM standard E308 refers to the premultiplied values as *weighting
/// factors*.
#[cfg_attr(
    feature = "pyffi",
    pyclass(frozen, module = "prettypretty.color.spectrum")
)]
#[derive(Debug, Default)]
pub struct IlluminatedObserver {
    label: String,
    start: usize,
    minimum: [Float; 3],
    maximum: [Float; 3],
    checksum: [Float; 3],
    data: Arc<[[Float; 3]]>,
}

impl IlluminatedObserver {
    /// Create a new illuminated observer.
    #[allow(clippy::missing_panics_doc)]
    pub fn new<Illuminant, Observer>(illuminant: &Illuminant, observer: &Observer) -> Self
    where
        Illuminant: SpectralDistribution<Value = Float>,
        Observer: SpectralDistribution<Value = [Float; 3]>,
    {
        let start = illuminant.start().max(observer.start());
        let end = illuminant.end().min(observer.end());

        let mut data = Arc::<[[Float; 3]]>::new_uninit_slice(end - start);
        let values = Arc::get_mut(&mut data).expect("value was just created");

        let mut checksum = ThreeSum::new();
        let mut minimum = [Float::INFINITY; 3];
        let mut maximum = [Float::NEG_INFINITY; 3];

        for index in start..end {
            let [x, y, z] = *observer.at(index);
            let s = *illuminant.at(index) / 100.0;
            let value = [s * x, s * y, s * z];

            values[index - start].write(value);
            checksum += value;

            for c in 0..=2 {
                minimum[c] = minimum[c].min(value[c]);
                maximum[c] = maximum[c].max(value[c]);
            }
        }

        Self {
            label: format!("{} / {}", illuminant.label(), observer.label()),
            start,
            minimum,
            maximum,
            checksum: checksum.value(),
            // SAFETY: Above loop initializes all of data through the values alias
            data: unsafe { data.assume_init() },
        }
    }
}

#[cfg_attr(feature = "pyffi", pymethods)]
impl IlluminatedObserver {
    #[cfg(feature = "pyffi")]
    #[new]
    pub fn py_new(illuminant: &Illuminant, observer: &Observer) -> Self {
        Self::new(illuminant, observer)
    }

    /// Get a descriptive label for this illuminated observer.
    #[inline]
    pub fn label(&self) -> String {
        self.label.clone()
    }

    /// Get this illuminated observer's starting wavelength.
    #[inline]
    pub fn start(&self) -> usize {
        self.start
    }

    /// Get this illuminated observer's ending wavelength.
    #[inline]
    pub fn end(&self) -> usize {
        self.start + self.data.len()
    }

    /// Determine whether this illuminated observer is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.len() == 0
    }

    /// Determine the number of entries in this illuminated observer.
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Get the premultiplied triple for the given wavelength.
    pub fn at(&self, wavelength: usize) -> &[Float; 3] {
        &self.data[wavelength.saturating_sub(self.start)]
    }

    /// Get this illuminated observer's component-wise minimum.
    #[inline]
    pub fn minimum(&self) -> [Float; 3] {
        self.minimum
    }

    /// Get this illuminated observer's component-wise maximum.
    #[inline]
    pub fn maximum(&self) -> [Float; 3] {
        self.maximum
    }

    /// Get this illuminated observer's checksum.
    #[inline]
    pub fn checksum(&self) -> [Float; 3] {
        self.checksum
    }

    /// Get this illuminated observer's luminosity.
    ///
    /// The luminosity is the sum of all values for the second component.
    #[inline]
    pub fn luminosity(&self) -> Float {
        self.checksum[1]
    }

    /// Determine the white point for this illuminated observer.
    pub fn white_point(&self) -> Color {
        let [x, y, z] = self.checksum;
        // y/y to handle corner case of y being 0.0
        #[allow(clippy::eq_op)]
        Color::new(ColorSpace::Xyz, [x / y, y / y, z / y])
    }

    /// Create a new spectrum traversal with the given stride.
    ///
    /// This method returns an iterator tracing the limits of the human visual
    /// gamut in the CIE's XYZ color space, as parameterized by this illuminated
    /// observer's component distributions. The returned iterator implements the
    /// standard algorithm, shifting and rotating square pulses of unit height
    /// and increasing widths across this distribution's spectrum.
    pub fn visual_gamut(&self, stride: NonZeroUsize) -> SpectrumTraversal {
        SpectrumTraversal::new(stride, self.luminosity(), self.data.clone())
    }

    /// Get this illuminated observer's number of values. <i
    /// class=python-only>Python only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __len__(&self) -> usize {
        self.data.len()
    }

    /// Get the entry at the given zero-based index, not wavelength. <i
    /// class=python-only>Python only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __getitem__(&self, index: usize) -> PyResult<[Float; 3]> {
        self.get(index).copied().ok_or_else(|| {
            pyo3::exceptions::PyIndexError::new_err(format!(
                "{} <= {} < {} doesn't hold for {}",
                self.start(),
                index,
                self.end(),
                self.label()
            ))
        })
    }

    /// Get a debug representation for this illuminated observer. <i
    /// class=python-only>Python only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __repr__(&self) -> String {
        format!("{:?}", self)
    }
}

impl SpectralDistribution for IlluminatedObserver {
    type Value = [Float; 3];

    fn label(&self) -> String {
        self.label.clone()
    }

    fn start(&self) -> usize {
        self.start
    }

    fn len(&self) -> usize {
        self.data.len()
    }

    fn at(&self, wavelength: usize) -> &Self::Value {
        &self.data[wavelength.saturating_sub(self.start)]
    }

    fn checksum(&self) -> Self::Value {
        self.checksum
    }
}

impl core::ops::Index<usize> for IlluminatedObserver {
    type Output = <Self as SpectralDistribution>::Value;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        self.at(index)
    }
}

// --------------------------------------------------------------------------------------------------------------------

pub mod std_observer {
    //! Free-standing functions related to the CIE standard observer.

    #[cfg(feature = "pyffi")]
    use pyo3::prelude::pyfunction;

    use crate::Float;

    /// Compute an [analytical
    /// approximation](https://research.nvidia.com/publication/2013-07_simple-analytic-approximations-cie-xyz-color-matching-functions)
    /// for the 1931 2º standard observer's x.
    #[cfg_attr(feature = "pyffi", pyfunction)]
    pub fn x(wavelength: Float) -> Float {
        let p1 = (wavelength - 442.0) * (if wavelength < 442.0 { 0.0624 } else { 0.0374 });
        let p2 = (wavelength - 599.8) * (if wavelength < 599.8 { 0.0264 } else { 0.0323 });
        let p3 = (wavelength - 501.1) * (if wavelength < 501.1 { 0.0490 } else { 0.0382 });

        const C0_362: Float = 0.362;
        const C1_056: Float = 1.056;

        C0_362.mul_add(
            (-0.5 * p1 * p1).exp(),
            C1_056.mul_add((-0.5 * p2 * p2).exp(), -0.065 * (-0.5 * p3 * p3).exp()),
        )
    }

    /// Compute an [analytical
    /// approximation](https://research.nvidia.com/publication/2013-07_simple-analytic-approximations-cie-xyz-color-matching-functions)
    /// for the 1931 2º standard observer's y.
    #[cfg_attr(feature = "pyffi", pyfunction)]
    pub fn y(wavelength: Float) -> Float {
        let p1 = (wavelength - 568.8) * (if wavelength < 568.8 { 0.0213 } else { 0.0247 });
        let p2 = (wavelength - 530.9) * (if wavelength < 530.9 { 0.0613 } else { 0.0322 });

        const C0_821: Float = 0.821;
        C0_821.mul_add((-0.5 * p1 * p1).exp(), 0.286 * (-0.5 * p2 * p2).exp())
    }

    /// Compute an [analytical
    /// approximation](https://research.nvidia.com/publication/2013-07_simple-analytic-approximations-cie-xyz-color-matching-functions)
    /// for the 1931 2º standard observer's z.
    #[cfg_attr(feature = "pyffi", pyfunction)]
    pub fn z(wavelength: Float) -> Float {
        let p1 = (wavelength - 437.0) * (if wavelength < 437.0 { 0.0845 } else { 0.0278 });
        let p2 = (wavelength - 459.0) * (if wavelength < 459.0 { 0.0385 } else { 0.0725 });

        const C1_217: Float = 1.217;
        C1_217.mul_add((-0.5 * p1 * p1).exp(), 0.681 * (-0.5 * p2 * p2).exp())
    }
}

// --------------------------------------------------------------------------------------------------------------------

/// A convenient constant for 1nm.
pub const ONE_NANOMETER: NonZeroUsize = NonZeroUsize::new(1).expect("one is non-zero");

/// An iterator tracing the visual gamut.
///
/// This iterator traces the boundaries of the human visual gamut assuming a
/// specific illuminant and observer by determining the colors resulting from
/// [square wave pulses](https://horizon-lab.org/colorvis/gamutvis.html) of
/// [increasing widths](https://www.russellcottrell.com/photo/visualGamut.htm)
/// shifted and rotated across the illuminant's and observer's shared spectrum.
/// Colors resulting from a pulse with the same width form a line.
///
/// Pulse positions and widths grow with the same stride. The first pulse
/// position is 0, whereas the first pulse width is 1nm. As a result, the first
/// line yielded by this iterator is the spectral locus; it is best rendered
/// with a stride of 1nm.
#[cfg_attr(feature = "pyffi", pyclass(module = "prettypretty.color.spectrum"))]
#[derive(Debug)]
pub struct SpectrumTraversal {
    data: Arc<[[Float; 3]]>,
    luminosity: Float,
    stride: usize,
    position: usize,
    width: usize,
    remaining: usize,
}

impl SpectrumTraversal {
    /// Create a new spectral traversal.
    ///
    /// The given data must be the result of premultiplying an illuminant with
    /// an observer, e.g., an illuminated observer.
    fn new(stride: NonZeroUsize, luminosity: Float, data: Arc<[[Float; 3]]>) -> Self {
        let stride = stride.get();
        let remaining = Self::derive_total_count(data.len(), stride);

        Self {
            data,
            luminosity,
            stride,
            position: 0,
            width: 0,
            remaining,
        }
    }

    fn derive_total_count(len: usize, stride: usize) -> usize {
        Self::derive_line_count(len, stride) * Self::derive_line_length(len, stride)
    }

    #[inline]
    fn derive_line_count(len: usize, stride: usize) -> usize {
        let mut count = (len - 1) / stride;
        if (len - 1) % stride > 0 {
            count += 1;
        }

        count
    }

    #[inline]
    fn derive_line_length(len: usize, stride: usize) -> usize {
        1 + (len - 1) / stride
    }
}

#[cfg_attr(feature = "pyffi", pymethods)]
impl SpectrumTraversal {
    /// Get the traversal's stride.
    #[inline]
    pub fn stride(&self) -> usize {
        self.stride
    }

    /// Get the total number of lines yielded by this spectrum traversal.
    #[inline]
    pub fn line_count(&self) -> usize {
        Self::derive_line_count(self.data.len(), self.stride)
    }

    /// Get the total number of colors per line yielded by this spectrum traversal.
    #[inline]
    pub fn line_length(&self) -> usize {
        Self::derive_line_length(self.data.len(), self.stride)
    }

    /// Compute the triple for a square, unit-height pulse.
    ///
    /// This method computes the sum of the underlying illuminated observer's
    /// values from the given start zero-based index (not wavelength) and width.
    /// Effective index values greater or equal to the underling illuminated
    /// observer's data table transparently wrap to the beginning of the table.
    pub fn pulse(&self, start: usize, width: usize) -> [Float; 3] {
        let mut sum = ThreeSum::new();
        for index in start..start + width {
            let index = index % self.data.len();
            sum += self.data[index];
        }
        sum.value()
    }

    /// Compute the XYZ color for a square, unit-height pulse.
    ///
    /// This method normalizes the result of [`SpectrumTraversal::pulse`] by
    /// dividing it with the illuminated observer's luminosity before wrapping
    /// it as a high-resolution color in the XYZ color space.
    pub fn pulse_color(&self, start: usize, width: usize) -> Color {
        let [x, y, z] = self.pulse(start, width);

        Color::new(
            ColorSpace::Xyz,
            [
                x / self.luminosity,
                y / self.luminosity,
                z / self.luminosity,
            ],
        )
    }

    /// Get the number of remaining steps. <i class=python-only>Python only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __len__(&self) -> usize {
        self.len()
    }

    /// Get this iterator. <i class=python-only>Python only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
        slf
    }

    /// Get the next step. <i class=python-only>Python only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __next__(mut slf: PyRefMut<'_, Self>) -> Option<GamutTraversalStep> {
        slf.next()
    }

    /// Get a debug representation. <i class=python-only>Python only!</i>
    #[cfg(feature = "pyffi")]
    pub fn __repr__(&self) -> String {
        format!(
            "SpectrumTraversal(stride={}, position={}, width={}, remaining={}, samples={})",
            self.stride,
            self.position,
            self.width,
            self.remaining,
            self.data.len(),
        )
    }
}

impl Iterator for SpectrumTraversal {
    type Item = GamutTraversalStep;

    fn next(&mut self) -> Option<Self::Item> {
        if self.data.len() <= self.width {
            return None;
        } else if self.width == 0 {
            self.width = 1;
        }

        self.remaining -= 1;
        let color = self.pulse_color(self.position, self.width);

        let result = if self.position == 0 {
            GamutTraversalStep::MoveTo(color)
        } else {
            GamutTraversalStep::LineTo(color)
        };

        self.position += self.stride;

        if self.data.len() <= self.position {
            self.width += self.stride;
            self.position = 0;
        }

        Some(result)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl ExactSizeIterator for SpectrumTraversal {
    fn len(&self) -> usize {
        self.remaining
    }
}

impl core::iter::FusedIterator for SpectrumTraversal {}

// --------------------------------------------------------------------------------------------------------------------

pub use crate::cie::CIE_ILLUMINANT_D50;
pub use crate::cie::CIE_ILLUMINANT_D65;
pub use crate::cie::CIE_OBSERVER_10DEG_1964;
pub use crate::cie::CIE_OBSERVER_2DEG_1931;

/// The CIE standard illuminant E at 1nm resolution.
pub static CIE_ILLUMINANT_E: FixedDistribution =
    FixedDistribution::new("Illuminant E", 300, 531, 53_100.0, 100.0);

// --------------------------------------------------------------------------------------------------------------------

#[cfg(test)]
mod test {
    use super::*;
    use crate::core::Sum;
    use std::num::NonZeroUsize;

    #[test]
    fn test_checksum() {
        for illuminant in [&CIE_ILLUMINANT_D50, &CIE_ILLUMINANT_D65] {
            let mut sum = Sum::new();

            for wavelength in illuminant.range() {
                sum += *illuminant.at(wavelength);
            }

            assert_eq!(sum.value(), illuminant.checksum());
        }

        for observer in [&CIE_OBSERVER_2DEG_1931, &CIE_OBSERVER_10DEG_1964] {
            let mut x_sum = Sum::new();
            let mut y_sum = Sum::new();
            let mut z_sum = Sum::new();

            for wavelength in observer.range() {
                let [x, y, z] = *observer.at(wavelength);
                x_sum += x;
                y_sum += y;
                z_sum += z;
            }

            assert_eq!(
                [x_sum.value(), y_sum.value(), z_sum.value()],
                observer.checksum()
            );
        }
    }

    #[test]
    fn test_spectrum_traversal() {
        for (stride, line_count, line_length) in [(9, 53, 53), (10, 47, 48)] {
            let total = line_count * line_length;

            let mut traversal =
                IlluminatedObserver::new(&CIE_ILLUMINANT_D65, &CIE_OBSERVER_2DEG_1931)
                    .visual_gamut(NonZeroUsize::new(stride).unwrap());

            assert_eq!(traversal.line_count(), line_count);
            assert_eq!(traversal.line_length(), line_length);
            assert_eq!(traversal.len(), total);

            for index in 0..(line_count * line_length) {
                let step = traversal.next();

                assert_eq!(traversal.len(), total - index - 1);
                if index % line_length == 0 {
                    assert!(matches!(step, Some(GamutTraversalStep::MoveTo(_))));
                } else {
                    assert!(matches!(step, Some(GamutTraversalStep::LineTo(_))));
                }
            }

            assert!(matches!(traversal.next(), None));
        }
    }
}