Repository navigation
Expand file tree
/
Copy pathrand.v
More file actions
1678 lines (1569 loc) · 58.8 KB
/
Copy pathrand.v
File metadata and controls
1678 lines (1569 loc) · 58.8 KB
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
module vtl
import math
import rand
import rand.config
import vsl.blas as vsl_blas
import vsl.lapack as vsl_lapack
// RandomGenerator owns an independent pseudorandom stream for reproducible
// experiments that must not modify or depend on V's global random state.
pub struct RandomGenerator {
mut:
rng &rand.PRNG
}
// new_random_generator creates an independent generator initialized from seed.
pub fn new_random_generator(seed int) RandomGenerator {
mut rng := rand.new_default(config.PRNGConfigStruct{
seed_: [u32(seed), 0]
})
return RandomGenerator{
rng: rng
}
}
// free releases the generator's underlying pseudorandom engine.
pub fn (mut generator RandomGenerator) free() {
generator.rng.free()
}
// uniform returns f64 values in the [minimum, maximum) range.
pub fn (mut generator RandomGenerator) uniform(minimum f64, maximum f64, shape []int) !&Tensor[f64] {
if maximum < minimum {
return error('uniform: maximum must be greater than or equal to minimum')
}
mut result := zeros[f64](shape, TensorData{})
for i in 0 .. result.size {
result.set_nth(i, generator.rng.f64_in_range(minimum, maximum)!)
}
return result
}
// integers returns seeded int samples from [low, high).
pub fn (mut generator RandomGenerator) integers(low int, high int, shape []int) !&Tensor[int] {
return generator.integers_with_endpoint(low, high, shape, false)
}
// integers_with_endpoint returns seeded int samples from [low, high) or
// [low, high] when endpoint is true.
pub fn (mut generator RandomGenerator) integers_with_endpoint(low int, high int, shape []int, endpoint bool) !&Tensor[int] {
mut upper := high
if endpoint {
if high == max_int {
return error('integers: inclusive upper bound cannot be max_int')
}
upper++
}
if upper <= low {
return error('integers: upper bound must be greater than lower bound')
}
if low < 0 && upper >= 0 && upper > max_int + low {
return error('integers: requested range is too wide for the random generator')
}
mut result := zeros[int](shape, TensorData{})
for i in 0 .. result.size {
result.set_nth(i, int(generator.rng.i64_in_range(i64(low), i64(upper))!))
}
return result
}
// normal returns f64 values from a normal distribution with the given parameters.
pub fn (mut generator RandomGenerator) normal(shape []int, params NormalTensorData) !&Tensor[f64] {
if params.sigma <= 0 {
return error('normal: sigma must be positive')
}
mut result := zeros[f64](shape, TensorData{})
for i in 0 .. result.size {
result.set_nth(i, generator.rng.normal(config.NormalConfigStruct{
mu: params.mu
sigma: params.sigma
})!)
}
return result
}
// multivariate_normal draws samples with the requested mean and covariance.
// sample_shape describes the leading sample dimensions; the final output axis
// contains the variables. Positive-semidefinite covariance matrices are
// supported, including singular matrices.
pub fn (mut generator RandomGenerator) multivariate_normal(mean &Tensor[f64], covariance &Tensor[f64], sample_shape []int) !&Tensor[f64] {
n := mean.shape[0] or { return error('multivariate_normal: mean must be a non-empty vector') }
sample_count := validate_multivariate_normal_inputs(mean, covariance, sample_shape, n)!
factor := multivariate_normal_factor(covariance, n)!
mut standard := zeros[f64]([sample_count, n], TensorData{})
for i in 0 .. standard.size {
standard.set_nth(i, generator.rng.normal(config.NormalConfigStruct{})!)
}
return transform_multivariate_normal(mean, sample_shape, n, sample_count, factor, standard,
TensorData{})
}
// multivariate_normal draws samples with the requested mean and covariance
// using VTL's global random stream.
pub fn multivariate_normal(mean &Tensor[f64], covariance &Tensor[f64], sample_shape []int, params TensorData) !&Tensor[f64] {
n := mean.shape[0] or { return error('multivariate_normal: mean must be a non-empty vector') }
sample_count := validate_multivariate_normal_inputs(mean, covariance, sample_shape, n)!
factor := multivariate_normal_factor(covariance, n)!
mut standard := zeros[f64]([sample_count, n], params)
for i in 0 .. standard.size {
standard.set_nth(i, rand.normal(config.NormalConfigStruct{})!)
}
return transform_multivariate_normal(mean, sample_shape, n, sample_count, factor, standard,
params)
}
fn validate_multivariate_normal_inputs(mean &Tensor[f64], covariance &Tensor[f64], sample_shape []int, n int) !int {
if mean.rank() != 1 || n == 0 {
return error('multivariate_normal: mean must be a non-empty vector')
}
if covariance.rank() != 2 || covariance.shape[0] != n || covariance.shape[1] != n {
return error('multivariate_normal: covariance must be a square matrix matching the mean length')
}
if n > max_int / n {
return error('multivariate_normal: covariance dimensions are too large')
}
mut sample_count := 1
for dimension in sample_shape {
if dimension < 0 || (dimension > 0 && sample_count > max_int / dimension) {
return error('multivariate_normal: sample dimensions must be non-negative and fit in memory')
}
sample_count *= dimension
}
if sample_count > max_int / n {
return error('multivariate_normal: sample output is too large')
}
for i in 0 .. mean.size {
value := mean.get_nth(i)
if math.is_nan(value) || math.is_inf(value, 0) {
return error('multivariate_normal: mean values must be finite')
}
}
mut scale := 1.0
for row in 0 .. n {
for col in 0 .. n {
a := covariance.get_nth(row * n + col)
if math.is_nan(a) || math.is_inf(a, 0) {
return error('multivariate_normal: covariance values must be finite')
}
if math.abs(a) > scale {
scale = math.abs(a)
}
}
}
for row in 0 .. n {
for col in row + 1 .. n {
a := covariance.get_nth(row * n + col)
b := covariance.get_nth(col * n + row)
if math.abs(a - b) > 1e-10 * scale {
return error('multivariate_normal: covariance must be symmetric')
}
}
}
return sample_count
}
fn multivariate_normal_factor(covariance &Tensor[f64], n int) ![][]f64 {
mut matrix := [][]f64{len: n, init: []f64{len: n}}
mut scale := 1.0
for row in 0 .. n {
for col in 0 .. n {
value := 0.5 * (covariance.get_nth(row * n + col) + covariance.get_nth(col * n + row))
matrix[row][col] = value
if math.abs(value) > scale {
scale = math.abs(value)
}
}
}
eigenvalues := vsl_lapack.syev(mut matrix, .ev_compute, vsl_blas.Uplo.lower)!
mut factor := [][]f64{len: n, init: []f64{len: n}}
for component in 0 .. n {
if eigenvalues[component] < -1e-10 * scale {
return error('multivariate_normal: covariance must be positive semidefinite')
}
eigen_scale := math.sqrt(if eigenvalues[component] > 0 { eigenvalues[component] } else { 0 })
for row in 0 .. n {
factor[row][component] = matrix[row][component] * eigen_scale
}
}
return factor
}
fn transform_multivariate_normal(mean &Tensor[f64], sample_shape []int, n int, sample_count int, factor [][]f64, standard &Tensor[f64], params TensorData) !&Tensor[f64] {
mut output_shape := sample_shape.clone()
output_shape << n
mut values := []f64{len: sample_count * n}
for sample in 0 .. sample_count {
for row in 0 .. n {
mut value := mean.get_nth(row)
for component in 0 .. n {
value += factor[row][component] * standard.get_nth(sample * n + component)
}
values[sample * n + row] = value
}
}
return from_array[f64](values, output_shape, params)
}
// lognormal returns samples whose natural logarithm follows a normal
// distribution with the given mean and standard deviation.
pub fn (mut generator RandomGenerator) lognormal(mean f64, sigma f64, shape []int) !&Tensor[f64] {
if math.is_nan(mean) || math.is_inf(mean, 0) || sigma < 0 || math.is_nan(sigma)
|| math.is_inf(sigma, 0) {
return error('lognormal: mean must be finite and sigma must be finite and non-negative')
}
mut result := zeros[f64](shape, TensorData{})
for i in 0 .. result.size {
log_value := if sigma == 0 {
mean
} else {
generator.rng.normal(config.NormalConfigStruct{
mu: mean
sigma: sigma
})!
}
result.set_nth(i, math.exp(log_value))
}
return result
}
// bernoulli returns bool values sampled with the given probability of true.
pub fn (mut generator RandomGenerator) bernoulli(probability f64, shape []int) !&Tensor[bool] {
if probability < 0 || probability > 1 {
return error('bernoulli: probability must be in [0, 1]')
}
mut result := zeros[bool](shape, TensorData{})
for i in 0 .. result.size {
result.set_nth(i, generator.rng.bernoulli(probability)!)
}
return result
}
// binomial returns the number of successful trials in each sample using this
// generator's independent stream.
pub fn (mut generator RandomGenerator) binomial(trials int, probability f64, shape []int) !&Tensor[int] {
if trials < 0 {
return error('binomial: trials must be non-negative')
}
if probability < 0 || probability > 1 || math.is_nan(probability) || math.is_inf(probability, 0) {
return error('binomial: probability must be finite and in [0, 1]')
}
mut result := zeros[int](shape, TensorData{})
for i in 0 .. result.size {
result.set_nth(i, generator.rng.binomial(trials, probability)!)
}
return result
}
// negative_binomial counts failures before n successes using this generator's
// independent stream. n is the positive real-valued success threshold and p
// is the success probability for each trial.
pub fn (mut generator RandomGenerator) negative_binomial(n f64, probability f64, shape []int) !&Tensor[int] {
validate_negative_binomial_parameters(n, probability)!
mut rng := generator.rng
mut values := []int{len: size_from_shape(shape)}
for i in 0 .. values.len {
values[i] = sample_negative_binomial(n, probability, mut rng)!
}
return from_array[int](values, shape)
}
fn validate_negative_binomial_parameters(n f64, probability f64) ! {
if n <= 0 || math.is_nan(n) || math.is_inf(n, 0) {
return error('negative_binomial: n must be finite and positive')
}
if probability <= 0 || probability > 1 || math.is_nan(probability)
|| math.is_inf(probability, 0) {
return error('negative_binomial: probability must be finite and in (0, 1]')
}
if probability < 1 {
scale := (1 - probability) / probability
if math.is_inf(scale, 0) || scale <= 0 {
return error('negative_binomial: probability is too small for a finite sample scale')
}
}
}
fn sample_negative_binomial(n f64, probability f64, mut rng &rand.PRNG) !int {
if probability == 1 {
return 0
}
lambda := sample_gamma(n, (1 - probability) / probability, mut rng)!
validate_poisson_rate(lambda)!
return sample_poisson(lambda, mut rng)
}
// hypergeometric samples the number of good items in draws made without
// replacement from a population containing ngood good and nbad bad items.
pub fn (mut generator RandomGenerator) hypergeometric(ngood int, nbad int, nsample int, shape []int) !&Tensor[int] {
validate_hypergeometric_parameters(ngood, nbad, nsample)!
mut values := []int{len: size_from_shape(shape)}
total_population := ngood + nbad
sample_count := if nsample < total_population - nsample {
nsample
} else {
total_population - nsample
}
hrua_config := if sample_count > 10 && ngood > 0 && nbad > 0 {
hypergeometric_hrua_config(ngood, nbad, sample_count)
} else {
HypergeometricHruaConfig{}
}
for sample_index in 0 .. values.len {
mut selected_good := 0
if sample_count > 10 && ngood > 0 && nbad > 0 {
for {
x := open_unit_interval(generator.rng.f64_in_range(0.0, 1.0)!)
y := generator.rng.f64_in_range(0.0, 1.0)!
candidate, accepted := hypergeometric_hrua_candidate(hrua_config, sample_count, x,
y)
if accepted {
selected_good = candidate
break
}
}
} else {
mut remaining_good := f64(if ngood < nbad { ngood } else { nbad })
mut remaining := sample_count
d1 := total_population - sample_count
for remaining_good > 0 && remaining > 0 {
u := generator.rng.f64_in_range(0.0, 1.0)!
remaining_good = hypergeometric_hyp_update(remaining_good, d1, remaining, u)
remaining--
}
selected_good = int(f64(if ngood < nbad { ngood } else { nbad }) - remaining_good)
if ngood > nbad {
selected_good = sample_count - selected_good
}
}
// HRUA samples the minority of the sample and its complement. Reflect
// the result back to the requested sample if the complement was drawn.
selected_good = if sample_count == nsample {
selected_good
} else {
ngood - selected_good
}
values[sample_index] = selected_good
}
return from_array[int](values, shape)
}
// multinomial returns category counts for repeated samples from one
// categorical distribution. The final output axis contains the categories.
pub fn (mut generator RandomGenerator) multinomial(trials int, probabilities &Tensor[f64], sample_shape []int) !&Tensor[int] {
if trials < 0 {
return error('multinomial: trials must be non-negative')
}
if probabilities.size == 0 {
return error('multinomial: probabilities must not be empty')
}
mut values := probabilities.to_array()
mut total_probability := 0.0
for probability in values {
if probability < 0 || math.is_nan(probability) || math.is_inf(probability, 0) {
return error('multinomial: probabilities must be finite and non-negative')
}
total_probability += probability
}
if total_probability <= 0 || math.is_inf(total_probability, 0) {
return error('multinomial: probabilities must have a finite positive sum')
}
if math.abs(total_probability - 1.0) > 1e-12 {
return error('multinomial: probabilities must sum to one')
}
for i in 0 .. values.len {
values[i] /= total_probability
}
category_count := values.len
mut output_shape := sample_shape.clone()
output_shape << category_count
mut counts := []int{len: size_from_shape(output_shape)}
sample_count := size_from_shape(sample_shape)
for sample in 0 .. sample_count {
mut remaining_trials := trials
mut remaining_probability := 1.0
for category in 0 .. category_count - 1 {
probability := if remaining_probability <= 0 {
0.0
} else {
values[category] / remaining_probability
}
count := generator.rng.binomial(remaining_trials, math.min(probability, 1.0))!
counts[sample * category_count + category] = count
remaining_trials -= count
remaining_probability -= values[category]
}
counts[sample * category_count + category_count - 1] = remaining_trials
}
return from_array[int](counts, output_shape)
}
// exponential returns f64 samples from an exponential distribution with the
// given positive finite rate using this generator's independent stream.
pub fn (mut generator RandomGenerator) exponential(lambda f64, shape []int) !&Tensor[f64] {
if lambda <= 0 || math.is_nan(lambda) || math.is_inf(lambda, 0) {
return error('exponential: lambda must be finite and positive')
}
mut result := zeros[f64](shape, TensorData{})
for i in 0 .. result.size {
result.set_nth(i, generator.rng.exponential(lambda))
}
return result
}
// gumbel returns samples from a Gumbel distribution with the given location
// and non-negative scale using this generator's independent stream.
pub fn (mut generator RandomGenerator) gumbel(location f64, scale f64, shape []int) !&Tensor[f64] {
validate_location_scale(location, scale, 'gumbel')!
mut values := []f64{len: size_from_shape(shape), init: location}
if scale == 0 {
return from_array[f64](values, shape)
}
for i in 0 .. values.len {
u := open_unit_interval(generator.rng.f64_in_range(0.0, 1.0)!)
values[i] = sample_gumbel(location, scale, u)
}
return from_array[f64](values, shape)
}
// laplace returns samples from a Laplace distribution with the given location
// and non-negative scale using this generator's independent stream.
pub fn (mut generator RandomGenerator) laplace(location f64, scale f64, shape []int) !&Tensor[f64] {
validate_location_scale(location, scale, 'laplace')!
mut values := []f64{len: size_from_shape(shape), init: location}
if scale == 0 {
return from_array[f64](values, shape)
}
for i in 0 .. values.len {
u := open_unit_interval(generator.rng.f64_in_range(0.0, 1.0)!)
values[i] = sample_laplace(location, scale, u)
}
return from_array[f64](values, shape)
}
// cauchy returns samples from a Cauchy distribution with the given location
// and positive scale using this generator's independent stream.
pub fn (mut generator RandomGenerator) cauchy(location f64, scale f64, shape []int) !&Tensor[f64] {
validate_cauchy_parameters(location, scale)!
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
u := open_unit_interval(generator.rng.f64_in_range(0.0, 1.0)!)
values[i] = sample_cauchy(location, scale, u)
}
return from_array[f64](values, shape)
}
// wald returns samples from a Wald (inverse Gaussian) distribution with the
// given positive mean and positive scale using this generator's stream.
pub fn (mut generator RandomGenerator) wald(mean f64, scale f64, shape []int) !&Tensor[f64] {
validate_wald_parameters(mean, scale)!
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
z := generator.rng.normal(config.NormalConfigStruct{})!
u := open_unit_interval(generator.rng.f64_in_range(0.0, 1.0)!)
values[i] = sample_wald(mean, scale, z, u)
}
return from_array[f64](values, shape)
}
// logistic returns samples from a Logistic distribution with the given
// location and non-negative scale using this generator's independent stream.
pub fn (mut generator RandomGenerator) logistic(location f64, scale f64, shape []int) !&Tensor[f64] {
validate_location_scale(location, scale, 'logistic')!
mut values := []f64{len: size_from_shape(shape), init: location}
if scale == 0 {
return from_array[f64](values, shape)
}
for i in 0 .. values.len {
u := open_unit_interval(generator.rng.f64_in_range(0.0, 1.0)!)
values[i] = sample_logistic(location, scale, u)
}
return from_array[f64](values, shape)
}
// pareto returns samples from the standard Pareto distribution (minimum zero)
// with the given positive shape parameter and this generator's stream.
pub fn (mut generator RandomGenerator) pareto(shape_parameter f64, shape []int) !&Tensor[f64] {
validate_pareto_shape(shape_parameter)!
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
u := open_unit_interval(generator.rng.f64_in_range(0.0, 1.0)!)
values[i] = math.pow(1 - u, -1 / shape_parameter) - 1
}
return from_array[f64](values, shape)
}
// rayleigh returns samples from a Rayleigh distribution with non-negative
// scale and this generator's independent stream.
pub fn (mut generator RandomGenerator) rayleigh(scale f64, shape []int) !&Tensor[f64] {
validate_location_scale(0, scale, 'rayleigh')!
mut values := []f64{len: size_from_shape(shape)}
if scale == 0 {
return from_array[f64](values, shape)
}
for i in 0 .. values.len {
u := open_unit_interval(generator.rng.f64_in_range(0.0, 1.0)!)
values[i] = scale * math.sqrt(-2 * math.log(1 - u))
}
return from_array[f64](values, shape)
}
// triangular returns samples from a triangular distribution defined by its
// left endpoint, mode, right endpoint, and this generator's independent stream.
pub fn (mut generator RandomGenerator) triangular(left f64, mode f64, right f64, shape []int) !&Tensor[f64] {
validate_triangular_parameters(left, mode, right)!
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
u := open_unit_interval(generator.rng.f64_in_range(0.0, 1.0)!)
values[i] = sample_triangular(left, mode, right, u)
}
return from_array[f64](values, shape)
}
// geometric returns the number of Bernoulli trials needed for the first
// success, independently sampled from this generator. Results start at 1.
pub fn (mut generator RandomGenerator) geometric(probability f64, shape []int) !&Tensor[int] {
validate_geometric_probability(probability)!
mut result := zeros[int](shape, TensorData{})
for i in 0 .. result.size {
u := generator.rng.f64_in_range(0.0, 1.0)!
result.set_nth(i, geometric_sample(probability, u))
}
return result
}
// poisson returns integer event counts with the given finite, non-negative
// expected rate using this generator's independent stream.
pub fn (mut generator RandomGenerator) poisson(lambda f64, shape []int) !&Tensor[int] {
validate_poisson_rate(lambda)!
mut rng := generator.rng
mut values := []int{len: size_from_shape(shape)}
for i in 0 .. values.len {
values[i] = sample_poisson(lambda, mut rng)!
}
return from_array[int](values, shape)
}
fn sample_poisson(lambda f64, mut rng &rand.PRNG) !int {
if lambda == 0 {
return 0
}
// Knuth's product method is simple and fast when the expected count is small.
if lambda < 10 {
limit := math.exp(-lambda)
mut product := 1.0
mut count := 0
for product > limit {
count++
product *= rng.f64_in_range(0.0, 1.0)!
}
return count - 1
}
// Hörmann's PTRS transformed rejection method has constant expected work
// for large rates, unlike the product method whose cost grows with lambda.
ptrs := poisson_ptrs_config(lambda)
for _ in 0 .. 10000 {
u := rng.f64_in_range(0.0, 1.0)!
v := rng.f64_in_range(0.0, 1.0)!
candidate, accepted := sample_poisson_ptrs_candidate(ptrs, u, v)
if accepted {
return candidate
}
}
return error('poisson: rejection sampler did not converge')
}
// weibull returns samples from the unit-scale Weibull distribution. The
// positive shape parameter controls the distribution's tail and hazard rate.
pub fn (mut generator RandomGenerator) weibull(shape_parameter f64, shape []int) !&Tensor[f64] {
if shape_parameter <= 0 || math.is_nan(shape_parameter) || math.is_inf(shape_parameter, 0) {
return error('weibull: shape parameter must be finite and positive')
}
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
u := generator.rng.f64_in_range(0.0, 1.0)!
values[i] = math.pow(-math.log(1.0 - u), 1.0 / shape_parameter)
}
return from_array[f64](values, shape)
}
// chi_square returns samples from a chi-square distribution with the given
// positive degrees of freedom.
pub fn (mut generator RandomGenerator) chi_square(degrees_of_freedom f64, shape []int) !&Tensor[f64] {
validate_degrees_of_freedom(degrees_of_freedom, 'chi_square')!
mut rng := generator.rng
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
values[i] = sample_gamma(degrees_of_freedom / 2, 2, mut rng)!
}
return from_array[f64](values, shape)
}
// student_t returns samples from the standard Student's t distribution.
pub fn (mut generator RandomGenerator) student_t(degrees_of_freedom f64, shape []int) !&Tensor[f64] {
validate_degrees_of_freedom(degrees_of_freedom, 'student_t')!
mut rng := generator.rng
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
normal_sample := rng.normal(config.NormalConfigStruct{})!
chi_square_sample := sample_gamma(degrees_of_freedom / 2, 2, mut rng)!
if chi_square_sample <= 0 {
return error('student_t: sampled chi-square value underflowed to zero')
}
values[i] = normal_sample / math.sqrt(chi_square_sample / degrees_of_freedom)
}
return from_array[f64](values, shape)
}
// f_distribution returns samples from an F distribution with the specified
// numerator and denominator degrees of freedom.
pub fn (mut generator RandomGenerator) f_distribution(numerator_df f64, denominator_df f64, shape []int) !&Tensor[f64] {
validate_degrees_of_freedom(numerator_df, 'f_distribution')!
validate_degrees_of_freedom(denominator_df, 'f_distribution')!
mut rng := generator.rng
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
numerator := sample_gamma(numerator_df / 2, 2, mut rng)!
denominator := sample_gamma(denominator_df / 2, 2, mut rng)!
if denominator <= 0 {
return error('f_distribution: sampled denominator underflowed to zero')
}
values[i] = (numerator / numerator_df) / (denominator / denominator_df)
}
return from_array[f64](values, shape)
}
fn validate_degrees_of_freedom(degrees_of_freedom f64, distribution string) ! {
if degrees_of_freedom <= 0 || math.is_nan(degrees_of_freedom)
|| math.is_inf(degrees_of_freedom, 0) {
return error('${distribution}: degrees of freedom must be finite and positive')
}
}
// choice samples values from a tensor's flattened logical order. Without
// replacement, selected positions are unique; the same value may still occur
// more than once in the population.
pub fn (mut generator RandomGenerator) choice[T](population &Tensor[T], size int, replace bool) !&Tensor[T] {
if population.size == 0 {
return error('choice: population must not be empty')
}
if size < 0 {
return error('choice: sample size must be non-negative')
}
if !replace && size > population.size {
return error('choice: cannot sample more positions than the population without replacement')
}
mut selected := []T{len: size}
if replace {
for i in 0 .. size {
index := int(generator.rng.f64_in_range(0.0, f64(population.size))!)
selected[i] = population.get_nth(index)
}
} else {
mut positions := []int{len: population.size}
for index in 0 .. population.size {
positions[index] = index
}
for i in 0 .. size {
offset := int(generator.rng.f64_in_range(0.0, f64(population.size - i))!)
selected_position := i + offset
positions[i], positions[selected_position] = positions[selected_position], positions[i]
selected[i] = population.get_nth(positions[i])
}
}
return from_1d[T](selected)
}
// choice_weighted samples values from a tensor's flattened logical order in
// proportion to non-negative weights. Without replacement, each selected
// position is removed from the remaining weight distribution.
pub fn (mut generator RandomGenerator) choice_weighted[T](population &Tensor[T], weights &Tensor[f64], size int, replace bool) !&Tensor[T] {
if population.size == 0 {
return error('choice_weighted: population must not be empty')
}
if weights.size != population.size {
return error('choice_weighted: weights must match the flattened population size')
}
if size < 0 {
return error('choice_weighted: sample size must be non-negative')
}
if !replace && size > population.size {
return error('choice_weighted: cannot sample more positions than the population without replacement')
}
mut remaining := weights.to_array()
mut total_weight := 0.0
mut positive_weights := 0
for weight in remaining {
if weight < 0 || math.is_nan(weight) || math.is_inf(weight, 0) {
return error('choice_weighted: weights must be finite and non-negative')
}
total_weight += weight
if weight > 0 {
positive_weights++
}
}
if total_weight <= 0 || math.is_inf(total_weight, 0) {
return error('choice_weighted: weights must have a finite positive sum')
}
if !replace && size > positive_weights {
return error('choice_weighted: not enough positive weights for sampling without replacement')
}
mut selected := []T{len: size}
for draw in 0 .. size {
threshold := generator.rng.f64_in_range(0.0, total_weight)!
mut cumulative := 0.0
mut selected_index := -1
for index, weight in remaining {
if weight <= 0 {
continue
}
cumulative += weight
if threshold < cumulative {
selected_index = index
break
}
}
if selected_index < 0 {
for index, weight in remaining {
if weight > 0 {
selected_index = index
}
}
}
selected[draw] = population.get_nth(selected_index)
if !replace {
total_weight -= remaining[selected_index]
remaining[selected_index] = 0
}
}
return from_1d[T](selected)
}
// choice_axis samples complete slices along axis and replaces that axis by size.
pub fn (mut generator RandomGenerator) choice_axis[T](population &Tensor[T], size int, axis int, replace bool) !&Tensor[T] {
axis_index := random_sampling_axis(population, axis, 'choice_axis')!
mut positions := []int{len: population.shape[axis_index]}
for index in 0 .. positions.len {
positions[index] = index
}
position_tensor := from_1d[int](positions)!
selected := generator.choice[int](position_tensor, size, replace)!
return population.take(selected.to_array(), axis_index)
}
// choice_weighted_axis samples complete slices in proportion to non-negative
// axis weights and replaces that axis by size.
pub fn (mut generator RandomGenerator) choice_weighted_axis[T](population &Tensor[T], weights &Tensor[f64], size int, axis int, replace bool) !&Tensor[T] {
axis_index := random_sampling_axis(population, axis, 'choice_weighted_axis')!
if weights.rank() != 1 || weights.shape[0] != population.shape[axis_index] {
return error('choice_weighted_axis: weights must be one-dimensional and match the selected axis')
}
mut positions := []int{len: population.shape[axis_index]}
for index in 0 .. positions.len {
positions[index] = index
}
position_tensor := from_1d[int](positions)!
selected := generator.choice_weighted[int](position_tensor, weights, size, replace)!
return population.take(selected.to_array(), axis_index)
}
fn random_sampling_axis[T](population &Tensor[T], axis int, operation string) !int {
rank := population.rank()
if rank == 0 {
return error('${operation}: population must have at least one dimension')
}
axis_index := if axis < 0 { axis + rank } else { axis }
if axis_index < 0 || axis_index >= rank {
return error('${operation}: axis ${axis} is out of range for rank ${rank}')
}
if population.shape[axis_index] == 0 {
return error('${operation}: selected axis must not be empty')
}
return axis_index
}
// permutation returns the integers in [0, size) in a seeded random order.
pub fn (mut generator RandomGenerator) permutation(size int) !&Tensor[int] {
if size < 0 {
return error('permutation: size must be non-negative')
}
mut values := []int{len: size}
for i in 0 .. size {
values[i] = i
}
for i := size - 1; i > 0; i-- {
j := int(generator.rng.f64_in_range(0.0, f64(i + 1))!)
values[i], values[j] = values[j], values[i]
}
return from_1d[int](values)
}
// permutation_tensor returns a copy with rows shuffled along the first axis,
// matching NumPy's permutation behavior for an N-dimensional array.
pub fn (mut generator RandomGenerator) permutation_tensor[T](input &Tensor[T]) !&Tensor[T] {
if input.rank() == 0 {
return error('permutation_tensor: input must have at least one dimension')
}
indices := generator.permutation(input.shape[0])!
return input.take(indices.to_array(), 0)
}
// permutation_axis returns a copy with slices shuffled along the selected axis.
// Negative axes are accepted, matching Tensor.take and NumPy's axis convention.
pub fn (mut generator RandomGenerator) permutation_axis[T](input &Tensor[T], axis int) !&Tensor[T] {
rank := input.rank()
if rank == 0 {
return error('permutation_axis: input must have at least one dimension')
}
axis_index := if axis < 0 { axis + rank } else { axis }
if axis_index < 0 || axis_index >= rank {
return error('permutation_axis: axis ${axis} is out of range for rank ${rank}')
}
indices := generator.permutation(input.shape[axis_index])!
return input.take(indices.to_array(), axis_index)
}
// gamma returns samples from a Gamma distribution using this generator's
// independent stream. `alpha` is the shape and `scale` is the scale parameter.
pub fn (mut generator RandomGenerator) gamma(alpha f64, scale f64, shape []int) !&Tensor[f64] {
validate_gamma_parameters(alpha, scale)!
mut rng := generator.rng
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
values[i] = sample_gamma(alpha, scale, mut rng)!
}
return from_array[f64](values, shape)
}
fn validate_gamma_parameters(alpha f64, scale f64) ! {
if alpha <= 0 || scale <= 0 || math.is_nan(alpha) || math.is_inf(alpha, 0)
|| math.is_nan(scale) || math.is_inf(scale, 0) {
return error('gamma: alpha and scale must be finite and positive')
}
}
fn sample_gamma(alpha f64, scale f64, mut rng &rand.PRNG) !f64 {
shape := if alpha < 1 { alpha + 1 } else { alpha }
d := shape - 1.0 / 3.0
c := 1.0 / math.sqrt(9 * d)
for _ in 0 .. 10000 {
x := rng.normal(config.NormalConfigStruct{})!
if 1 + c * x <= 0 {
continue
}
u := rng.f64_in_range(0.0, 1.0)!
mut sample, accepted := gamma_candidate(d, c, x, u)
if accepted {
if alpha < 1 {
sample *= math.pow(rng.f64_in_range(0.0, 1.0)!, 1 / alpha)
}
return sample * scale
}
}
return error('gamma: rejection sampler did not converge')
}
fn gamma_candidate(d f64, c f64, x f64, uniform_value f64) (f64, bool) {
base := 1 + c * x
if base <= 0 {
return 0, false
}
v := base * base * base
if uniform_value < 1 - 0.0331 * x * x * x * x
|| math.log(uniform_value) < 0.5 * x * x + d * (1 - v + math.log(v)) {
return d * v, true
}
return 0, false
}
// beta returns samples from a Beta distribution using this generator's
// independent stream. `alpha` and `beta` are the two positive shape parameters.
pub fn (mut generator RandomGenerator) beta(alpha f64, beta f64, shape []int) !&Tensor[f64] {
validate_gamma_parameters(alpha, 1)!
validate_gamma_parameters(beta, 1)!
mut rng := generator.rng
mut values := []f64{len: size_from_shape(shape)}
for i in 0 .. values.len {
x := sample_gamma(alpha, 1, mut rng)!
y := sample_gamma(beta, 1, mut rng)!
if x + y == 0 {
return error('beta: sampled gamma values underflowed to zero')
}
values[i] = x / (x + y)
}
return from_array[f64](values, shape)
}
// dirichlet returns samples from a Dirichlet distribution. The final output
// axes match the concentration tensor's shape; sample_shape is prepended.
pub fn (mut generator RandomGenerator) dirichlet[T](alpha &Tensor[T], sample_shape []int) !&Tensor[f64] {
if alpha.rank() != 1 || alpha.size == 0 {
return error('dirichlet: concentration parameters must be a non-empty vector')
}
for dimension in sample_shape {
if dimension < 0 {
return error('dirichlet: sample dimensions must be non-negative')
}
}
mut concentrations := []f64{len: alpha.size}
for i in 0 .. alpha.size {
value := td(alpha.get_nth(i)).f64()
if value <= 0 || math.is_nan(value) || math.is_inf(value, 0) {
return error('dirichlet: concentration parameters must be finite and positive')
}
concentrations[i] = value
}
mut output_shape := sample_shape.clone()
output_shape << alpha.size
sample_count := size_from_shape(sample_shape)
mut values := []f64{len: sample_count * alpha.size}
mut rng := generator.rng
for sample in 0 .. sample_count {
start := sample * alpha.size
mut total := 0.0
for category, concentration in concentrations {
values[start + category] = sample_gamma(concentration, 1.0, mut rng)!
total += values[start + category]
}
if total == 0 || math.is_inf(total, 0) {
return error('dirichlet: sampled gamma values could not be normalized')
}
for category in 0 .. alpha.size {
values[start + category] /= total
}
}
return from_array[f64](values, output_shape)
}
// bernoulli returns a tensor of bernoulli random variables.
pub fn bernoulli[T](prob f64, shape []int, params TensorData) &Tensor[T] {
mut t := zeros[T](shape, params)
mut iter := t.iterator()
for {
_, i := iter.next() or { break }
rand_value := cast[T](rand.bernoulli(prob) or { 0.0 })
t.set(i, rand_value)
}
return t
}
// binomial returns a tensor of binomial random variables.
pub fn binomial[T](n int, prob f64, shape []int, params TensorData) !&Tensor[T] {
mut t := zeros[T](shape, params)
mut iter := t.iterator()
for {
_, i := iter.next() or { break }
rand_value := cast[T](rand.binomial(n, prob) or { return err })
t.set(i, rand_value)
}
return t
}
// exponential returns a tensor of exponential random variables.
pub fn exponential[T](lambda f64, shape []int, params TensorData) &Tensor[T] {
mut t := zeros[T](shape, params)
mut iter := t.iterator()
for {
_, i := iter.next() or { break }
rand_value := cast[T](rand.exponential(lambda))
t.set(i, rand_value)
}
return t
}
// gumbel returns samples from a Gumbel distribution using VTL's global stream.
pub fn gumbel(location f64, scale f64, shape []int, params TensorData) !&Tensor[f64] {
validate_location_scale(location, scale, 'gumbel')!
mut values := []f64{len: size_from_shape(shape), init: location}
if scale == 0 {
return from_array[f64](values, shape, params)
}
for i in 0 .. values.len {
u := open_unit_interval(rand.f64_in_range(0.0, 1.0)!)
values[i] = sample_gumbel(location, scale, u)
}
return from_array[f64](values, shape, params)
}
// laplace returns samples from a Laplace distribution using VTL's global stream.
pub fn laplace(location f64, scale f64, shape []int, params TensorData) !&Tensor[f64] {
validate_location_scale(location, scale, 'laplace')!
mut values := []f64{len: size_from_shape(shape), init: location}
if scale == 0 {
return from_array[f64](values, shape, params)
}
for i in 0 .. values.len {
u := open_unit_interval(rand.f64_in_range(0.0, 1.0)!)
values[i] = sample_laplace(location, scale, u)
}
return from_array[f64](values, shape, params)
}