gamlss-diagnostics 0.4.0

Post-fit diagnostics utilities for GAMLSS modeling
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
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
#![forbid(unsafe_code)]
//! Post-fit diagnostics utilities for Rust-native GAMLSS models.
//!
//! This crate is the intended home for diagnostics that are important for
//! GAMLSS parity but should not be part of the core [`gamlss_core::Family`]
//! contract.
//!
//! Current utilities include:
//!
//! - PIT/CDF residuals;
//! - ordered multivariate Rosenblatt residuals;
//! - CRPS summaries;
//! - reusable diagnostics views for prediction rows.
//!
//! Planned utilities include:
//!
//! - randomized quantile residuals;
//! - worm plot data;
//! - centile curve data;
//! - fitted parameter extraction helpers;
//! - distribution-level prediction helpers.
//!
//! The public surface intentionally grows through small extension APIs.
//! Distribution-specific capabilities should be expressed through extension
//! traits such as [`gamlss_core::HasCdf`] and [`gamlss_core::HasQuantile`],
//! while this crate provides post-fit utilities built on top of compiled model
//! predictions.
//!
//! ```
//! # use gamlss_core::{DenseDesign, Gamlss, Identity, Log, Mu, NoPenalty, ParameterBlock, ParameterBlocks, Sigma};
//! # use gamlss_diagnostics::prelude::*;
//! # use gamlss_family::Normal;
//! # let y = [0.0, 1.0, -1.0];
//! # let blocks = ParameterBlocks::new((
//! #     ParameterBlock::<Mu, _, _>::linear(DenseDesign::intercept(y.len()), NoPenalty, 0),
//! #     ParameterBlock::<Sigma, _, _>::linear(DenseDesign::intercept(y.len()), NoPenalty, 0),
//! # ));
//! # let model = Gamlss::try_new(Normal::<Identity, Log>::new(), blocks, &y)?;
//! let parameters = [0.0, 0.0];
//! let pit = model.pit_values(&parameters)?;
//! let residuals = model.quantile_residuals(&parameters)?;
//! # assert_eq!(pit.len(), residuals.len());
//! # Ok::<_, gamlss_core::ModelError>(())
//! ```

use gamlss_core::{
    Family, Gamlss, GamlssBlocks, HasCdf, HasCrps, HasMarginalCdf, HasObservationDimension,
    HasRosenblattTransform, ModelError, ObservationView, PredictionView,
};
use gamlss_special::unit_normal_quantile;

/// Common diagnostics imports.
pub mod prelude {
    pub use crate::{
        CdfDiagnosticsExt, CrpsDiagnosticsExt, MarginalCdfDiagnosticsExt, PredictionDiagnosticsExt,
        PredictionDiagnosticsView, PredictionRosenblattDiagnosticsExt, RosenblattDiagnosticsExt,
    };
}

/// Validated diagnostics view over prediction rows and observations.
///
/// This view is built from a core [`PredictionView`] plus an observation view,
/// validating the prediction observation length and observation invariants once.
/// Reuse it when computing multiple diagnostics over the same prediction rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PredictionDiagnosticsView<'a, 'obs, F, PBlocks, PObs> {
    prediction: PredictionView<'a, F, PBlocks>,
    obs: &'obs PObs,
}

impl<'a, 'obs, F, PBlocks, PObs> PredictionDiagnosticsView<'a, 'obs, F, PBlocks, PObs>
where
    F: for<'row> Family<Observation<'row> = f64>,
    PBlocks: GamlssBlocks<F>,
    PObs: ObservationView<'obs, Observation = f64> + 'obs,
{
    fn new(
        prediction: &PredictionView<'a, F, PBlocks>,
        obs: &'obs PObs,
    ) -> Result<Self, ModelError> {
        validate_prediction_observations(prediction.nrows(), obs)?;
        Ok(Self {
            prediction: *prediction,
            obs,
        })
    }

    /// Number of prediction rows.
    #[must_use]
    #[inline]
    pub const fn nrows(&self) -> usize {
        self.prediction.nrows()
    }

    /// Returns PIT values for the validated prediction rows.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` has the wrong length.
    pub fn pit_values(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError>
    where
        F: HasCdf,
    {
        let mut out = vec![0.0; self.nrows()];
        self.pit_values_into(parameters, &mut out)?;
        Ok(out)
    }

    /// Writes PIT values for the validated prediction rows into `out`.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` or `out` have the wrong length.
    pub fn pit_values_into(&self, parameters: &[f64], out: &mut [f64]) -> Result<(), ModelError>
    where
        F: HasCdf,
    {
        self.diagnostic_values_into(parameters, out, |family, observation, theta| {
            family.cdf(observation, theta)
        })
    }

    /// Returns normalized quantile residuals for the validated prediction rows.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` has the wrong length.
    pub fn quantile_residuals(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError>
    where
        F: HasCdf,
    {
        self.pit_values(parameters).map(normalize_pit_values)
    }

    /// Returns CRPS values for the validated prediction rows.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` has the wrong length.
    pub fn crps_values(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError>
    where
        F: HasCrps,
    {
        let mut out = vec![0.0; self.nrows()];
        self.crps_values_into(parameters, &mut out)?;
        Ok(out)
    }

    /// Writes CRPS values for the validated prediction rows into `out`.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` or `out` have the wrong length.
    pub fn crps_values_into(&self, parameters: &[f64], out: &mut [f64]) -> Result<(), ModelError>
    where
        F: HasCrps,
    {
        self.diagnostic_values_into(parameters, out, |family, observation, theta| {
            family.crps(observation, theta)
        })
    }

    fn diagnostic_values_into(
        &self,
        parameters: &[f64],
        out: &mut [f64],
        mut evaluate: impl FnMut(&F, f64, &F::Theta) -> f64,
    ) -> Result<(), ModelError> {
        validate_output_len(self.nrows(), out.len())?;
        self.prediction.for_each_theta(parameters, |row, theta| {
            out[row] = evaluate(
                self.prediction.family(),
                self.obs.observation_at(row),
                &theta,
            );
        })
    }
}

/// Explicit component-wise marginal PIT diagnostics for multivariate families.
pub trait MarginalCdfDiagnosticsExt<F, Blocks> {
    /// Returns marginal PIT values for one response coordinate.
    ///
    /// `observations` contains that coordinate in model row order. The explicit
    /// scalar slice prevents a joint multivariate CDF from being mistaken for a
    /// scalar PIT.
    fn marginal_pit_values(
        &self,
        parameters: &[f64],
        component: usize,
        observations: &[f64],
    ) -> Result<Vec<f64>, ModelError>;

    /// Writes marginal PIT values into `out`.
    fn marginal_pit_values_into(
        &self,
        parameters: &[f64],
        component: usize,
        observations: &[f64],
        out: &mut [f64],
    ) -> Result<(), ModelError>;
}

impl<F, Blocks, Obs> MarginalCdfDiagnosticsExt<F, Blocks> for Gamlss<F, Blocks, Obs>
where
    F: HasMarginalCdf + HasObservationDimension,
    Blocks: GamlssBlocks<F>,
    for<'obs> Obs: ObservationView<'obs, Observation = F::Observation<'obs>>,
{
    fn marginal_pit_values(
        &self,
        parameters: &[f64],
        component: usize,
        observations: &[f64],
    ) -> Result<Vec<f64>, ModelError> {
        let mut out = vec![0.0; self.nobs()];
        self.marginal_pit_values_into(parameters, component, observations, &mut out)?;
        Ok(out)
    }

    fn marginal_pit_values_into(
        &self,
        parameters: &[f64],
        component: usize,
        observations: &[f64],
        out: &mut [f64],
    ) -> Result<(), ModelError> {
        if component >= self.family().observation_dimension() {
            return Err(ModelError::InvalidParameter {
                parameter: "marginal PIT component",
                expected: "inside the family observation dimension",
            });
        }
        validate_output_len(self.nobs(), observations.len())?;
        validate_output_len(self.nobs(), out.len())?;
        self.for_each_theta(parameters, |row, theta| {
            out[row] = self
                .family()
                .marginal_cdf(component, observations[row], &theta);
        })
    }
}

/// Ordered multivariate PIT diagnostics for a validated core [`PredictionView`].
pub trait PredictionRosenblattDiagnosticsExt<F, PBlocks>
where
    F: HasRosenblattTransform,
    PBlocks: GamlssBlocks<F>,
{
    /// Returns row-major Rosenblatt values with one contiguous coordinate block per row.
    fn rosenblatt_values<'obs, PObs>(
        &self,
        parameters: &[f64],
        obs: &'obs PObs,
    ) -> Result<Vec<f64>, ModelError>
    where
        PObs: ObservationView<'obs, Observation = F::Observation<'obs>> + 'obs;

    /// Writes row-major Rosenblatt values into `out`.
    fn rosenblatt_values_into<'obs, PObs>(
        &self,
        parameters: &[f64],
        obs: &'obs PObs,
        out: &mut [f64],
    ) -> Result<(), ModelError>
    where
        PObs: ObservationView<'obs, Observation = F::Observation<'obs>> + 'obs;
}

impl<F, PBlocks> PredictionRosenblattDiagnosticsExt<F, PBlocks> for PredictionView<'_, F, PBlocks>
where
    F: HasRosenblattTransform,
    PBlocks: GamlssBlocks<F>,
{
    fn rosenblatt_values<'obs, PObs>(
        &self,
        parameters: &[f64],
        obs: &'obs PObs,
    ) -> Result<Vec<f64>, ModelError>
    where
        PObs: ObservationView<'obs, Observation = F::Observation<'obs>> + 'obs,
    {
        let len = checked_rosenblatt_len(self.nrows(), self.family().observation_dimension())?;
        let mut out = vec![0.0; len];
        self.rosenblatt_values_into(parameters, obs, &mut out)?;
        Ok(out)
    }

    fn rosenblatt_values_into<'obs, PObs>(
        &self,
        parameters: &[f64],
        obs: &'obs PObs,
        out: &mut [f64],
    ) -> Result<(), ModelError>
    where
        PObs: ObservationView<'obs, Observation = F::Observation<'obs>> + 'obs,
    {
        let nrows = self.nrows();
        let actual = obs.len();
        if actual != nrows {
            return Err(ModelError::ResponseLength {
                expected: nrows,
                actual,
            });
        }
        obs.validate()?;
        let dimension = self.family().observation_dimension();
        validate_output_len(checked_rosenblatt_len(nrows, dimension)?, out.len())?;

        let family = self.family();
        let mut transform_error = None;
        self.for_each_theta(parameters, |row, theta| {
            if transform_error.is_some() {
                return;
            }
            let start = row * dimension;
            transform_error = family
                .rosenblatt_into(
                    obs.observation_at(row),
                    &theta,
                    &mut out[start..start + dimension],
                )
                .err();
        })?;
        transform_error.map_or(Ok(()), Err)
    }
}

/// Ordered multivariate PIT diagnostics for fitted GAMLSS models.
pub trait RosenblattDiagnosticsExt<F, Blocks>
where
    F: HasRosenblattTransform,
    Blocks: GamlssBlocks<F>,
{
    /// Returns row-major Rosenblatt values for the training observations.
    ///
    /// Coordinate order is the family observation order and therefore also the
    /// conditioning order of the transform.
    fn rosenblatt_values(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError>;

    /// Writes row-major Rosenblatt values for the training observations into `out`.
    fn rosenblatt_values_into(&self, parameters: &[f64], out: &mut [f64])
    -> Result<(), ModelError>;

    /// Returns row-major Rosenblatt values for compatible prediction rows.
    fn rosenblatt_values_with_blocks<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
    ) -> Result<Vec<f64>, ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = F::Observation<'obs>> + 'obs;

    /// Writes row-major Rosenblatt values for compatible prediction rows into `out`.
    fn rosenblatt_values_with_blocks_into<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
        out: &mut [f64],
    ) -> Result<(), ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = F::Observation<'obs>> + 'obs;
}

impl<F, Blocks, Obs> RosenblattDiagnosticsExt<F, Blocks> for Gamlss<F, Blocks, Obs>
where
    F: HasRosenblattTransform,
    Blocks: GamlssBlocks<F>,
    for<'obs> Obs: ObservationView<'obs, Observation = F::Observation<'obs>>,
{
    fn rosenblatt_values(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError> {
        self.prediction_view(self.blocks())?
            .rosenblatt_values(parameters, self.obs())
    }

    fn rosenblatt_values_into(
        &self,
        parameters: &[f64],
        out: &mut [f64],
    ) -> Result<(), ModelError> {
        self.prediction_view(self.blocks())?
            .rosenblatt_values_into(parameters, self.obs(), out)
    }

    fn rosenblatt_values_with_blocks<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
    ) -> Result<Vec<f64>, ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = F::Observation<'obs>> + 'obs,
    {
        self.prediction_view(blocks)?
            .rosenblatt_values(parameters, obs)
    }

    fn rosenblatt_values_with_blocks_into<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
        out: &mut [f64],
    ) -> Result<(), ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = F::Observation<'obs>> + 'obs,
    {
        self.prediction_view(blocks)?
            .rosenblatt_values_into(parameters, obs, out)
    }
}

/// Diagnostics extension for a validated core [`PredictionView`].
pub trait PredictionDiagnosticsExt<F, PBlocks>
where
    F: for<'row> Family<Observation<'row> = f64>,
    PBlocks: GamlssBlocks<F>,
{
    /// Adds validated prediction observations to this prediction view.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `obs` has the wrong length or invalid
    /// observation/weight values.
    fn with_observations<'obs, PObs>(
        &self,
        obs: &'obs PObs,
    ) -> Result<PredictionDiagnosticsView<'_, 'obs, F, PBlocks, PObs>, ModelError>
    where
        PObs: ObservationView<'obs, Observation = f64> + 'obs;
}

impl<F, PBlocks> PredictionDiagnosticsExt<F, PBlocks> for PredictionView<'_, F, PBlocks>
where
    F: for<'row> Family<Observation<'row> = f64>,
    PBlocks: GamlssBlocks<F>,
{
    fn with_observations<'obs, PObs>(
        &self,
        obs: &'obs PObs,
    ) -> Result<PredictionDiagnosticsView<'_, 'obs, F, PBlocks, PObs>, ModelError>
    where
        PObs: ObservationView<'obs, Observation = f64> + 'obs,
    {
        PredictionDiagnosticsView::new(self, obs)
    }
}

/// CDF-based diagnostics for fitted GAMLSS models.
pub trait CdfDiagnosticsExt<F, Blocks>
where
    F: HasCdf + for<'row> Family<Observation<'row> = f64>,
    Blocks: GamlssBlocks<F>,
{
    /// Returns probability integral transform values for training rows.
    ///
    /// The returned vector has one value per training observation, in row
    /// order. Invalid observation or parameter domains are represented by the
    /// family CDF result, usually `NaN`, rather than an additional diagnostics
    /// error.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` has the wrong length.
    fn pit_values(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError>;

    /// Writes PIT values for training rows into an existing output slice.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` or `out` have the wrong length.
    fn pit_values_into(&self, parameters: &[f64], out: &mut [f64]) -> Result<(), ModelError>;

    /// Returns PIT values for supplied compatible prediction blocks and observations.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if parameters, prediction blocks, or observations
    /// are incompatible with the fitted model.
    fn pit_values_with_blocks<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
    ) -> Result<Vec<f64>, ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = f64> + 'obs;

    /// Writes PIT values for supplied prediction rows into an existing output slice.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if parameters, prediction blocks, observations,
    /// or `out` are incompatible with the fitted model.
    fn pit_values_with_blocks_into<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
        out: &mut [f64],
    ) -> Result<(), ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = f64> + 'obs;

    /// Returns normalized quantile residuals for training rows.
    ///
    /// For continuous distributions this is `Phi^-1(F(y_i; theta_i))`, where
    /// `Phi^-1` is the inverse standard-normal CDF and `F` is the family CDF.
    /// Non-finite and out-of-range PIT values propagate as `NaN`; PIT values at
    /// unit interval boundaries map to infinities.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` has the wrong length.
    fn quantile_residuals(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError> {
        self.pit_values(parameters).map(normalize_pit_values)
    }

    /// Returns normalized quantile residuals for supplied prediction rows.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if parameters, prediction blocks, or observations
    /// are incompatible with the fitted model.
    fn quantile_residuals_with_blocks<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
    ) -> Result<Vec<f64>, ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = f64> + 'obs,
    {
        self.pit_values_with_blocks(parameters, blocks, obs)
            .map(normalize_pit_values)
    }
}

impl<F, Blocks, Obs> CdfDiagnosticsExt<F, Blocks> for Gamlss<F, Blocks, Obs>
where
    F: HasCdf + for<'row> Family<Observation<'row> = f64>,
    Blocks: GamlssBlocks<F>,
    for<'row> Obs: ObservationView<'row, Observation = f64>,
{
    fn pit_values(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError> {
        let mut out = vec![0.0; self.nobs()];
        self.pit_values_into(parameters, &mut out)?;
        Ok(out)
    }

    fn pit_values_into(&self, parameters: &[f64], out: &mut [f64]) -> Result<(), ModelError> {
        diagnostic_values_into(self, parameters, out, |family, observation, theta| {
            family.cdf(observation, theta)
        })
    }

    fn pit_values_with_blocks<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
    ) -> Result<Vec<f64>, ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = f64> + 'obs,
    {
        let prediction = self.prediction_view(blocks)?;
        let diagnostics = prediction.with_observations(obs)?;
        let mut out = vec![0.0; diagnostics.nrows()];
        diagnostics.pit_values_into(parameters, &mut out)?;
        Ok(out)
    }

    fn pit_values_with_blocks_into<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
        out: &mut [f64],
    ) -> Result<(), ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = f64> + 'obs,
    {
        let prediction = self.prediction_view(blocks)?;
        prediction
            .with_observations(obs)?
            .pit_values_into(parameters, out)
    }
}

/// CRPS-based diagnostics for fitted GAMLSS models.
pub trait CrpsDiagnosticsExt<F, Blocks>
where
    F: HasCrps + for<'row> Family<Observation<'row> = f64>,
    Blocks: GamlssBlocks<F>,
{
    /// Returns CRPS values for training rows.
    ///
    /// The returned vector has one value per training observation, in row
    /// order. Invalid observation or parameter domains are represented by the
    /// family CRPS result, usually `NaN`.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` has the wrong length.
    fn crps_values(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError>;

    /// Writes CRPS values for training rows into an existing output slice.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` or `out` have the wrong length.
    fn crps_values_into(&self, parameters: &[f64], out: &mut [f64]) -> Result<(), ModelError>;

    /// Returns CRPS values for supplied compatible prediction blocks and observations.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if parameters, prediction blocks, or observations
    /// are incompatible with the fitted model.
    fn crps_values_with_blocks<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
    ) -> Result<Vec<f64>, ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = f64> + 'obs;

    /// Writes CRPS values for supplied prediction rows into an existing output slice.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if parameters, prediction blocks, observations,
    /// or `out` are incompatible with the fitted model.
    fn crps_values_with_blocks_into<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
        out: &mut [f64],
    ) -> Result<(), ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = f64> + 'obs;

    /// Returns the arithmetic mean of [`Self::crps_values`].
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` has the wrong length.
    #[allow(clippy::cast_precision_loss)]
    fn mean_crps(&self, parameters: &[f64]) -> Result<f64, ModelError> {
        let values = self.crps_values(parameters)?;
        Ok(values.iter().sum::<f64>() / values.len() as f64)
    }

    /// Returns the observation-weighted mean CRPS for training rows.
    ///
    /// If all observation weights are zero, returns `NaN`.
    ///
    /// # Errors
    ///
    /// Returns [`ModelError`] if `parameters` has the wrong length.
    fn weighted_mean_crps(&self, parameters: &[f64]) -> Result<f64, ModelError>;
}

impl<F, Blocks, Obs> CrpsDiagnosticsExt<F, Blocks> for Gamlss<F, Blocks, Obs>
where
    F: HasCrps + for<'row> Family<Observation<'row> = f64>,
    Blocks: GamlssBlocks<F>,
    for<'row> Obs: ObservationView<'row, Observation = f64>,
{
    fn crps_values(&self, parameters: &[f64]) -> Result<Vec<f64>, ModelError> {
        let mut out = vec![0.0; self.nobs()];
        self.crps_values_into(parameters, &mut out)?;
        Ok(out)
    }

    fn crps_values_into(&self, parameters: &[f64], out: &mut [f64]) -> Result<(), ModelError> {
        diagnostic_values_into(self, parameters, out, |family, observation, theta| {
            family.crps(observation, theta)
        })
    }

    fn crps_values_with_blocks<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
    ) -> Result<Vec<f64>, ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = f64> + 'obs,
    {
        let prediction = self.prediction_view(blocks)?;
        let diagnostics = prediction.with_observations(obs)?;
        let mut out = vec![0.0; diagnostics.nrows()];
        diagnostics.crps_values_into(parameters, &mut out)?;
        Ok(out)
    }

    fn crps_values_with_blocks_into<'obs, PBlocks, PObs>(
        &self,
        parameters: &[f64],
        blocks: &PBlocks,
        obs: &'obs PObs,
        out: &mut [f64],
    ) -> Result<(), ModelError>
    where
        PBlocks: GamlssBlocks<F>,
        PObs: ObservationView<'obs, Observation = f64> + 'obs,
    {
        let prediction = self.prediction_view(blocks)?;
        prediction
            .with_observations(obs)?
            .crps_values_into(parameters, out)
    }

    fn weighted_mean_crps(&self, parameters: &[f64]) -> Result<f64, ModelError> {
        let family = self.family();
        let obs = self.obs();
        let mut weighted_sum = 0.0;
        let mut weight_sum = 0.0;

        self.for_each_theta(parameters, |row, theta| {
            let weight = obs.weight_at(row);
            if weight == 0.0 {
                return;
            }

            let value = family.crps(obs.observation_at(row), &theta);
            weighted_sum = weight.mul_add(value, weighted_sum);
            weight_sum += weight;
        })?;

        Ok(weighted_sum / weight_sum)
    }
}

fn diagnostic_values_into<F, Blocks, Obs>(
    model: &Gamlss<F, Blocks, Obs>,
    parameters: &[f64],
    out: &mut [f64],
    mut evaluate: impl FnMut(&F, f64, &F::Theta) -> f64,
) -> Result<(), ModelError>
where
    F: for<'row> Family<Observation<'row> = f64>,
    Blocks: GamlssBlocks<F>,
    for<'row> Obs: ObservationView<'row, Observation = f64>,
{
    validate_output_len(model.nobs(), out.len())?;
    let family = model.family();
    let obs = model.obs();
    model.for_each_theta(parameters, |row, theta| {
        out[row] = evaluate(family, obs.observation_at(row), &theta);
    })
}

fn validate_prediction_observations<'obs, Obs>(
    expected: usize,
    obs: &'obs Obs,
) -> Result<(), ModelError>
where
    Obs: ObservationView<'obs, Observation = f64> + 'obs,
{
    let actual = obs.len();
    if actual != expected {
        return Err(ModelError::ResponseLength { expected, actual });
    }
    obs.validate()
}

const fn validate_output_len(expected: usize, actual: usize) -> Result<(), ModelError> {
    if actual == expected {
        Ok(())
    } else {
        Err(ModelError::ResponseLength { expected, actual })
    }
}

fn checked_rosenblatt_len(nrows: usize, dimension: usize) -> Result<usize, ModelError> {
    nrows
        .checked_mul(dimension)
        .ok_or(ModelError::ArithmeticOverflow {
            context: "row-major Rosenblatt diagnostics length",
        })
}

fn normalize_pit_values(mut values: Vec<f64>) -> Vec<f64> {
    for value in &mut values {
        *value = unit_normal_quantile(*value);
    }
    values
}

#[cfg(test)]
mod tests {
    use approx::assert_relative_eq;
    use gamlss_core::{
        CholeskyScale, DenseDesign, Gamlss, Identity, LinearPredictorBlock, Log,
        LowerTriangularParameterBlock, ModelError, Mu, NoPenalty, ParameterBlock, ParameterBlocks,
        Sigma, VectorParameterBlock,
    };
    use gamlss_family::{MvNormalCholeskyDefault, Normal};

    use super::{
        CdfDiagnosticsExt, CrpsDiagnosticsExt, PredictionDiagnosticsExt,
        PredictionRosenblattDiagnosticsExt, RosenblattDiagnosticsExt, normalize_pit_values,
    };

    type TestModel<'a> = Gamlss<
        Normal<Identity, Log>,
        ParameterBlocks<(
            ParameterBlock<Mu, LinearPredictorBlock<DenseDesign>, NoPenalty>,
            ParameterBlock<Sigma, LinearPredictorBlock<DenseDesign>, NoPenalty>,
        )>,
        &'a [f64],
    >;

    type WeightedTestModel<'a> = Gamlss<
        Normal<Identity, Log>,
        ParameterBlocks<(
            ParameterBlock<Mu, LinearPredictorBlock<DenseDesign>, NoPenalty>,
            ParameterBlock<Sigma, LinearPredictorBlock<DenseDesign>, NoPenalty>,
        )>,
        (&'a [f64], &'a [f64]),
    >;

    fn normal_intercept_model(y: &[f64]) -> TestModel<'_> {
        let blocks = ParameterBlocks::new((
            ParameterBlock::<Mu, _, _>::linear(DenseDesign::intercept(y.len()), NoPenalty, 0),
            ParameterBlock::<Sigma, _, _>::linear(DenseDesign::intercept(y.len()), NoPenalty, 0),
        ));

        Gamlss::try_new(Normal::<Identity, Log>::new(), blocks, y).expect("valid normal model")
    }

    fn weighted_normal_intercept_model<'a>(
        y: &'a [f64],
        weights: &'a [f64],
    ) -> WeightedTestModel<'a> {
        let blocks = ParameterBlocks::new((
            ParameterBlock::<Mu, _, _>::linear(DenseDesign::intercept(y.len()), NoPenalty, 0),
            ParameterBlock::<Sigma, _, _>::linear(DenseDesign::intercept(y.len()), NoPenalty, 0),
        ));

        Gamlss::try_new_weighted(Normal::<Identity, Log>::new(), blocks, y, weights)
            .expect("valid weighted normal model")
    }

    #[test]
    fn pit_values_use_training_observations_and_fitted_parameters() {
        let y = [0.0, 1.0, -1.0];
        let model = normal_intercept_model(&y);

        let pit = model.pit_values(&[0.0, 0.0]).expect("valid parameters");
        let mut pit_into = vec![f64::NAN; y.len()];
        model
            .pit_values_into(&[0.0, 0.0], &mut pit_into)
            .expect("valid parameters");

        assert_relative_eq!(pit[0], 0.5, epsilon = 1.0e-7);
        assert_relative_eq!(pit[1], 0.841_344_746, epsilon = 1.0e-7);
        assert_relative_eq!(pit[2], 0.158_655_254, epsilon = 1.0e-7);
        assert_eq!(pit_into, pit);
    }

    #[test]
    fn quantile_residuals_transform_pit_values_to_standard_normal_scale() {
        let y = [-1.0, 0.0, 1.0];
        let model = normal_intercept_model(&y);

        let residuals = model
            .quantile_residuals(&[0.0, 0.0])
            .expect("valid parameters");

        assert_relative_eq!(residuals[0], -1.0, epsilon = 1.0e-6);
        assert_relative_eq!(residuals[1], 0.0, epsilon = 1.0e-6);
        assert_relative_eq!(residuals[2], 1.0, epsilon = 1.0e-6);
    }

    #[test]
    fn quantile_residuals_map_invalid_and_boundary_pit_values() {
        let residuals = normalize_pit_values(vec![f64::NAN, -0.1, 0.0, 1.0, 1.1]);

        assert!(residuals[0].is_nan());
        assert!(residuals[1].is_nan());
        assert!(residuals[2].is_infinite());
        assert!(residuals[2].is_sign_negative());
        assert!(residuals[3].is_infinite());
        assert!(residuals[3].is_sign_positive());
        assert!(residuals[4].is_nan());
    }

    #[test]
    fn pit_values_reject_wrong_parameter_length() {
        let y = [0.0];
        let model = normal_intercept_model(&y);

        assert_eq!(
            model.pit_values(&[]).unwrap_err(),
            ModelError::BetaLength {
                expected: 2,
                actual: 0
            }
        );
        assert_eq!(
            model.pit_values_into(&[0.0, 0.0], &mut []).unwrap_err(),
            ModelError::ResponseLength {
                expected: 1,
                actual: 0
            }
        );
    }

    #[test]
    fn crps_values_use_training_observations_and_fitted_parameters() {
        let y = [0.0, 1.0];
        let model = normal_intercept_model(&y);

        let crps = model.crps_values(&[0.0, 0.0]).expect("valid parameters");
        let mut crps_into = vec![f64::NAN; y.len()];
        model
            .crps_values_into(&[0.0, 0.0], &mut crps_into)
            .expect("valid parameters");

        assert_relative_eq!(crps[0], 0.233_694_977_255_109_13, epsilon = 1.0e-12);
        assert_relative_eq!(crps[1], 0.602_441_357_627_616_5, epsilon = 1.0e-12);
        assert_eq!(crps_into, crps);
        assert_relative_eq!(
            model.mean_crps(&[0.0, 0.0]).expect("valid parameters"),
            crps[0].midpoint(crps[1]),
            epsilon = 1.0e-12
        );
    }

    #[test]
    fn diagnostics_with_blocks_match_training_helpers_for_training_blocks() {
        let y = [-1.0, 0.0, 1.0];
        let model = normal_intercept_model(&y);
        let parameters = [0.0, 0.0];
        let obs = &y[..];
        let prediction = model.prediction_view(model.blocks()).unwrap();
        let diagnostics = prediction.with_observations(&obs).unwrap();

        assert_eq!(
            model
                .pit_values_with_blocks(&parameters, model.blocks(), &obs)
                .unwrap(),
            model.pit_values(&parameters).unwrap()
        );
        assert_eq!(
            diagnostics.pit_values(&parameters).unwrap(),
            model.pit_values(&parameters).unwrap()
        );
        assert_eq!(
            model
                .quantile_residuals_with_blocks(&parameters, model.blocks(), &obs)
                .unwrap(),
            model.quantile_residuals(&parameters).unwrap()
        );
        assert_eq!(
            diagnostics.quantile_residuals(&parameters).unwrap(),
            model.quantile_residuals(&parameters).unwrap()
        );
        assert_eq!(
            model
                .crps_values_with_blocks(&parameters, model.blocks(), &obs)
                .unwrap(),
            model.crps_values(&parameters).unwrap()
        );
        assert_eq!(
            diagnostics.crps_values(&parameters).unwrap(),
            model.crps_values(&parameters).unwrap()
        );

        let mut pit = vec![f64::NAN; diagnostics.nrows()];
        diagnostics.pit_values_into(&parameters, &mut pit).unwrap();
        assert_eq!(pit, model.pit_values(&parameters).unwrap());

        let mut crps = vec![f64::NAN; diagnostics.nrows()];
        diagnostics
            .crps_values_into(&parameters, &mut crps)
            .unwrap();
        assert_eq!(crps, model.crps_values(&parameters).unwrap());
    }

    #[test]
    fn diagnostics_with_blocks_reject_observation_row_mismatch() {
        let y = [0.0, 1.0];
        let model = normal_intercept_model(&y);
        let obs = &[0.0][..];

        assert_eq!(
            model
                .pit_values_with_blocks(&[0.0, 0.0], model.blocks(), &obs)
                .unwrap_err(),
            ModelError::ResponseLength {
                expected: 2,
                actual: 1
            }
        );
    }

    #[test]
    fn weighted_mean_crps_uses_observation_weights() {
        let y = [0.0, 1.0];
        let weights = [0.0, 2.0];
        let model = weighted_normal_intercept_model(&y, &weights);
        let crps = model.crps_values(&[0.0, 0.0]).unwrap();

        assert_relative_eq!(
            model.weighted_mean_crps(&[0.0, 0.0]).unwrap(),
            crps[1],
            epsilon = 1.0e-12
        );
    }

    #[test]
    fn weighted_mean_crps_skips_zero_weighted_observations_before_crps() {
        let y = [f64::NAN, 1.0];
        let weights = [0.0, 2.0];
        let model = weighted_normal_intercept_model(&y, &weights);

        assert_relative_eq!(
            model.weighted_mean_crps(&[0.0, 0.0]).unwrap(),
            0.602_441_357_627_616_5,
            epsilon = 1.0e-12
        );
    }

    #[test]
    fn weighted_mean_crps_returns_nan_when_all_weights_are_zero() {
        let y = [0.0, 1.0];
        let weights = [0.0, 0.0];
        let model = weighted_normal_intercept_model(&y, &weights);

        assert!(model.weighted_mean_crps(&[0.0, 0.0]).unwrap().is_nan());
    }

    #[test]
    fn crps_values_reject_wrong_parameter_length() {
        let y = [0.0];
        let model = normal_intercept_model(&y);

        assert_eq!(
            model.crps_values(&[]).unwrap_err(),
            ModelError::BetaLength {
                expected: 2,
                actual: 0
            }
        );
        assert_eq!(
            model.crps_values_into(&[0.0, 0.0], &mut []).unwrap_err(),
            ModelError::ResponseLength {
                expected: 1,
                actual: 0
            }
        );
    }

    #[test]
    fn rosenblatt_diagnostics_use_row_major_coordinate_order() {
        let y = [[0.0, 0.0], [1.0, 1.5]];
        let n = y.len();
        let mu = VectorParameterBlock::<Mu, 2, _, _>::new(
            [
                LinearPredictorBlock::new(DenseDesign::intercept(n)),
                LinearPredictorBlock::new(DenseDesign::intercept(n)),
            ],
            NoPenalty,
            0,
        );
        let cholesky = LowerTriangularParameterBlock::<CholeskyScale, 2, _, _>::new(
            vec![
                LinearPredictorBlock::new(DenseDesign::intercept(n)),
                LinearPredictorBlock::new(DenseDesign::intercept(n)),
                LinearPredictorBlock::new(DenseDesign::intercept(n)),
            ],
            NoPenalty,
            0,
        );
        let blocks = ParameterBlocks::new((mu, cholesky));
        let model = Gamlss::try_new_with_observations(
            MvNormalCholeskyDefault::<2>::new(),
            blocks,
            y.as_slice(),
        )
        .unwrap();
        let parameters = [0.0, 0.0, 0.0, 0.5, 0.0];

        let values = model.rosenblatt_values(&parameters).unwrap();
        assert_eq!(values.len(), 4);
        assert_relative_eq!(values[0], 0.5, epsilon = 1.0e-12);
        assert_relative_eq!(values[1], 0.5, epsilon = 1.0e-12);
        assert_relative_eq!(values[2], 0.841_344_746, epsilon = 1.0e-9);
        assert_relative_eq!(values[3], 0.841_344_746, epsilon = 1.0e-9);

        let prediction = model.prediction_view(model.blocks()).unwrap();
        assert_eq!(
            prediction
                .rosenblatt_values(&parameters, &y.as_slice())
                .unwrap(),
            values
        );
        assert_eq!(
            model
                .rosenblatt_values_with_blocks(&parameters, model.blocks(), &y.as_slice())
                .unwrap(),
            values
        );
        assert_eq!(
            model
                .rosenblatt_values_into(&parameters, &mut [0.0; 3])
                .unwrap_err(),
            ModelError::ResponseLength {
                expected: 4,
                actual: 3,
            }
        );
    }

    #[test]
    fn diagnostics_prelude_exposes_extension_traits() {
        use crate::prelude::*;

        let y = [0.0];
        let model = normal_intercept_model(&y);

        assert_relative_eq!(
            model.pit_values(&[0.0, 0.0]).unwrap()[0],
            0.5,
            epsilon = 1.0e-7
        );
        assert_relative_eq!(
            model.quantile_residuals(&[0.0, 0.0]).unwrap()[0],
            0.0,
            epsilon = 1.0e-6
        );
        assert_relative_eq!(
            model.mean_crps(&[0.0, 0.0]).unwrap(),
            0.233_694_977_255_109_13,
            epsilon = 1.0e-12
        );
    }
}