ruviz 0.7.0

High-performance 2D plotting library for Rust
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
//! Axis scale transformations
//!
//! Provides linear and logarithmic scale transformations for axis mapping.

/// Scale transformation trait
pub trait Scale {
    /// Transform a value from data space to normalized [0, 1] space
    fn transform(&self, value: f64) -> f64;

    /// Inverse transform from normalized space back to data space
    fn inverse(&self, normalized: f64) -> f64;

    /// Get the data range
    fn range(&self) -> (f64, f64);
}

/// Linear scale transformation
#[derive(Debug, Clone)]
pub struct LinearScale {
    min: f64,
    max: f64,
}

impl LinearScale {
    /// Create a new linear scale with the given range
    pub fn new(min: f64, max: f64) -> Self {
        Self { min, max }
    }
}

impl Scale for LinearScale {
    fn transform(&self, value: f64) -> f64 {
        if (self.max - self.min).abs() < f64::EPSILON {
            return 0.5;
        }
        (value - self.min) / (self.max - self.min)
    }

    fn inverse(&self, normalized: f64) -> f64 {
        normalized * (self.max - self.min) + self.min
    }

    fn range(&self) -> (f64, f64) {
        (self.min, self.max)
    }
}

/// Logarithmic scale transformation (base 10)
#[derive(Debug, Clone)]
pub struct LogScale {
    min: f64,
    max: f64,
    log_min: f64,
    log_max: f64,
}

impl LogScale {
    /// Create a new log scale with the given range
    ///
    /// # Panics
    /// Panics if min <= 0 or max <= 0
    pub fn new(min: f64, max: f64) -> Self {
        assert!(min > 0.0, "Log scale requires positive values");
        assert!(max > 0.0, "Log scale requires positive values");
        Self {
            min,
            max,
            log_min: min.log10(),
            log_max: max.log10(),
        }
    }
}

impl Scale for LogScale {
    /// Returns `NaN` for values a log axis cannot represent (zero, negative, or
    /// non-finite), matching [`AxisScale::normalized_position`].
    fn transform(&self, value: f64) -> f64 {
        if !AxisScale::Log.is_valid_value(value) {
            return f64::NAN;
        }
        let log_range = self.log_max - self.log_min;
        if log_range.abs() < f64::EPSILON {
            return 0.5;
        }
        (value.log10() - self.log_min) / log_range
    }

    fn inverse(&self, normalized: f64) -> f64 {
        let log_value = normalized * (self.log_max - self.log_min) + self.log_min;
        10.0_f64.powf(log_value)
    }

    fn range(&self) -> (f64, f64) {
        (self.min, self.max)
    }
}

/// Symmetric logarithmic scale transformation
///
/// This scale is linear around zero (within ±linthresh) and logarithmic outside.
/// Useful for data that spans positive and negative values or includes zero.
#[derive(Debug, Clone)]
pub struct SymLogScale {
    min: f64,
    max: f64,
    /// Linear threshold: values between -linthresh and +linthresh are scaled linearly
    linthresh: f64,
    /// Precomputed log of linthresh for efficiency
    log_linthresh: f64,
}

impl SymLogScale {
    /// Create a new symmetric log scale with the given range and linear threshold
    ///
    /// # Arguments
    /// * `min` - Minimum data value
    /// * `max` - Maximum data value
    /// * `linthresh` - Linear threshold (must be > 0). Values within ±linthresh are linear.
    ///
    /// # Panics
    /// Panics if linthresh <= 0
    pub fn new(min: f64, max: f64, linthresh: f64) -> Self {
        assert!(linthresh > 0.0, "SymLog scale requires positive linthresh");
        Self {
            min,
            max,
            linthresh,
            log_linthresh: linthresh.log10(),
        }
    }

    /// Transform a single value using symlog
    fn symlog(&self, value: f64) -> f64 {
        if value.abs() <= self.linthresh {
            // Linear region: scale to match log at threshold
            value / self.linthresh
        } else {
            // Logarithmic region
            let sign = value.signum();
            let abs_val = value.abs();
            sign * (1.0 + (abs_val / self.linthresh).log10())
        }
    }

    /// Inverse symlog transform
    fn inv_symlog(&self, transformed: f64) -> f64 {
        if transformed.abs() <= 1.0 {
            // Linear region
            transformed * self.linthresh
        } else {
            // Logarithmic region
            let sign = transformed.signum();
            let abs_t = transformed.abs();
            sign * self.linthresh * 10.0_f64.powf(abs_t - 1.0)
        }
    }
}

impl Scale for SymLogScale {
    fn transform(&self, value: f64) -> f64 {
        let t_min = self.symlog(self.min);
        let t_max = self.symlog(self.max);
        let t_value = self.symlog(value);

        let range = t_max - t_min;
        if range.abs() < f64::EPSILON {
            return 0.5;
        }
        (t_value - t_min) / range
    }

    fn inverse(&self, normalized: f64) -> f64 {
        let t_min = self.symlog(self.min);
        let t_max = self.symlog(self.max);
        let t_value = normalized * (t_max - t_min) + t_min;
        self.inv_symlog(t_value)
    }

    fn range(&self) -> (f64, f64) {
        (self.min, self.max)
    }
}

/// User-facing axis scale configuration
///
/// This enum provides a simple API for setting axis scales on plots.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum AxisScale {
    /// Linear scale (default)
    #[default]
    Linear,
    /// Logarithmic scale (base 10)
    /// Only valid for positive data values
    Log,
    /// Symmetric logarithmic scale
    /// Linear within ±linthresh, logarithmic outside
    SymLog {
        /// Linear threshold (values within ±linthresh are scaled linearly)
        linthresh: f64,
    },
}

#[inline]
pub(crate) fn linear_range_is_degenerate(range: f64) -> bool {
    range.abs() < f64::EPSILON
}

pub(crate) fn expand_degenerate_range(min: f64, max: f64, scale: &AxisScale) -> (f64, f64) {
    match scale {
        AxisScale::Log if min == max && min.is_finite() && min > 0.0 => {
            let lower = min / 10.0;
            let upper = min * 10.0;
            if lower > 0.0 && lower < min {
                (lower, if upper.is_finite() { upper } else { min })
            } else if upper.is_finite() && upper > min {
                (min, upper)
            } else {
                (min, max)
            }
        }
        AxisScale::Log => (min, max),
        _ if min == max || linear_range_is_degenerate(max - min) => (min - 1.0, max + 1.0),
        _ => (min, max),
    }
}

#[inline]
pub(crate) fn linear_normalized_position_with_range(
    value: f64,
    min: f64,
    max: f64,
    range: f64,
) -> f64 {
    if range.is_infinite() && value.is_finite() && min.is_finite() && max.is_finite() {
        (value / 2.0 - min / 2.0) / (max / 2.0 - min / 2.0)
    } else {
        (value - min) / range
    }
}

#[inline]
fn linear_inverse_normalized_position(normalized: f64, min: f64, max: f64) -> f64 {
    let range = max - min;
    if range.is_infinite() && min.is_finite() && max.is_finite() {
        (1.0 - normalized) * min + normalized * max
    } else {
        normalized * range + min
    }
}

#[inline]
fn log_normalization_bounds(min: f64, max: f64) -> (f64, f64) {
    if min.is_finite() && min > 0.0 && max.is_finite() && max > 0.0 {
        (min, max)
    } else {
        (min.max(f64::EPSILON), max.max(f64::EPSILON))
    }
}

#[inline]
fn log_ratio(value: f64, base: f64) -> f64 {
    let ratio = value / base;
    if ratio.is_finite() && ratio > 0.5 && ratio < 2.0 {
        ((value - base) / base).ln_1p()
    } else {
        value.ln() - base.ln()
    }
}

/// The one wording for "a logarithmic axis cannot show non-positive data".
///
/// Every refusal that stems from a log axis meeting a zero or a negative value
/// opens with this sentence — [`AxisScale::validate_range`] for an invalid axis
/// range, and the pre-render check that refuses aggregate plot geometry. Sharing
/// the string is what stops the two from drifting into different advice, and it
/// is the reason both of them name `SymLog` as the fix.
pub(crate) const LOG_SCALE_REQUIRES_POSITIVE: &str =
    "Logarithmic scale requires positive values. Use SymLog for data with zero or negative values.";

impl AxisScale {
    /// Create a logarithmic scale
    pub fn log() -> Self {
        AxisScale::Log
    }

    /// Create a symmetric logarithmic scale with the given linear threshold
    pub fn symlog(linthresh: f64) -> Self {
        AxisScale::SymLog { linthresh }
    }

    /// Can this scale represent `value` at all?
    ///
    /// A logarithmic axis has no position for zero or a negative sample. This
    /// is the single predicate that decides that, and both
    /// [`Self::normalized_position`] and [`Scale::transform`] for [`LogScale`]
    /// are defined in terms of it — so a caller that filters samples up front
    /// and a caller that just projects them cannot disagree about which samples
    /// exist.
    ///
    /// ```
    /// use ruviz::axes::AxisScale;
    ///
    /// assert!(AxisScale::Log.is_valid_value(10.0));
    /// assert!(!AxisScale::Log.is_valid_value(0.0));
    /// assert!(!AxisScale::Log.is_valid_value(-1.0));
    /// assert!(AxisScale::Linear.is_valid_value(-1.0));
    /// ```
    #[inline]
    pub fn is_valid_value(&self, value: f64) -> bool {
        match self {
            AxisScale::Linear | AxisScale::SymLog { .. } => value.is_finite(),
            AxisScale::Log => value.is_finite() && value > 0.0,
        }
    }

    /// The first finite value this scale has no position for, if any.
    ///
    /// Non-finite input is skipped: `NaN` and the infinities are not "data this
    /// axis cannot show", they are broken data, and they already have their own
    /// (better) diagnostic. What this finds is a real number the axis genuinely
    /// cannot place — a zero or a negative on a logarithmic axis.
    ///
    /// Callers that build *aggregate* geometry (a bar, a histogram bin, a box
    /// plot's quartiles) use this to refuse the figure up front, because such a
    /// value does not make their shape shorter, it makes it meaningless.
    /// Callers that draw independent samples must not: they drop the sample and
    /// break the line at the gap instead.
    ///
    /// ```
    /// use ruviz::axes::AxisScale;
    ///
    /// assert_eq!(AxisScale::Log.first_unplaceable([1.0, 10.0, 0.0]), Some(0.0));
    /// assert_eq!(AxisScale::Log.first_unplaceable([1.0, 10.0]), None);
    /// // A linear axis can place every finite number.
    /// assert_eq!(AxisScale::Linear.first_unplaceable([-1.0, 0.0]), None);
    /// // Broken data is not this function's business.
    /// assert_eq!(AxisScale::Log.first_unplaceable([f64::NAN]), None);
    /// ```
    pub fn first_unplaceable(&self, values: impl IntoIterator<Item = f64>) -> Option<f64> {
        if matches!(self, AxisScale::Linear | AxisScale::SymLog { .. }) {
            // Every finite value has a position, so the scan cannot find one.
            return None;
        }
        values
            .into_iter()
            .find(|value| value.is_finite() && !self.is_valid_value(*value))
    }

    /// Normalize a value into `[0, 1]` for the provided range.
    ///
    /// This preserves range direction, so reversed ranges produce inverted
    /// normalized coordinates.
    ///
    /// Returns `NaN` when [`Self::is_valid_value`] rejects `value` — notably a
    /// zero or negative sample on a [`AxisScale::Log`] axis. Renderers must
    /// treat a `NaN` position as "no point here" and break the polyline, rather
    /// than plotting it: previously such samples were clamped to `0.0` and drawn
    /// directly on the axis spine, where they read as real data.
    pub fn normalized_position(&self, value: f64, min: f64, max: f64) -> f64 {
        match self {
            AxisScale::Linear => {
                let range = max - min;
                if linear_range_is_degenerate(range) {
                    0.5
                } else {
                    linear_normalized_position_with_range(value, min, max, range)
                }
            }
            AxisScale::Log => {
                if !self.is_valid_value(value) {
                    return f64::NAN;
                }

                if min.is_finite() && min > 0.0 && max.is_finite() && max > 0.0 {
                    if min == max {
                        return 0.5;
                    }
                    return log_ratio(value, min) / log_ratio(max, min);
                }

                let (min, max) = log_normalization_bounds(min, max);
                let log_min = min.log10();
                let log_max = max.log10();
                let log_range = log_max - log_min;
                if log_range.abs() <= f64::EPSILON {
                    0.5
                } else {
                    (value.log10() - log_min) / log_range
                }
            }
            AxisScale::SymLog { linthresh } => {
                let symlog = |input: f64| {
                    if input.abs() <= *linthresh {
                        input / *linthresh
                    } else {
                        input.signum() * (1.0 + (input.abs() / *linthresh).log10())
                    }
                };

                let transformed_min = symlog(min);
                let transformed_max = symlog(max);
                let transformed_value = symlog(value);
                let range = transformed_max - transformed_min;
                if range.abs() <= f64::EPSILON {
                    0.5
                } else {
                    (transformed_value - transformed_min) / range
                }
            }
        }
    }

    /// Convert a normalized scale position back into a value in the provided range.
    ///
    /// This is the mathematical inverse of [`Self::normalized_position`] for valid,
    /// non-degenerate ranges. Range direction is preserved, so `0.0` maps to
    /// `min` and `1.0` maps to `max` even when the range is reversed.
    pub fn inverse_normalized_position(&self, normalized: f64, min: f64, max: f64) -> f64 {
        match self {
            AxisScale::Linear => linear_inverse_normalized_position(normalized, min, max),
            AxisScale::Log => {
                if min.is_finite() && min > 0.0 && max.is_finite() && max > 0.0 {
                    if normalized == 0.0 {
                        return min;
                    }
                    if normalized == 1.0 {
                        return max;
                    }
                    if min == max {
                        return min;
                    }

                    let log_range = log_ratio(max, min);
                    if log_range.abs() < 0.5 {
                        return min * (normalized * log_range).exp();
                    }
                }

                let (min, max) = log_normalization_bounds(min, max);
                let log_min = min.log10();
                let log_max = max.log10();
                10.0_f64.powf(normalized * (log_max - log_min) + log_min)
            }
            AxisScale::SymLog { linthresh } => {
                let symlog = |input: f64| {
                    if input.abs() <= *linthresh {
                        input / *linthresh
                    } else {
                        input.signum() * (1.0 + (input.abs() / *linthresh).log10())
                    }
                };
                let inverse_symlog = |input: f64| {
                    if input.abs() <= 1.0 {
                        input * *linthresh
                    } else {
                        input.signum() * *linthresh * 10.0_f64.powf(input.abs() - 1.0)
                    }
                };

                let transformed_min = symlog(min);
                let transformed_max = symlog(max);
                inverse_symlog(normalized * (transformed_max - transformed_min) + transformed_min)
            }
        }
    }

    /// Create a scale instance for the given data range
    pub fn create_scale(&self, min: f64, max: f64) -> Box<dyn Scale> {
        match self {
            AxisScale::Linear => Box::new(LinearScale::new(min, max)),
            AxisScale::Log => {
                let (min, max) = log_normalization_bounds(min, max);
                Box::new(LogScale::new(min, max))
            }
            AxisScale::SymLog { linthresh } => Box::new(SymLogScale::new(min, max, *linthresh)),
        }
    }

    /// Check if this scale is valid for the given data range
    pub fn validate_range(&self, min: f64, max: f64) -> Result<(), String> {
        match self {
            AxisScale::Linear => Ok(()),
            AxisScale::Log => {
                if min <= 0.0 || max <= 0.0 {
                    Err(LOG_SCALE_REQUIRES_POSITIVE.to_string())
                } else {
                    Ok(())
                }
            }
            AxisScale::SymLog { linthresh } => {
                if *linthresh <= 0.0 {
                    Err("SymLog scale requires positive linthresh value.".to_string())
                } else {
                    Ok(())
                }
            }
        }
    }
}

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

    #[test]
    fn test_linear_scale() {
        let scale = LinearScale::new(0.0, 100.0);

        assert!((scale.transform(0.0) - 0.0).abs() < 1e-10);
        assert!((scale.transform(50.0) - 0.5).abs() < 1e-10);
        assert!((scale.transform(100.0) - 1.0).abs() < 1e-10);

        assert!((scale.inverse(0.0) - 0.0).abs() < 1e-10);
        assert!((scale.inverse(0.5) - 50.0).abs() < 1e-10);
        assert!((scale.inverse(1.0) - 100.0).abs() < 1e-10);
    }

    #[test]
    fn test_log_scale() {
        let scale = LogScale::new(1.0, 1000.0);

        assert!((scale.transform(1.0) - 0.0).abs() < 1e-10);
        assert!((scale.transform(1000.0) - 1.0).abs() < 1e-10);

        // 10^1.5 ≈ 31.6 should be at ~0.5
        let mid = scale.inverse(0.5);
        assert!((mid.log10() - 1.5).abs() < 1e-10);
    }

    #[test]
    fn test_scale_range() {
        let scale = LinearScale::new(10.0, 20.0);
        assert_eq!(scale.range(), (10.0, 20.0));
    }

    #[test]
    fn test_symlog_scale_linear_region() {
        let scale = SymLogScale::new(-10.0, 10.0, 1.0);

        // Values within ±linthresh should be linear
        let t_zero = scale.transform(0.0);
        let t_half = scale.transform(0.5);
        let t_neg_half = scale.transform(-0.5);

        // Zero should be at center
        assert!((t_zero - 0.5).abs() < 0.1);
        // Symmetric around zero in linear region
        assert!((t_half - t_zero - (t_zero - t_neg_half)).abs() < 0.01);
    }

    #[test]
    fn test_symlog_scale_log_region() {
        let scale = SymLogScale::new(1.0, 100.0, 1.0);

        // At threshold, t=1
        let t_1 = scale.transform(1.0);
        // At 10, t = 1 + log10(10) = 2
        let t_10 = scale.transform(10.0);
        // At 100, t = 1 + log10(100) = 3
        let t_100 = scale.transform(100.0);

        assert!(t_1 < t_10);
        assert!(t_10 < t_100);
        assert!((t_1 - 0.0).abs() < 0.01); // min should map to 0
        assert!((t_100 - 1.0).abs() < 0.01); // max should map to 1
    }

    #[test]
    fn test_symlog_scale_inverse() {
        let scale = SymLogScale::new(-100.0, 100.0, 1.0);

        for value in [-50.0, -1.0, -0.5, 0.0, 0.5, 1.0, 50.0] {
            let normalized = scale.transform(value);
            let back = scale.inverse(normalized);
            assert!(
                (back - value).abs() < 0.01,
                "Inverse failed for {}: got {}",
                value,
                back
            );
        }
    }

    #[test]
    fn test_axis_scale_enum() {
        assert_eq!(AxisScale::default(), AxisScale::Linear);
        assert_eq!(AxisScale::log(), AxisScale::Log);
        assert_eq!(AxisScale::symlog(1.0), AxisScale::SymLog { linthresh: 1.0 });
    }

    #[test]
    fn test_axis_scale_validation() {
        // Linear is always valid
        assert!(AxisScale::Linear.validate_range(-10.0, 10.0).is_ok());

        // Log requires positive
        assert!(AxisScale::Log.validate_range(1.0, 100.0).is_ok());
        assert!(AxisScale::Log.validate_range(-1.0, 100.0).is_err());
        assert!(AxisScale::Log.validate_range(0.0, 100.0).is_err());

        // SymLog requires positive linthresh
        assert!(AxisScale::symlog(1.0).validate_range(-100.0, 100.0).is_ok());
        assert!(
            AxisScale::symlog(0.0)
                .validate_range(-100.0, 100.0)
                .is_err()
        );
    }

    #[test]
    fn test_axis_scale_create_scale() {
        let linear = AxisScale::Linear.create_scale(0.0, 100.0);
        assert!((linear.transform(50.0) - 0.5).abs() < 0.01);

        let log = AxisScale::Log.create_scale(1.0, 1000.0);
        assert!((log.transform(1.0) - 0.0).abs() < 0.01);
        assert!((log.transform(1000.0) - 1.0).abs() < 0.01);

        let symlog = AxisScale::symlog(1.0).create_scale(-100.0, 100.0);
        assert!((symlog.transform(0.0) - 0.5).abs() < 0.1);
    }

    #[test]
    fn test_axis_scale_create_log_scale_preserves_positive_sub_epsilon_bounds() {
        let min = f64::EPSILON / 16.0;
        let max = f64::EPSILON / 2.0;
        let scale = AxisScale::Log.create_scale(min, max);

        assert_eq!(scale.range(), (min, max));
        assert_eq!(scale.transform(min), 0.0);
        assert_eq!(scale.transform(max), 1.0);
        assert!((scale.inverse(0.5) - (min * max).sqrt()).abs() <= min * 1e-12);
    }

    #[test]
    fn test_expand_equal_log_range_stays_positive_for_tiny_value() {
        for value in [1.0, f64::EPSILON / 1024.0, f64::from_bits(1)] {
            let (min, max) = expand_degenerate_range(value, value, &AxisScale::Log);

            assert!(min > 0.0, "lower bound must stay positive for {value}");
            assert!(min < value || max > value);
            assert!(min < max, "expanded bounds must have extent for {value}");
            assert!(max.is_finite());
        }
    }

    #[test]
    fn test_axis_scale_normalized_position_preserves_reversed_ranges() {
        assert!((AxisScale::Linear.normalized_position(4.0, 4.0, 0.0) - 0.0).abs() < 1e-10);
        assert!((AxisScale::Linear.normalized_position(0.0, 4.0, 0.0) - 1.0).abs() < 1e-10);

        let log_mid = AxisScale::Log.normalized_position(10.0, 100.0, 1.0);
        assert!((log_mid - 0.5).abs() < 1e-10);
    }

    #[test]
    fn test_axis_scale_inverse_normalization_endpoints_and_midpoints() {
        let cases = [
            (AxisScale::Linear, 0.0, 10.0, 5.0),
            (AxisScale::Log, 1.0, 100.0, 10.0),
            (AxisScale::symlog(1.0), -100.0, 100.0, 0.0),
        ];

        for (scale, min, max, midpoint) in cases {
            assert!((scale.inverse_normalized_position(0.0, min, max) - min).abs() < 1e-10);
            assert!((scale.inverse_normalized_position(0.5, min, max) - midpoint).abs() < 1e-10);
            assert!((scale.inverse_normalized_position(1.0, min, max) - max).abs() < 1e-10);
        }
    }

    #[test]
    fn test_axis_scale_inverse_normalization_roundtrips_reversed_ranges() {
        let cases = [
            (AxisScale::Linear, 20.0, -10.0, vec![20.0, 7.0, -10.0]),
            (AxisScale::Log, 1000.0, 1.0, vec![1000.0, 10.0, 1.0]),
            (
                AxisScale::symlog(2.0),
                200.0,
                -50.0,
                vec![200.0, 10.0, 0.0, -2.0, -50.0],
            ),
        ];

        for (scale, min, max, values) in cases {
            for value in values {
                let normalized = scale.normalized_position(value, min, max);
                let recovered = scale.inverse_normalized_position(normalized, min, max);
                let tolerance = value.abs().max(1.0) * 1e-10;
                assert!(
                    (recovered - value).abs() <= tolerance,
                    "{scale:?} failed to round-trip {value} in {min}..{max}: {recovered}"
                );
            }
        }
    }

    /// Regression: non-positive samples used to normalize to `0.0`, which put
    /// them exactly on the axis spine where they read as genuine data. They
    /// must be `NaN` so renderers can break the line at the gap.
    #[test]
    fn test_axis_scale_log_invalid_values_are_not_clamped_onto_the_spine() {
        for invalid in [0.0, -0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            assert!(
                !AxisScale::Log.is_valid_value(invalid),
                "{invalid} should be invalid on a log axis"
            );
            let normalized = AxisScale::Log.normalized_position(invalid, 1.0, 100.0);
            assert!(
                normalized.is_nan(),
                "log axis mapped {invalid} to {normalized} instead of NaN"
            );
        }

        // Valid samples are unaffected.
        assert_eq!(AxisScale::Log.normalized_position(1.0, 1.0, 100.0), 0.0);
        assert_eq!(AxisScale::Log.normalized_position(100.0, 1.0, 100.0), 1.0);
        assert!(AxisScale::Log.inverse_normalized_position(0.5, 1.0, 100.0) > 0.0);
        assert!(AxisScale::Log.validate_range(0.0, 100.0).is_err());
    }

    #[test]
    fn test_first_unplaceable_reports_the_offending_value_on_a_log_axis() {
        assert_eq!(
            AxisScale::Log.first_unplaceable([5.0, 1.0, 0.0, -3.0]),
            Some(0.0),
            "the first offender is reported, not the last"
        );
        assert_eq!(AxisScale::Log.first_unplaceable([5.0, -3.0]), Some(-3.0));
        assert_eq!(AxisScale::Log.first_unplaceable([1.0, 10.0, 100.0]), None);
        assert_eq!(AxisScale::Log.first_unplaceable([0.0f64; 0]), None);
    }

    /// Broken data (`NaN`, infinities) is not what this predicate is about, and
    /// reporting it here would hand the caller a "use SymLog" message for a
    /// problem SymLog does not solve.
    #[test]
    fn test_first_unplaceable_ignores_non_finite_values() {
        assert_eq!(
            AxisScale::Log.first_unplaceable([f64::NAN, f64::INFINITY, f64::NEG_INFINITY]),
            None
        );
        assert_eq!(
            AxisScale::Log.first_unplaceable([f64::NAN, -1.0]),
            Some(-1.0),
            "a genuine offender after a NaN is still found"
        );
    }

    /// A linear or symlog axis has a position for every finite number, so the
    /// scan must never fire there — the aggregate-geometry refusal built on it
    /// applies to log axes and nothing else.
    #[test]
    fn test_first_unplaceable_never_fires_on_non_log_scales() {
        for scale in [AxisScale::Linear, AxisScale::symlog(1.0)] {
            assert_eq!(
                scale.first_unplaceable([-1e300, -1.0, 0.0, 1.0, f64::NAN]),
                None,
                "{scale:?} refused a value it can place"
            );
        }
    }

    /// `validate_range` and the aggregate-geometry refusal must give the same
    /// advice, which is only guaranteed while they share one string.
    #[test]
    fn test_log_range_rejection_uses_the_shared_wording() {
        let message = AxisScale::Log
            .validate_range(0.0, 100.0)
            .expect_err("a zero lower bound is not on a log axis");
        assert_eq!(message, LOG_SCALE_REQUIRES_POSITIVE);
        assert!(message.contains("SymLog"), "{message}");
    }

    #[test]
    fn test_is_valid_value_accepts_everything_finite_on_non_log_scales() {
        for scale in [AxisScale::Linear, AxisScale::symlog(1.0)] {
            for value in [-1e300, -1.0, 0.0, 1.0, 1e300] {
                assert!(scale.is_valid_value(value), "{scale:?} rejected {value}");
            }
            assert!(!scale.is_valid_value(f64::NAN));
            assert!(!scale.is_valid_value(f64::INFINITY));
        }
    }

    #[test]
    fn test_log_scale_transform_agrees_with_axis_scale_on_invalid_values() {
        let scale = LogScale::new(1.0, 1000.0);
        for invalid in [0.0, -5.0, f64::NAN] {
            assert!(scale.transform(invalid).is_nan());
            assert!(
                AxisScale::Log
                    .normalized_position(invalid, 1.0, 1000.0)
                    .is_nan()
            );
        }
    }

    #[test]
    fn test_axis_scale_log_normalization_supports_sub_epsilon_domains() {
        let low = f64::EPSILON / 16.0;
        let high = f64::EPSILON / 2.0;
        let midpoint = 10.0_f64.powf(low.log10() + (high.log10() - low.log10()) * 0.5);

        for (min, max) in [(low, high), (high, low)] {
            assert_eq!(AxisScale::Log.normalized_position(min, min, max), 0.0);
            assert_eq!(AxisScale::Log.normalized_position(max, min, max), 1.0);

            for value in [min, midpoint, max] {
                let normalized = AxisScale::Log.normalized_position(value, min, max);
                let recovered = AxisScale::Log.inverse_normalized_position(normalized, min, max);
                assert!(
                    ((recovered - value) / value).abs() <= 1e-12,
                    "failed to round-trip {value} in {min}..{max}: {recovered}"
                );
            }
        }
    }

    #[test]
    fn test_axis_scale_log_normalization_supports_close_positive_bounds() {
        let min = 1.0_f64;
        let midpoint = f64::from_bits(min.to_bits() + 1);
        let max = f64::from_bits(min.to_bits() + 2);

        assert_eq!(AxisScale::Log.normalized_position(min, min, max), 0.0);
        assert_eq!(AxisScale::Log.normalized_position(max, min, max), 1.0);
        let normalized = AxisScale::Log.normalized_position(midpoint, min, max);
        assert!((normalized - 0.5).abs() <= f64::EPSILON);
        assert_eq!(
            AxisScale::Log.inverse_normalized_position(normalized, min, max),
            midpoint
        );
    }

    #[test]
    fn test_axis_scale_linear_exact_epsilon_span_is_not_degenerate() {
        let min = 0.0;
        let max = f64::EPSILON;

        assert_eq!(AxisScale::Linear.normalized_position(min, min, max), 0.0);
        assert_eq!(
            AxisScale::Linear.normalized_position(max / 2.0, min, max),
            0.5
        );
        assert_eq!(AxisScale::Linear.normalized_position(max, min, max), 1.0);

        let translated_min = 1.0;
        let translated_max = translated_min + f64::EPSILON;
        assert_eq!(
            AxisScale::Linear.normalized_position(translated_min, translated_min, translated_max),
            0.0
        );
        assert_eq!(
            AxisScale::Linear.normalized_position(translated_max, translated_min, translated_max),
            1.0
        );
    }

    #[test]
    fn test_axis_scale_linear_normalization_supports_finite_extreme_ranges() {
        for (min, max) in [(-f64::MAX, f64::MAX), (f64::MAX, -f64::MAX)] {
            assert_eq!(AxisScale::Linear.normalized_position(min, min, max), 0.0);
            assert_eq!(AxisScale::Linear.normalized_position(0.0, min, max), 0.5);
            assert_eq!(AxisScale::Linear.normalized_position(max, min, max), 1.0);

            assert_eq!(
                AxisScale::Linear.inverse_normalized_position(0.0, min, max),
                min
            );
            assert_eq!(
                AxisScale::Linear.inverse_normalized_position(0.5, min, max),
                0.0
            );
            assert_eq!(
                AxisScale::Linear.inverse_normalized_position(1.0, min, max),
                max
            );
        }
    }
}