u-analytics 0.27.0

Statistical process control, process capability, Weibull reliability, change-point detection, measurement system analysis (Gage R&R), correlation, regression, distribution analysis, and hypothesis testing.
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
//! Run rules for detecting non-random patterns in control charts.
//!
//! Implements the Western Electric (4 rules) and Nelson (8 rules) run tests
//! for identifying special causes of variation in control chart data. The two
//! sets share three tests and differ in the fourth: a run on one side of the
//! centre line is **eight** points in the Western Electric handbook and
//! **nine** in Nelson's list, so each has its own [`ViolationType`].
//!
//! # Choosing a set
//!
//! Every added test raises the false alarm rate of an in-control process. The
//! supplementary tests help find a shift while a process is being brought into
//! control (Phase I); in routine monitoring (Phase II) the 3-sigma test alone is
//! the conventional choice (ISO 7870-2:2023, 8.2.7). That is why an unspecified
//! set is [`RuleSet::shewhart`].
//!
//! # References
//!
//! - Nelson, L.S. (1984). "The Shewhart Control Chart — Tests for Special Causes",
//!   *Journal of Quality Technology* 16(4), pp. 237-239.
//! - Western Electric (1956). *Statistical Quality Control Handbook*.
//! - NIST/SEMATECH e-Handbook of Statistical Methods, 6.3.2 ("What are the WECO rules").
//! - ISO 7870-2:2023, *Control charts — Part 2: Shewhart control charts*, 8.2.7 and Annex B.
//! - Montgomery, D.C. (2019). *Introduction to Statistical Quality Control*, 8th ed.

use super::chart::{ChartPoint, ControlLimits, ViolationType};

/// Trait for applying run rules to chart data.
///
/// Run rules detect non-random patterns that indicate special causes of
/// variation even when individual points remain within control limits.
pub trait RunRule {
    /// Check points against this rule set and return violations per point index.
    ///
    /// Returns a vector of `(point_index, violation_type)` pairs. A single
    /// point may appear multiple times if it triggers multiple rules.
    fn check(&self, points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)>;
}

/// Western Electric rules (4 rules) -- [`RuleSet::western_electric`].
///
/// The original run tests of the Western Electric *Statistical Quality Control
/// Handbook* (1956):
///
/// 1. Any point beyond 3 sigma (Nelson Rule 1)
/// 2. 2 of 3 consecutive points beyond 2 sigma, same side (Nelson Rule 5)
/// 3. 4 of 5 consecutive points beyond 1 sigma, same side (Nelson Rule 6)
/// 4. **8** consecutive points on the same side of the center line
///    ([`ViolationType::EightOneSide`] -- Nelson's Rule 2 asks for nine)
pub struct WesternElectricRules;

/// Nelson rules (8 rules) -- [`RuleSet::nelson`].
///
/// The full set of eight tests for special causes as defined by
/// Nelson (1984). Rules 1, 5 and 6 are also Western Electric rules; Rule 2
/// (nine points on one side) is a longer run than Western Electric's eight.
///
/// # Examples
///
/// ```
/// use u_analytics::spc::{NelsonRules, RunRule, ChartPoint, ControlLimits};
///
/// let limits = ControlLimits { ucl: 28.0, cl: 25.0, lcl: 22.0 };
/// let points: Vec<ChartPoint> = vec![
///     ChartPoint { value: 25.0, index: 0, violations: vec![] },
///     ChartPoint { value: 29.0, index: 1, violations: vec![] },
/// ];
///
/// let violations = NelsonRules.check(&points, &limits);
/// assert!(!violations.is_empty()); // Rule 1: point beyond UCL
/// ```
pub struct NelsonRules;

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Compute 1-sigma and 2-sigma zone boundaries from control limits.
///
/// Returns `(one_sigma, two_sigma)` where `one_sigma = (UCL - CL) / 3`.
fn zone_widths(limits: &ControlLimits) -> (f64, f64) {
    let sigma = (limits.ucl - limits.cl) / 3.0;
    (sigma, 2.0 * sigma)
}

/// Nelson Rule 1: Point beyond control limits.
///
/// A single point falls outside the UCL or LCL.
fn check_rule1(points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
    let mut violations = Vec::new();
    for point in points {
        if point.value > limits.ucl || point.value < limits.lcl {
            violations.push((point.index, ViolationType::BeyondLimits));
        }
    }
    violations
}

/// `run` consecutive points on the same side of the center line, reported as
/// `rule` -- Nelson Rule 2 (nine) and the Western Electric run rule (eight).
///
/// Indicates a sustained shift in the process mean.
fn check_one_side(
    points: &[ChartPoint],
    limits: &ControlLimits,
    run: usize,
    rule: ViolationType,
) -> Vec<(usize, ViolationType)> {
    let mut violations = Vec::new();
    if points.len() < run {
        return violations;
    }

    let cl = limits.cl;
    // Track consecutive runs above/below center line.
    // +1 = above, -1 = below, 0 = exactly on center (counted as neither side).
    let sides: Vec<i8> = points
        .iter()
        .map(|p| {
            if p.value > cl {
                1
            } else if p.value < cl {
                -1
            } else {
                0
            }
        })
        .collect();

    let mut run_length = 1_usize;
    for i in 1..sides.len() {
        if sides[i] != 0 && sides[i] == sides[i - 1] {
            run_length += 1;
        } else {
            run_length = 1;
        }
        if run_length >= run {
            violations.push((points[i].index, rule));
        }
    }
    violations
}

/// Nelson Rule 3: 6 consecutive points steadily increasing or decreasing.
///
/// Indicates a trend in the process.
fn check_rule3(points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
    let _ = limits; // Not used for trend detection
    let mut violations = Vec::new();
    if points.len() < 6 {
        return violations;
    }

    // Direction: +1 = increasing, -1 = decreasing, 0 = equal
    let dirs: Vec<i8> = points
        .windows(2)
        .map(|w| {
            if w[1].value > w[0].value {
                1
            } else if w[1].value < w[0].value {
                -1
            } else {
                0
            }
        })
        .collect();

    let mut run_length = 1_usize;
    for i in 1..dirs.len() {
        if dirs[i] != 0 && dirs[i] == dirs[i - 1] {
            run_length += 1;
        } else {
            run_length = 1;
        }
        // 5 consecutive same-direction changes = 6 points forming a trend.
        // The violation is reported at the last point of the trend.
        if run_length >= 5 {
            // dirs[i] corresponds to the transition between points[i] and points[i+1],
            // so the last point of the 6-point trend is points[i+1].
            violations.push((points[i + 1].index, ViolationType::SixTrend));
        }
    }
    violations
}

/// Nelson Rule 4: 14 consecutive points alternating up and down.
///
/// Indicates systematic variation (e.g., two alternating streams).
fn check_rule4(points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
    let _ = limits;
    let mut violations = Vec::new();
    if points.len() < 14 {
        return violations;
    }

    // Direction changes: +1 = up, -1 = down, 0 = equal
    let dirs: Vec<i8> = points
        .windows(2)
        .map(|w| {
            if w[1].value > w[0].value {
                1
            } else if w[1].value < w[0].value {
                -1
            } else {
                0
            }
        })
        .collect();

    // Count consecutive alternations
    let mut alt_length = 1_usize;
    for i in 1..dirs.len() {
        if dirs[i] != 0 && dirs[i - 1] != 0 && dirs[i] == -dirs[i - 1] {
            alt_length += 1;
        } else {
            alt_length = 1;
        }
        // 13 consecutive alternating directions = 14 points alternating.
        // dirs[i] corresponds to points[i]→points[i+1],
        // so the last point is points[i+1].
        if alt_length >= 13 {
            violations.push((points[i + 1].index, ViolationType::FourteenAlternating));
        }
    }
    violations
}

/// Nelson Rule 5: 2 out of 3 consecutive points beyond 2 sigma, same side.
///
/// An early warning of a potential shift.
fn check_rule5(points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
    let mut violations = Vec::new();
    if points.len() < 3 {
        return violations;
    }

    let (_, two_sigma) = zone_widths(limits);
    let upper_2s = limits.cl + two_sigma;
    let lower_2s = limits.cl - two_sigma;

    for i in 2..points.len() {
        let window = &points[i - 2..=i];

        // Check upper side: count points above CL + 2σ
        let above_count = window.iter().filter(|p| p.value > upper_2s).count();
        if above_count >= 2 {
            violations.push((points[i].index, ViolationType::TwoOfThreeBeyond2Sigma));
            continue;
        }

        // Check lower side: count points below CL - 2σ
        let below_count = window.iter().filter(|p| p.value < lower_2s).count();
        if below_count >= 2 {
            violations.push((points[i].index, ViolationType::TwoOfThreeBeyond2Sigma));
        }
    }
    violations
}

/// Nelson Rule 6: 4 out of 5 consecutive points beyond 1 sigma, same side.
///
/// Indicates a small sustained shift.
fn check_rule6(points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
    let mut violations = Vec::new();
    if points.len() < 5 {
        return violations;
    }

    let (one_sigma, _) = zone_widths(limits);
    let upper_1s = limits.cl + one_sigma;
    let lower_1s = limits.cl - one_sigma;

    for i in 4..points.len() {
        let window = &points[i - 4..=i];

        // Check upper side: count points above CL + σ
        let above_count = window.iter().filter(|p| p.value > upper_1s).count();
        if above_count >= 4 {
            violations.push((points[i].index, ViolationType::FourOfFiveBeyond1Sigma));
            continue;
        }

        // Check lower side: count points below CL - σ
        let below_count = window.iter().filter(|p| p.value < lower_1s).count();
        if below_count >= 4 {
            violations.push((points[i].index, ViolationType::FourOfFiveBeyond1Sigma));
        }
    }
    violations
}

/// Nelson Rule 7: 15 consecutive points within 1 sigma of center line.
///
/// Indicates stratification — reduced variation suggesting mixed streams.
fn check_rule7(points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
    let mut violations = Vec::new();
    if points.len() < 15 {
        return violations;
    }

    let (one_sigma, _) = zone_widths(limits);
    let upper_1s = limits.cl + one_sigma;
    let lower_1s = limits.cl - one_sigma;

    let mut run_length = 0_usize;
    for point in points {
        if point.value >= lower_1s && point.value <= upper_1s {
            run_length += 1;
        } else {
            run_length = 0;
        }
        if run_length >= 15 {
            violations.push((point.index, ViolationType::FifteenWithin1Sigma));
        }
    }
    violations
}

/// Nelson Rule 8: 8 consecutive points beyond 1 sigma on either side.
///
/// Indicates a mixture pattern — points avoid the center zone.
fn check_rule8(points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
    let mut violations = Vec::new();
    if points.len() < 8 {
        return violations;
    }

    let (one_sigma, _) = zone_widths(limits);
    let upper_1s = limits.cl + one_sigma;
    let lower_1s = limits.cl - one_sigma;

    let mut run_length = 0_usize;
    for point in points {
        // Point is beyond 1σ on either side (not within CL ± σ)
        if point.value > upper_1s || point.value < lower_1s {
            run_length += 1;
        } else {
            run_length = 0;
        }
        if run_length >= 8 {
            violations.push((point.index, ViolationType::EightBeyond1Sigma));
        }
    }
    violations
}

// ---------------------------------------------------------------------------
// Selectable rule sets
// ---------------------------------------------------------------------------

/// A chosen subset of the run tests.
///
/// Each test reports exactly one [`ViolationType`], so a rule is named by what
/// it would report rather than by a parallel enum that would have to be kept in
/// step with this one.
///
/// Three sets have names -- [`shewhart`](RuleSet::shewhart) (the 3-sigma test
/// alone, the default), [`western_electric`](RuleSet::western_electric) and
/// [`nelson`](RuleSet::nelson) -- and [`RuleSet::named`] looks them up by the
/// names a wire request uses; any other combination is built from the tests a
/// process actually warrants. A rule that a process is known to
/// trigger for a benign reason -- a deliberately drifting tool, a bimodal
/// fixture -- otherwise has to be filtered out downstream, after it has already
/// been counted as an out-of-control signal.
///
/// # Examples
///
/// ```
/// use u_analytics::spc::{RuleSet, RunRule, ChartPoint, ControlLimits, ViolationType};
///
/// // Only the 3-sigma test, and nothing else.
/// let rules = RuleSet::from_iter([ViolationType::BeyondLimits]);
///
/// let limits = ControlLimits { ucl: 28.0, cl: 25.0, lcl: 22.0 };
/// let points: Vec<ChartPoint> = (0..12)
///     .map(|i| ChartPoint { value: 26.0, index: i, violations: vec![] })
///     .collect();
///
/// // Twelve points above the centre line would trip Nelson rule 2, but that
/// // test is not in this set.
/// assert!(rules.check(&points, &limits).is_empty());
/// assert!(RuleSet::nelson().check(&points, &limits).len() > 0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RuleSet {
    mask: u16,
}

fn bit_of(v: ViolationType) -> u16 {
    let position = ViolationType::ALL
        .iter()
        .position(|&r| r == v)
        .expect("ViolationType::ALL lists every variant");
    1 << position
}

impl RuleSet {
    /// The names [`RuleSet::named`] takes, in the order a refusal lists them.
    pub const NAMES: [&'static str; 3] = ["shewhart", "western_electric", "nelson"];

    /// The 3-sigma test alone -- Shewhart's criterion, and the default.
    ///
    /// In routine monitoring each added test raises the false alarm rate of an
    /// in-control process (ISO 7870-2:2023, 8.2.7), so the supplementary tests
    /// are chosen, not assumed.
    pub fn shewhart() -> Self {
        Self::from_iter([ViolationType::BeyondLimits])
    }

    /// Nelson's eight tests (1984).
    pub fn nelson() -> Self {
        Self::from_iter([
            ViolationType::BeyondLimits,
            ViolationType::NineOneSide,
            ViolationType::SixTrend,
            ViolationType::FourteenAlternating,
            ViolationType::TwoOfThreeBeyond2Sigma,
            ViolationType::FourOfFiveBeyond1Sigma,
            ViolationType::FifteenWithin1Sigma,
            ViolationType::EightBeyond1Sigma,
        ])
    }

    /// The four Western Electric tests (1956): Nelson rules 1, 5 and 6, and
    /// eight points in a row on one side of the centre line.
    pub fn western_electric() -> Self {
        Self::from_iter([
            ViolationType::BeyondLimits,
            ViolationType::TwoOfThreeBeyond2Sigma,
            ViolationType::FourOfFiveBeyond1Sigma,
            ViolationType::EightOneSide,
        ])
    }

    /// The set a name in [`RuleSet::NAMES`] stands for.
    pub fn named(name: &str) -> Option<Self> {
        match name {
            "shewhart" => Some(Self::shewhart()),
            "western_electric" => Some(Self::western_electric()),
            "nelson" => Some(Self::nelson()),
            _ => None,
        }
    }

    /// The empty set: no run test is applied.
    ///
    /// Useful as a base to add to, and as the honest way to say "limits only".
    pub fn none() -> Self {
        Self { mask: 0 }
    }

    /// Whether this set applies the test that reports `rule`.
    pub fn contains(&self, rule: ViolationType) -> bool {
        self.mask & bit_of(rule) != 0
    }

    /// This set with `rule` added.
    #[must_use]
    pub fn with(mut self, rule: ViolationType) -> Self {
        self.mask |= bit_of(rule);
        self
    }

    /// This set with `rule` removed.
    #[must_use]
    pub fn without(mut self, rule: ViolationType) -> Self {
        self.mask &= !bit_of(rule);
        self
    }

    /// The tests in this set, in the order of [`ViolationType::ALL`].
    pub fn iter(&self) -> impl Iterator<Item = ViolationType> + '_ {
        ViolationType::ALL.into_iter().filter(|&r| self.contains(r))
    }

    /// How many tests this set applies.
    pub fn len(&self) -> usize {
        self.mask.count_ones() as usize
    }

    /// Whether no test is applied.
    pub fn is_empty(&self) -> bool {
        self.mask == 0
    }
}

impl Default for RuleSet {
    /// [`RuleSet::shewhart`] -- the 3-sigma test alone.
    fn default() -> Self {
        Self::shewhart()
    }
}

impl FromIterator<ViolationType> for RuleSet {
    fn from_iter<I: IntoIterator<Item = ViolationType>>(iter: I) -> Self {
        let mut mask = 0u16;
        for v in iter {
            mask |= bit_of(v);
        }
        Self { mask }
    }
}

impl RunRule for RuleSet {
    fn check(&self, points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
        let mut results = Vec::new();
        for rule in self.iter() {
            results.extend(match rule {
                ViolationType::BeyondLimits => check_rule1(points, limits),
                ViolationType::NineOneSide => {
                    check_one_side(points, limits, 9, ViolationType::NineOneSide)
                }
                ViolationType::EightOneSide => {
                    check_one_side(points, limits, 8, ViolationType::EightOneSide)
                }
                ViolationType::SixTrend => check_rule3(points, limits),
                ViolationType::FourteenAlternating => check_rule4(points, limits),
                ViolationType::TwoOfThreeBeyond2Sigma => check_rule5(points, limits),
                ViolationType::FourOfFiveBeyond1Sigma => check_rule6(points, limits),
                ViolationType::FifteenWithin1Sigma => check_rule7(points, limits),
                ViolationType::EightBeyond1Sigma => check_rule8(points, limits),
            });
        }
        results.sort_by_key(|&(idx, _)| idx);
        results
    }
}

// ---------------------------------------------------------------------------
// RunRule implementations
// ---------------------------------------------------------------------------

impl RunRule for WesternElectricRules {
    /// Apply the 4 Western Electric run rules.
    fn check(&self, points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
        RuleSet::western_electric().check(points, limits)
    }
}

impl RunRule for NelsonRules {
    /// Apply all 8 Nelson run rules.
    fn check(&self, points: &[ChartPoint], limits: &ControlLimits) -> Vec<(usize, ViolationType)> {
        RuleSet::nelson().check(points, limits)
    }
}

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

    // --- RuleSet ---

    /// Twelve points above the centre line: rule 2 fires, rule 1 does not.
    /// The distinguishing case for "did the selection actually take effect".
    fn nine_on_one_side() -> (Vec<ChartPoint>, ControlLimits) {
        let limits = ControlLimits {
            ucl: 28.0,
            cl: 25.0,
            lcl: 22.0,
        };
        let points = (0..12)
            .map(|i| ChartPoint {
                value: 26.0,
                index: i,
                violations: vec![],
            })
            .collect();
        (points, limits)
    }

    #[test]
    fn ruleset_applies_only_the_tests_it_holds() {
        let (points, limits) = nine_on_one_side();

        // Nelson catches the run; a set without that test does not.
        assert!(!RuleSet::nelson().check(&points, &limits).is_empty());
        assert!(RuleSet::nelson()
            .without(ViolationType::NineOneSide)
            .check(&points, &limits)
            .is_empty());

        // And a set holding only that test still catches it -- so the empty
        // result above is the selection working, not the data failing to trip.
        assert!(!RuleSet::from_iter([ViolationType::NineOneSide])
            .check(&points, &limits)
            .is_empty());
    }

    #[test]
    fn ruleset_empty_reports_nothing_even_beyond_limits() {
        let limits = ControlLimits {
            ucl: 28.0,
            cl: 25.0,
            lcl: 22.0,
        };
        let points = vec![ChartPoint {
            value: 99.0,
            index: 0,
            violations: vec![],
        }];
        assert!(!RuleSet::nelson().check(&points, &limits).is_empty());
        assert!(RuleSet::none().check(&points, &limits).is_empty());
    }

    #[test]
    fn named_sets_match_their_definitions() {
        assert_eq!(RuleSet::nelson().len(), 8);
        assert_eq!(RuleSet::western_electric().len(), 4);
        for r in [
            ViolationType::BeyondLimits,
            ViolationType::TwoOfThreeBeyond2Sigma,
            ViolationType::FourOfFiveBeyond1Sigma,
            ViolationType::EightOneSide,
        ] {
            assert!(RuleSet::western_electric().contains(r), "{r:?} missing");
        }
        for r in [
            ViolationType::NineOneSide,
            ViolationType::SixTrend,
            ViolationType::FourteenAlternating,
            ViolationType::FifteenWithin1Sigma,
            ViolationType::EightBeyond1Sigma,
        ] {
            assert!(!RuleSet::western_electric().contains(r), "{r:?} present");
        }
        assert!(RuleSet::none().is_empty());
    }

    /// The named unit structs delegate to `RuleSet`, so they must still agree
    /// with it -- otherwise the delegation quietly changed public behaviour.
    #[test]
    fn named_unit_structs_agree_with_their_rule_sets() {
        let (points, limits) = nine_on_one_side();
        assert_eq!(
            NelsonRules.check(&points, &limits),
            RuleSet::nelson().check(&points, &limits)
        );
        assert_eq!(
            WesternElectricRules.check(&points, &limits),
            RuleSet::western_electric().check(&points, &limits)
        );
    }

    /// Helper: create chart points from a slice of values.
    fn make_points(values: &[f64]) -> Vec<ChartPoint> {
        values
            .iter()
            .enumerate()
            .map(|(i, &v)| ChartPoint {
                value: v,
                index: i,
                violations: Vec::new(),
            })
            .collect()
    }

    // --- Rule 1: Beyond limits ---

    #[test]
    fn test_rule1_point_above_ucl() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let points = make_points(&[25.0, 31.0, 25.0]);
        let violations = check_rule1(&points, &limits);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].0, 1);
        assert_eq!(violations[0].1, ViolationType::BeyondLimits);
    }

    #[test]
    fn test_rule1_point_below_lcl() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let points = make_points(&[25.0, 19.0, 25.0]);
        let violations = check_rule1(&points, &limits);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].0, 1);
    }

    #[test]
    fn test_rule1_on_limit_is_not_violation() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let points = make_points(&[30.0, 20.0]);
        let violations = check_rule1(&points, &limits);
        assert!(violations.is_empty());
    }

    // --- Rule 2: 9 on same side ---

    #[test]
    fn test_rule2_nine_above() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        // 9 points above center line
        let values: Vec<f64> = (0..9).map(|_| 26.0).collect();
        let points = make_points(&values);
        let violations = check_one_side(&points, &limits, 9, ViolationType::NineOneSide);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].1, ViolationType::NineOneSide);
    }

    #[test]
    fn test_rule2_eight_not_enough() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let values: Vec<f64> = (0..8).map(|_| 26.0).collect();
        let points = make_points(&values);
        let violations = check_one_side(&points, &limits, 9, ViolationType::NineOneSide);
        assert!(violations.is_empty());
    }

    #[test]
    fn test_rule2_nine_below() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let values: Vec<f64> = (0..9).map(|_| 24.0).collect();
        let points = make_points(&values);
        let violations = check_one_side(&points, &limits, 9, ViolationType::NineOneSide);
        assert_eq!(violations.len(), 1);
    }

    // --- Western Electric run rule: 8 on one side ---

    /// Eight points above the centre line: the Western Electric set signals at
    /// the eighth point, Nelson's (nine) does not -- the one test where the two
    /// sets disagree.
    #[test]
    fn western_electric_run_is_eight_points_nelson_is_nine() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let points = make_points(&[26.0; 8]);

        let we = RuleSet::western_electric().check(&points, &limits);
        assert_eq!(we, vec![(7, ViolationType::EightOneSide)]);
        assert!(RuleSet::nelson().check(&points, &limits).is_empty());
        assert_eq!(WesternElectricRules.check(&points, &limits), we);

        // Seven is not a run for either.
        let seven = make_points(&[26.0; 7]);
        assert!(RuleSet::western_electric()
            .check(&seven, &limits)
            .is_empty());
    }

    /// The default set is the 3-sigma test alone: a run that both named sets
    /// flag is not a signal until a set asks for it.
    #[test]
    fn default_set_is_the_three_sigma_test() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let mut values = vec![26.0; 12];
        values.push(31.0);
        let points = make_points(&values);

        assert_eq!(RuleSet::default(), RuleSet::shewhart());
        assert_eq!(
            RuleSet::default().check(&points, &limits),
            vec![(12, ViolationType::BeyondLimits)]
        );
        assert!(RuleSet::nelson().check(&points, &limits).len() > 1);
    }

    #[test]
    fn named_sets_round_trip_and_names_round_trip() {
        for name in RuleSet::NAMES {
            assert!(RuleSet::named(name).is_some(), "{name}");
        }
        assert_eq!(RuleSet::named("weco"), None);
        for v in ViolationType::ALL {
            assert_eq!(ViolationType::from_name(v.name()), Some(v));
        }
        let all: RuleSet = ViolationType::ALL.into_iter().collect();
        assert_eq!(all.len(), ViolationType::ALL.len());
    }

    // --- Rule 3: 6 trending ---

    #[test]
    fn test_rule3_six_increasing() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let points = make_points(&[20.0, 21.0, 22.0, 23.0, 24.0, 25.0]);
        let violations = check_rule3(&points, &limits);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].1, ViolationType::SixTrend);
    }

    #[test]
    fn test_rule3_six_decreasing() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let points = make_points(&[30.0, 29.0, 28.0, 27.0, 26.0, 25.0]);
        let violations = check_rule3(&points, &limits);
        assert_eq!(violations.len(), 1);
    }

    #[test]
    fn test_rule3_five_not_enough() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let points = make_points(&[20.0, 21.0, 22.0, 23.0, 24.0]);
        let violations = check_rule3(&points, &limits);
        assert!(violations.is_empty());
    }

    // --- Rule 4: 14 alternating ---

    #[test]
    fn test_rule4_fourteen_alternating() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        // Create alternating pattern: 24, 26, 24, 26, ...
        let values: Vec<f64> = (0..14)
            .map(|i| if i % 2 == 0 { 24.0 } else { 26.0 })
            .collect();
        let points = make_points(&values);
        let violations = check_rule4(&points, &limits);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].1, ViolationType::FourteenAlternating);
    }

    #[test]
    fn test_rule4_thirteen_not_enough() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let values: Vec<f64> = (0..13)
            .map(|i| if i % 2 == 0 { 24.0 } else { 26.0 })
            .collect();
        let points = make_points(&values);
        let violations = check_rule4(&points, &limits);
        assert!(violations.is_empty());
    }

    // --- Rule 5: 2 of 3 beyond 2σ ---

    #[test]
    fn test_rule5_two_of_three_above() {
        let limits = ControlLimits {
            ucl: 28.0, // σ = (28-25)/3 ≈ 1.0, 2σ = 2.0
            cl: 25.0,
            lcl: 22.0,
        };
        // 2σ line upper = 25 + 2 = 27, lower = 25 - 2 = 23
        // Two of three points above 27
        let points = make_points(&[27.5, 25.0, 27.5]);
        let violations = check_rule5(&points, &limits);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].1, ViolationType::TwoOfThreeBeyond2Sigma);
    }

    #[test]
    fn test_rule5_two_of_three_below() {
        let limits = ControlLimits {
            ucl: 28.0,
            cl: 25.0,
            lcl: 22.0,
        };
        // Two of three below CL - 2σ = 23
        let points = make_points(&[22.5, 25.0, 22.5]);
        let violations = check_rule5(&points, &limits);
        assert_eq!(violations.len(), 1);
    }

    // --- Rule 6: 4 of 5 beyond 1σ ---

    #[test]
    fn test_rule6_four_of_five_above() {
        let limits = ControlLimits {
            ucl: 28.0, // σ = 1.0
            cl: 25.0,
            lcl: 22.0,
        };
        // 1σ upper = 26. Four of five points above 26.
        let points = make_points(&[26.5, 26.5, 25.0, 26.5, 26.5]);
        let violations = check_rule6(&points, &limits);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].1, ViolationType::FourOfFiveBeyond1Sigma);
    }

    // --- Rule 7: 15 within 1σ ---

    #[test]
    fn test_rule7_fifteen_within() {
        let limits = ControlLimits {
            ucl: 28.0, // σ = 1.0
            cl: 25.0,
            lcl: 22.0,
        };
        // 15 points within CL ± σ = [24, 26]
        let values: Vec<f64> = (0..15).map(|i| 24.5 + (i as f64 % 3.0) * 0.25).collect();
        let points = make_points(&values);
        let violations = check_rule7(&points, &limits);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].1, ViolationType::FifteenWithin1Sigma);
    }

    // --- Rule 8: 8 beyond 1σ on either side ---

    #[test]
    fn test_rule8_eight_beyond() {
        let limits = ControlLimits {
            ucl: 28.0, // σ = 1.0
            cl: 25.0,
            lcl: 22.0,
        };
        // 8 points beyond CL ± σ (alternating sides is fine)
        let points = make_points(&[27.0, 23.0, 27.0, 23.0, 27.0, 23.0, 27.0, 23.0]);
        let violations = check_rule8(&points, &limits);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].1, ViolationType::EightBeyond1Sigma);
    }

    #[test]
    fn test_rule8_seven_not_enough() {
        let limits = ControlLimits {
            ucl: 28.0,
            cl: 25.0,
            lcl: 22.0,
        };
        let points = make_points(&[27.0, 23.0, 27.0, 23.0, 27.0, 23.0, 27.0]);
        let violations = check_rule8(&points, &limits);
        assert!(violations.is_empty());
    }

    // --- Western Electric Rules ---

    #[test]
    fn test_western_electric_combines_four_rules() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        // A point beyond limits triggers WE rules
        let points = make_points(&[25.0, 31.0, 25.0]);
        let we = WesternElectricRules;
        let violations = we.check(&points, &limits);
        assert!(!violations.is_empty());
        assert!(violations
            .iter()
            .any(|(_, v)| *v == ViolationType::BeyondLimits));
    }

    // --- Nelson Rules ---

    #[test]
    fn test_nelson_detects_trend() {
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let points = make_points(&[20.0, 21.0, 22.0, 23.0, 24.0, 25.0]);
        let nelson = NelsonRules;
        let violations = nelson.check(&points, &limits);
        assert!(violations
            .iter()
            .any(|(_, v)| *v == ViolationType::SixTrend));
    }

    #[test]
    fn test_nelson_no_violations_in_random_data() {
        let limits = ControlLimits {
            ucl: 28.0,
            cl: 25.0,
            lcl: 22.0,
        };
        // A short random-looking sequence should not trigger
        let points = make_points(&[25.5, 24.8, 25.2, 24.9, 25.1]);
        let nelson = NelsonRules;
        let violations = nelson.check(&points, &limits);
        assert!(violations.is_empty());
    }

    #[test]
    fn test_nelson_rule2_continuation() {
        // If 10 points on same side, rules fire at point 8 (index) and 9
        let limits = ControlLimits {
            ucl: 30.0,
            cl: 25.0,
            lcl: 20.0,
        };
        let values: Vec<f64> = (0..10).map(|_| 26.0).collect();
        let points = make_points(&values);
        let violations = check_one_side(&points, &limits, 9, ViolationType::NineOneSide);
        // Should fire at index 8 and 9
        assert_eq!(violations.len(), 2);
        assert_eq!(violations[0].0, 8);
        assert_eq!(violations[1].0, 9);
    }

    #[test]
    fn test_rule5_not_triggered_mixed_sides() {
        let limits = ControlLimits {
            ucl: 28.0,
            cl: 25.0,
            lcl: 22.0,
        };
        // One point above 2σ upper (>27), one below 2σ lower (<23) — different sides
        // Rule 5 requires 2 of 3 on the SAME side, so this should not trigger
        let points = make_points(&[27.5, 25.0, 22.5]);
        let violations = check_rule5(&points, &limits);
        assert!(violations.is_empty());
    }

    #[test]
    fn test_rule7_fourteen_not_enough() {
        let limits = ControlLimits {
            ucl: 28.0,
            cl: 25.0,
            lcl: 22.0,
        };
        let values: Vec<f64> = (0..14).map(|_| 25.5).collect();
        let points = make_points(&values);
        let violations = check_rule7(&points, &limits);
        assert!(violations.is_empty());
    }
}