numrs2 0.3.3

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
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
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
//! Advanced and specialized distribution methods for RandomState
//!
//! This module contains the more complex distribution sampling methods for RandomState,
//! including multivariate distributions, extreme value distributions, and other
//! specialized statistical distributions.

use crate::array::Array;
use crate::error::{NumRs2Error, Result};
use num_traits::{Float, NumCast, ToPrimitive};
use scirs2_core::random::prelude::*;
use scirs2_core::SliceRandomExt;
use scirs2_stats::distributions::{ChiSquare, Gamma, Normal, Poisson};
use scirs2_stats::Distribution;
use std::fmt::Debug;
use std::fmt::Display;

use super::state::RandomState;

impl RandomState {
    /// Generate random values from a multivariate normal distribution
    pub fn multivariate_normal<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        mean: &[T],
        cov: &Array<T>,
        size: Option<&[usize]>,
    ) -> Result<Array<T>> {
        if mean.is_empty() {
            return Err(NumRs2Error::InvalidOperation(
                "Mean vector cannot be empty".to_string(),
            ));
        }

        let n = mean.len();
        let cov_shape = cov.shape();

        if cov_shape.len() != 2 || cov_shape[0] != n || cov_shape[1] != n {
            return Err(NumRs2Error::InvalidOperation(
                format!("Covariance matrix must be square with dimensions matching mean vector length ({}), got shape {:?}", n, cov_shape)
            ));
        }

        // For simplicity, this implementation uses a basic approach:
        // 1. Generate standard normal samples
        // 2. Apply Cholesky decomposition of covariance matrix
        // 3. Transform standard normal samples and add the mean

        // First determine the output shape
        let mut out_shape = Vec::new();
        if let Some(size_shape) = size {
            out_shape.extend_from_slice(size_shape);
        }
        out_shape.push(n);

        let total_samples: usize = if out_shape.len() > 1 {
            out_shape[..out_shape.len() - 1].iter().product()
        } else {
            1
        };

        // Generate standard normal samples
        let mut result = Vec::with_capacity(total_samples * n);
        let _rng = self.get_rng()?;

        // Generate samples from standard normal distribution
        for _ in 0..total_samples * n {
            let standard_normal = Normal::new(0.0, 1.0)
                .expect("multivariate_normal: standard normal N(0,1) should always be valid");
            let val_f64: f64 = standard_normal.rvs(1).expect("normal sampling failed")[0];
            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert standard normal sample".to_string(),
                )
            })?;
            result.push(val);
        }

        // Compute the Cholesky decomposition of the covariance matrix
        let chol = cholesky_decomposition::<T>(&cov.to_vec(), n)?;

        // Transform standard normal samples using the Cholesky factor
        let mut transformed = vec![T::zero(); total_samples * n];
        for i in 0..total_samples {
            for j in 0..n {
                let mut sum = T::zero();
                for k in 0..=j {
                    sum = sum + chol[j * n + k] * result[i * n + k];
                }
                transformed[i * n + j] = sum + mean[j];
            }
        }

        Ok(Array::from_vec(transformed).reshape(&out_shape))
    }

    /// Generate random values from a multivariate normal distribution with rotation
    ///
    /// # Arguments
    ///
    /// * `mean` - Mean vector
    /// * `cov` - Covariance matrix
    /// * `size` - Optional shape of the output array
    /// * `rotation` - Optional rotation matrix
    ///
    /// # Returns
    ///
    /// An array of random values from the multivariate normal distribution with rotation
    pub fn multivariate_normal_with_rotation<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        mean: &[T],
        cov: &Array<T>,
        size: Option<&[usize]>,
        rotation: Option<&Array<T>>,
    ) -> Result<Array<T>> {
        if mean.is_empty() {
            return Err(NumRs2Error::InvalidOperation(
                "Mean vector cannot be empty".to_string(),
            ));
        }

        let n = mean.len();
        let cov_shape = cov.shape();

        if cov_shape.len() != 2 || cov_shape[0] != n || cov_shape[1] != n {
            return Err(NumRs2Error::InvalidOperation(
                format!("Covariance matrix must be square with dimensions matching mean vector length ({}), got shape {:?}", n, cov_shape)
            ));
        }

        // Check rotation matrix if provided
        if let Some(rot) = rotation {
            let rot_shape = rot.shape();
            if rot_shape.len() != 2 || rot_shape[0] != n || rot_shape[1] != n {
                return Err(NumRs2Error::InvalidOperation(
                    format!("Rotation matrix must be square with dimensions matching mean vector length ({}), got shape {:?}", n, rot_shape)
                ));
            }
        }

        // First determine the output shape
        let mut out_shape = Vec::new();
        if let Some(size_shape) = size {
            out_shape.extend_from_slice(size_shape);
        }
        out_shape.push(n);

        let total_samples: usize = if out_shape.len() > 1 {
            out_shape[..out_shape.len() - 1].iter().product()
        } else {
            1
        };

        // Generate standard normal samples
        let mut result = Vec::with_capacity(total_samples * n);
        let _rng = self.get_rng()?;

        // Generate samples from standard normal distribution
        for _ in 0..total_samples * n {
            let standard_normal = Normal::new(0.0, 1.0).expect(
                "multivariate_normal_with_rotation: standard normal N(0,1) should always be valid",
            );
            let val_f64: f64 = standard_normal.rvs(1).expect("normal sampling failed")[0];
            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert standard normal sample".to_string(),
                )
            })?;
            result.push(val);
        }

        // Compute the Cholesky decomposition of the covariance matrix
        let chol = cholesky_decomposition::<T>(&cov.to_vec(), n)?;

        // Apply rotation if provided
        let transform = if let Some(rot) = rotation {
            // Multiply rotation by Cholesky factor
            let rot_data = rot.to_vec();
            let mut rotated_chol = vec![T::zero(); n * n];

            // Matrix multiplication: rot * chol
            for i in 0..n {
                for j in 0..n {
                    for k in 0..n {
                        rotated_chol[i * n + j] =
                            rotated_chol[i * n + j] + rot_data[i * n + k] * chol[k * n + j];
                    }
                }
            }

            rotated_chol
        } else {
            chol
        };

        // Transform standard normal samples using the Cholesky factor or rotated factor
        let mut transformed = vec![T::zero(); total_samples * n];
        for i in 0..total_samples {
            for j in 0..n {
                let mut sum = T::zero();
                for k in 0..=j {
                    sum = sum + transform[j * n + k] * result[i * n + k];
                }
                transformed[i * n + j] = sum + mean[j];
            }
        }

        Ok(Array::from_vec(transformed).reshape(&out_shape))
    }

    /// Generate random values from a Laplace (double exponential) distribution
    pub fn laplace<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        loc: T,
        scale: T,
        shape: &[usize],
    ) -> Result<Array<T>> {
        if scale <= T::zero() {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Scale parameter must be positive, got {}",
                scale
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let loc_f64 = loc.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert location parameter to f64".to_string())
        })?;
        let scale_f64 = scale.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert scale parameter to f64".to_string())
        })?;

        // Use the inverse CDF method for generating Laplace random variables
        let mut rng = self.get_rng()?;

        for _ in 0..size {
            // Generate uniform random variable in (0, 1)
            let u = loop {
                let v = rng.random::<f64>();
                if v > 0.0 && v < 1.0 {
                    break v;
                }
            };

            // Transform using inverse CDF
            let val_f64 = if u < 0.5 {
                loc_f64 + scale_f64 * (u * 2.0).ln()
            } else {
                loc_f64 - scale_f64 * ((1.0 - u) * 2.0).ln()
            };

            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert Laplace sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a Gumbel distribution
    pub fn gumbel<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        loc: T,
        scale: T,
        shape: &[usize],
    ) -> Result<Array<T>> {
        if scale <= T::zero() {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Scale parameter must be positive, got {}",
                scale
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let loc_f64 = loc.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert location parameter to f64".to_string())
        })?;
        let scale_f64 = scale.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert scale parameter to f64".to_string())
        })?;

        // Use the inverse CDF method for generating Gumbel random variables
        let mut rng = self.get_rng()?;

        for _ in 0..size {
            // Generate uniform random variable in (0, 1)
            let u = loop {
                let v = rng.random::<f64>();
                if v > 0.0 && v < 1.0 {
                    break v;
                }
            };

            // Transform using inverse CDF: X = loc - scale * ln(-ln(U))
            let val_f64 = loc_f64 - scale_f64 * (-u.ln()).ln();

            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert Gumbel sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a logistic distribution
    pub fn logistic<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        loc: T,
        scale: T,
        shape: &[usize],
    ) -> Result<Array<T>> {
        if scale <= T::zero() {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Scale parameter must be positive, got {}",
                scale
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let loc_f64 = loc.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert location parameter to f64".to_string())
        })?;
        let scale_f64 = scale.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert scale parameter to f64".to_string())
        })?;

        // Use the inverse CDF method for generating logistic random variables
        let mut rng = self.get_rng()?;

        for _ in 0..size {
            // Generate uniform random variable in (0, 1)
            let u = loop {
                let v = rng.random::<f64>();
                if v > 0.0 && v < 1.0 {
                    break v;
                }
            };

            // Transform using inverse CDF: X = loc + scale * ln(u / (1 - u))
            let val_f64 = loc_f64 + scale_f64 * (u / (1.0 - u)).ln();

            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert logistic sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a rayleigh distribution
    pub fn rayleigh<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        scale: T,
        shape: &[usize],
    ) -> Result<Array<T>> {
        if scale <= T::zero() {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Scale parameter must be positive, got {}",
                scale
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let scale_f64 = scale.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert scale parameter to f64".to_string())
        })?;

        // Use the inverse CDF method for generating Rayleigh random variables
        let mut rng = self.get_rng()?;

        for _ in 0..size {
            // Generate uniform random variable in (0, 1)
            let u = loop {
                let v = rng.random::<f64>();
                if v > 0.0 && v < 1.0 {
                    break v;
                }
            };

            // Transform using inverse CDF: X = scale * sqrt(-2 * ln(1 - u))
            let val_f64 = scale_f64 * (-2.0 * (1.0 - u).ln()).sqrt();

            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert Rayleigh sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a Wald (inverse Gaussian) distribution
    pub fn wald<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        mean: T,
        scale: T,
        shape: &[usize],
    ) -> Result<Array<T>> {
        if mean <= T::zero() || scale <= T::zero() {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Mean and scale parameters must be positive, got mean={}, scale={}",
                mean, scale
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let mean_f64 = mean.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert mean parameter to f64".to_string())
        })?;
        let scale_f64 = scale.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert scale parameter to f64".to_string())
        })?;

        // Implementation uses the algorithm from:
        // https://www.r-project.org/conferences/DSC-2003/Proceedings/MichaelEJ.pdf
        let mut rng = self.get_rng()?;

        for _ in 0..size {
            // Generate a standard normal random variable
            let standard_normal =
                Normal::new(0.0, 1.0).expect("wald: standard normal N(0,1) should always be valid");
            let z: f64 = standard_normal.rvs(1).expect("normal sampling failed")[0];

            // Calculate intermediate values
            let y = z * z;
            let x1 = mean_f64 + (mean_f64 * mean_f64 * y) / (2.0 * scale_f64)
                - (mean_f64 / (2.0 * scale_f64))
                    * ((4.0 * mean_f64 * scale_f64 * y) + (mean_f64 * mean_f64 * y * y)).sqrt();

            // Generate a uniform random variable
            let u = rng.random::<f64>();

            // Based on acceptance criteria, either use x1 or its reciprocal transformation
            let val_f64 = if u <= mean_f64 / (mean_f64 + x1) {
                x1
            } else {
                mean_f64 * mean_f64 / x1
            };

            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert Wald sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a negative binomial distribution
    pub fn negative_binomial<T: NumCast + Clone + Debug>(
        &self,
        n: f64,
        p: f64,
        shape: &[usize],
    ) -> Result<Array<T>> {
        if n <= 0.0 || p <= 0.0 || p >= 1.0 {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Parameters must satisfy n > 0 and 0 < p < 1, got n={}, p={}",
                n, p
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let _rng = self.get_rng()?;

        // Generate negative binomial using gamma-poisson mixture
        for _ in 0..size {
            // 1. Generate gamma random variable with shape=n and scale=(1-p)/p
            let gamma_dist = Gamma::new(n, (1.0 - p) / p, 0.0).map_err(|e| {
                NumRs2Error::InvalidOperation(format!("Failed to create gamma distribution: {}", e))
            })?;

            let lambda = gamma_dist.rvs(1).expect("gamma sampling failed")[0];

            // 2. Generate Poisson random variable with mean=lambda
            let poisson_dist = Poisson::new(lambda, 0.0).map_err(|e| {
                NumRs2Error::InvalidOperation(format!(
                    "Failed to create poisson distribution: {}",
                    e
                ))
            })?;

            let val_u64 = poisson_dist.rvs(1).expect("distribution sampling failed")[0];
            let val = T::from(val_u64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert negative binomial sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a geometric distribution
    pub fn geometric<T: NumCast + Clone + Debug>(
        &self,
        p: f64,
        shape: &[usize],
    ) -> Result<Array<T>> {
        if p <= 0.0 || p > 1.0 {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Probability must be in (0, 1], got {}",
                p
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let mut rng = self.get_rng()?;

        // Generate geometric random variables using inverse transform method
        for _ in 0..size {
            // Generate uniform random variable in (0, 1)
            let u = loop {
                let v = rng.random::<f64>();
                if v > 0.0 && v < 1.0 {
                    break v;
                }
            };

            // Geometric(p) = floor(log(U) / log(1-p)) + 1
            let val_u64 = (u.ln() / (1.0 - p).ln()).floor() as u64 + 1;

            let val = T::from(val_u64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert geometric sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a multinomial distribution
    pub fn multinomial<T: NumCast + Clone + Debug>(
        &self,
        n: usize,
        pvals: &[f64],
        shape: Option<&[usize]>,
    ) -> Result<Array<T>> {
        if pvals.is_empty() {
            return Err(NumRs2Error::InvalidOperation(
                "Probability array cannot be empty".to_string(),
            ));
        }

        // Validate probabilities sum to approximately 1
        let p_sum: f64 = pvals.iter().sum();
        if (p_sum - 1.0).abs() > 1e-10 {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Probabilities must sum to 1, got sum={}",
                p_sum
            )));
        }

        // Validate all probabilities are non-negative
        for &p in pvals {
            if p < 0.0 {
                return Err(NumRs2Error::InvalidOperation(
                    "All probabilities must be non-negative".to_string(),
                ));
            }
        }

        let k = pvals.len(); // number of categories

        // First determine the output shape
        let mut out_shape = Vec::new();
        if let Some(size_shape) = shape {
            out_shape.extend_from_slice(size_shape);
        }
        out_shape.push(k);

        let total_samples: usize = if out_shape.len() > 1 {
            out_shape[..out_shape.len() - 1].iter().product()
        } else {
            1
        };

        let mut result = Vec::with_capacity(total_samples * k);
        let mut rng = self.get_rng()?;

        // Generate multinomial samples
        for _ in 0..total_samples {
            let mut sample = vec![0u64; k];

            // Generate n samples, where each sample falls into a category based on pvals
            for _ in 0..n {
                let u = rng.random::<f64>();
                let mut cumsum = 0.0;

                for i in 0..k {
                    cumsum += pvals[i];
                    if u <= cumsum {
                        sample[i] += 1;
                        break;
                    }
                }
            }

            // Convert u64 to target type T
            for count in sample {
                let val = T::from(count).ok_or_else(|| {
                    NumRs2Error::InvalidOperation(
                        "Failed to convert multinomial sample to target type".to_string(),
                    )
                })?;
                result.push(val);
            }
        }

        Ok(Array::from_vec(result).reshape(&out_shape))
    }

    /// Generate random values from a hypergeometric distribution
    pub fn hypergeometric<T: NumCast + Clone + Debug>(
        &self,
        ngood: usize,
        nbad: usize,
        nsample: usize,
        shape: &[usize],
    ) -> Result<Array<T>> {
        if nsample > ngood + nbad {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Cannot sample {} from population of size {}",
                nsample,
                ngood + nbad
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let _rng = self.get_rng()?;

        // Naive implementation using direct sampling
        for _ in 0..size {
            // Create a population with ngood ones and nbad zeros
            let mut population = vec![false; nbad];
            population.extend(vec![true; ngood]);

            // Shuffle the population
            population.shuffle(&mut thread_rng());

            // Count number of ones in the sample
            let count = population[..nsample].iter().filter(|&&x| x).count() as u64;

            let val = T::from(count).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert hypergeometric sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a zipf distribution
    pub fn zipf<T: NumCast + Clone + Debug>(&self, a: f64, shape: &[usize]) -> Result<Array<T>> {
        if a <= 1.0 {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Parameter a must be > 1.0, got {}",
                a
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let mut rng = self.get_rng()?;

        // Implementation of Zipf distribution using rejection sampling
        // Based on algorithm from Luc Devroye's book "Non-Uniform Random Variate Generation"
        let b = 2.0f64.powf(a - 1.0);

        for _ in 0..size {
            // Initialize x variable
            let mut x: u64;
            let mut t: f64;

            loop {
                // Generate uniform variables
                let u = rng.random::<f64>();
                let v = rng.random::<f64>();

                // Initial candidate
                x = (u.powf(-1.0 / (a - 1.0))) as u64;
                if x < 1 {
                    x = 1;
                }

                // Acceptance-rejection test
                t = (1.0 + 1.0 / x as f64).powf(a - 1.0);
                if v * x as f64 * (t - 1.0) / (b - 1.0) <= t / b {
                    break;
                }
            }

            let val = T::from(x).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert zipf sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a logseries distribution
    pub fn logseries<T: NumCast + Clone + Debug>(
        &self,
        p: f64,
        shape: &[usize],
    ) -> Result<Array<T>> {
        if p <= 0.0 || p >= 1.0 {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Parameter p must be in (0, 1), got {}",
                p
            )));
        }

        let size: usize = shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let mut rng = self.get_rng()?;

        // Implementation using rejection method
        let r = (-p / (1.0 - p)).ln();

        for _ in 0..size {
            let mut x: u64;

            loop {
                // Generate uniform random variable
                let u = rng.random::<f64>();

                // Generate geometric random variable
                let v = rng.random::<f64>();
                x = (1.0 + (v.ln() / r).floor()) as u64;

                // Accept with probability x/(x+1)
                if u <= x as f64 / (x as f64 + 1.0) {
                    break;
                }
            }

            let val = T::from(x).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert logseries sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(shape))
    }

    /// Generate random values from a multivariate t-distribution
    ///
    /// The multivariate t-distribution is a generalization of the Student's t-distribution
    /// to multiple dimensions. It's characterized by a mean vector, covariance matrix,
    /// and degrees of freedom parameter.
    ///
    /// # Arguments
    ///
    /// * `mean` - Mean vector (length n)
    /// * `cov` - Covariance matrix (n x n, must be positive definite)
    /// * `df` - Degrees of freedom (must be positive)
    /// * `size` - Optional shape of the output array
    ///
    /// # Returns
    ///
    /// An array of random values from the multivariate t-distribution
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Mean vector is empty
    /// - Covariance matrix is not square or doesn't match mean vector dimensions
    /// - Covariance matrix is not positive definite
    /// - Degrees of freedom is not positive
    pub fn multivariate_t<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        mean: &[T],
        cov: &Array<T>,
        df: T,
        size: Option<&[usize]>,
    ) -> Result<Array<T>> {
        if mean.is_empty() {
            return Err(NumRs2Error::InvalidOperation(
                "Mean vector cannot be empty".to_string(),
            ));
        }

        if df <= T::zero() {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Degrees of freedom must be positive, got {}",
                df
            )));
        }

        let n = mean.len();
        let cov_shape = cov.shape();

        if cov_shape.len() != 2 || cov_shape[0] != n || cov_shape[1] != n {
            return Err(NumRs2Error::InvalidOperation(
                format!("Covariance matrix must be square with dimensions matching mean vector length ({}), got shape {:?}", n, cov_shape)
            ));
        }

        // Multivariate t-distribution is generated as:
        // X = mu + Y / sqrt(U/nu)
        // where Y ~ N(0, Sigma) and U ~ chi-squared(nu) are independent

        // First determine the output shape
        let mut out_shape = Vec::new();
        if let Some(size_shape) = size {
            out_shape.extend_from_slice(size_shape);
        }
        out_shape.push(n);

        let total_samples: usize = if out_shape.len() > 1 {
            out_shape[..out_shape.len() - 1].iter().product()
        } else {
            1
        };

        // Generate samples from standard normal distribution
        let mut normal_samples = Vec::with_capacity(total_samples * n);
        let df_f64 = df.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert df to f64".to_string())
        })?;

        let normal_dist = Normal::new(0.0, 1.0).map_err(|e| {
            NumRs2Error::InvalidOperation(format!("Failed to create normal distribution: {}", e))
        })?;

        let chi_square_dist = ChiSquare::new(df_f64, 0.0, 1.0).map_err(|e| {
            NumRs2Error::InvalidOperation(format!(
                "Failed to create chi-square distribution: {}",
                e
            ))
        })?;

        let _rng = self.get_rng()?;

        for _ in 0..total_samples * n {
            let val_f64 = normal_dist.rvs(1).map_err(|e| {
                NumRs2Error::InvalidOperation(format!("Failed to sample from normal: {}", e))
            })?[0];
            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert normal sample to target type".to_string(),
                )
            })?;
            normal_samples.push(val);
        }

        // Compute Cholesky decomposition of covariance matrix
        let chol = cholesky_decomposition::<T>(&cov.to_vec(), n)?;

        // Generate chi-square samples and transform
        let mut result = vec![T::zero(); total_samples * n];
        for i in 0..total_samples {
            // Generate chi-square sample
            let chi_val = chi_square_dist.rvs(1).map_err(|e| {
                NumRs2Error::InvalidOperation(format!("Failed to sample from chi-square: {}", e))
            })?[0];
            let scale_factor = T::from((df_f64 / chi_val).sqrt()).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert scale factor to target type".to_string(),
                )
            })?;

            // Transform normal samples using Cholesky factor and scale
            for j in 0..n {
                let mut sum = T::zero();
                for k in 0..=j {
                    sum = sum + chol[j * n + k] * normal_samples[i * n + k];
                }
                result[i * n + j] = mean[j] + sum * scale_factor;
            }
        }

        Ok(Array::from_vec(result).reshape(&out_shape))
    }

    /// Generate random values from a Wishart distribution
    ///
    /// The Wishart distribution is a generalization of the chi-squared distribution to
    /// positive-definite matrices. It's commonly used as the conjugate prior for the
    /// precision matrix (inverse covariance) in multivariate normal distributions.
    ///
    /// # Arguments
    ///
    /// * `df` - Degrees of freedom (must be >= dimension of scale matrix)
    /// * `scale` - Scale matrix (positive definite, p x p)
    /// * `size` - Optional shape of the output array
    ///
    /// # Returns
    ///
    /// An array of random positive-definite matrices from the Wishart distribution
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Scale matrix is not square
    /// - Scale matrix is not positive definite
    /// - Degrees of freedom is less than the dimension
    pub fn wishart<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        df: T,
        scale: &Array<T>,
        size: Option<&[usize]>,
    ) -> Result<Array<T>> {
        let scale_shape = scale.shape();

        if scale_shape.len() != 2 || scale_shape[0] != scale_shape[1] {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Scale matrix must be square, got shape {:?}",
                scale_shape
            )));
        }

        let p = scale_shape[0];
        let df_val = df.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert df to f64".to_string())
        })?;

        if df_val < p as f64 {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Degrees of freedom ({}) must be >= dimension of scale matrix ({})",
                df_val, p
            )));
        }

        // Compute Cholesky decomposition of scale matrix
        let chol = cholesky_decomposition::<T>(&scale.to_vec(), p)?;

        // Determine output shape
        let mut out_shape = Vec::new();
        if let Some(size_shape) = size {
            out_shape.extend_from_slice(size_shape);
        }
        out_shape.push(p);
        out_shape.push(p);

        let total_samples: usize = if out_shape.len() > 2 {
            out_shape[..out_shape.len() - 2].iter().product()
        } else {
            1
        };

        let mut result = Vec::with_capacity(total_samples * p * p);

        // Use Bartlett decomposition method
        // Generate each Wishart matrix independently
        for _ in 0..total_samples {
            // Create Bartlett matrix A (lower triangular)
            let mut a = vec![T::zero(); p * p];
            let _rng = self.get_rng()?;

            // Fill diagonal with chi-distributed values
            for i in 0..p {
                let chi_df = df_val - i as f64;
                let chi_dist = ChiSquare::new(chi_df, 0.0, 1.0).map_err(|e| {
                    NumRs2Error::InvalidOperation(format!(
                        "Failed to create chi-square distribution: {}",
                        e
                    ))
                })?;
                let chi_val = chi_dist.rvs(1).map_err(|e| {
                    NumRs2Error::InvalidOperation(format!(
                        "Failed to sample from chi-square: {}",
                        e
                    ))
                })?[0];
                a[i * p + i] = T::from(chi_val.sqrt()).ok_or_else(|| {
                    NumRs2Error::InvalidOperation("Failed to convert chi-square sample".to_string())
                })?;
            }

            // Fill lower triangle with standard normal values
            let normal_dist = Normal::new(0.0, 1.0).map_err(|e| {
                NumRs2Error::InvalidOperation(format!(
                    "Failed to create normal distribution: {}",
                    e
                ))
            })?;

            for i in 1..p {
                for j in 0..i {
                    let norm_val = normal_dist.rvs(1).map_err(|e| {
                        NumRs2Error::InvalidOperation(format!(
                            "Failed to sample from normal: {}",
                            e
                        ))
                    })?[0];
                    a[i * p + j] = T::from(norm_val).ok_or_else(|| {
                        NumRs2Error::InvalidOperation("Failed to convert normal sample".to_string())
                    })?;
                }
            }

            // Compute L * A where L is Cholesky factor of scale matrix
            let mut la = vec![T::zero(); p * p];
            for i in 0..p {
                for j in 0..=i {
                    let mut sum = T::zero();
                    for k in 0..=j.min(i) {
                        sum = sum + chol[i * p + k] * a[j * p + k];
                    }
                    la[i * p + j] = sum;
                }
            }

            // Compute result = L * A * A^T * L^T = (L * A) * (L * A)^T
            for i in 0..p {
                for j in 0..=i {
                    let mut sum = T::zero();
                    for k in 0..p {
                        sum = sum + la[i * p + k] * la[j * p + k];
                    }
                    result.push(sum);
                    if i != j {
                        result.push(sum); // Symmetric matrix
                    }
                }
            }
        }

        Ok(Array::from_vec(result).reshape(&out_shape))
    }

    /// Generate random values from a Frechet distribution
    ///
    /// The Frechet distribution (Type II extreme value distribution) is used in extreme
    /// value theory to model the maximum of a large sample of random variables.
    ///
    /// # Arguments
    ///
    /// * `shape` - Shape parameter (alpha, must be positive)
    /// * `loc` - Location parameter
    /// * `scale` - Scale parameter (must be positive)
    /// * `output_shape` - Shape of the output array
    ///
    /// # Returns
    ///
    /// An array of random values from the Frechet distribution
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Shape parameter is not positive
    /// - Scale parameter is not positive
    pub fn frechet<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        shape: T,
        loc: T,
        scale: T,
        output_shape: &[usize],
    ) -> Result<Array<T>> {
        if shape <= T::zero() {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Shape parameter must be positive, got {}",
                shape
            )));
        }

        if scale <= T::zero() {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Scale parameter must be positive, got {}",
                scale
            )));
        }

        let size: usize = output_shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let mut rng = self.get_rng()?;

        let shape_f64 = shape.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert shape to f64".to_string())
        })?;
        let loc_f64 = loc.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert location to f64".to_string())
        })?;
        let scale_f64 = scale.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert scale to f64".to_string())
        })?;

        // Use inverse CDF method: F^{-1}(u) = loc + scale * (-ln(u))^{-1/alpha}
        for _ in 0..size {
            let u = loop {
                let v = rng.random::<f64>();
                if v > 0.0 && v < 1.0 {
                    break v;
                }
            };

            let val_f64 = loc_f64 + scale_f64 * (-u.ln()).powf(-1.0 / shape_f64);
            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert Frechet sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(output_shape))
    }

    /// Generate random values from a Generalized Extreme Value (GEV) distribution
    ///
    /// The GEV distribution combines three types of extreme value distributions:
    /// - Type I (Gumbel): xi = 0
    /// - Type II (Frechet): xi > 0
    /// - Type III (Weibull): xi < 0
    ///
    /// # Arguments
    ///
    /// * `shape` - Shape parameter (xi)
    /// * `loc` - Location parameter (mu)
    /// * `scale` - Scale parameter (sigma, must be positive)
    /// * `output_shape` - Shape of the output array
    ///
    /// # Returns
    ///
    /// An array of random values from the GEV distribution
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Scale parameter is not positive
    pub fn gev<T: Float + NumCast + Clone + Debug + Display>(
        &self,
        shape: T,
        loc: T,
        scale: T,
        output_shape: &[usize],
    ) -> Result<Array<T>> {
        if scale <= T::zero() {
            return Err(NumRs2Error::InvalidOperation(format!(
                "Scale parameter must be positive, got {}",
                scale
            )));
        }

        let size: usize = output_shape.iter().product();
        let mut vec = Vec::with_capacity(size);
        let mut rng = self.get_rng()?;

        let xi = shape.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert shape to f64".to_string())
        })?;
        let mu = loc.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert location to f64".to_string())
        })?;
        let sigma = scale.to_f64().ok_or_else(|| {
            NumRs2Error::InvalidOperation("Failed to convert scale to f64".to_string())
        })?;

        let xi_threshold = 1e-10; // Threshold for considering xi approximately 0

        // Use inverse CDF method
        for _ in 0..size {
            let u = loop {
                let v = rng.random::<f64>();
                if v > 0.0 && v < 1.0 {
                    break v;
                }
            };

            let val_f64 = if xi.abs() < xi_threshold {
                // Type I (Gumbel): x = mu - sigma * ln(-ln(u))
                mu - sigma * (-u.ln()).ln()
            } else {
                // Type II (Frechet, xi > 0) or Type III (Weibull, xi < 0):
                // x = mu + sigma * ((-ln(u))^{-xi} - 1) / xi
                mu + sigma * ((-u.ln()).powf(-xi) - 1.0) / xi
            };

            let val = T::from(val_f64).ok_or_else(|| {
                NumRs2Error::InvalidOperation(
                    "Failed to convert GEV sample to target type".to_string(),
                )
            })?;
            vec.push(val);
        }

        Ok(Array::from_vec(vec).reshape(output_shape))
    }
}

/// Compute Cholesky decomposition of a symmetric positive-definite matrix
///
/// Given a flat row-major matrix of size n x n, computes the lower triangular
/// matrix L such that A = L * L^T.
///
/// # Arguments
///
/// * `matrix_data` - Flat row-major matrix data
/// * `n` - Dimension of the matrix
///
/// # Returns
///
/// The lower triangular Cholesky factor as a flat row-major vector
fn cholesky_decomposition<T: Float + NumCast + Clone + Debug + Display>(
    matrix_data: &[T],
    n: usize,
) -> Result<Vec<T>> {
    let mut chol = vec![T::zero(); n * n];

    for i in 0..n {
        for j in 0..=i {
            let mut sum = T::zero();
            for k in 0..j {
                sum = sum + chol[i * n + k] * chol[j * n + k];
            }

            if i == j {
                let val = matrix_data[i * n + i] - sum;
                if val <= T::zero() {
                    return Err(NumRs2Error::InvalidOperation(
                        "Covariance matrix is not positive definite".to_string(),
                    ));
                }
                chol[i * n + j] = val.sqrt();
            } else {
                chol[i * n + j] = T::one() / chol[j * n + j] * (matrix_data[i * n + j] - sum);
            }
        }
    }

    Ok(chol)
}