-
Notifications
You must be signed in to change notification settings - Fork 9
/
random.clj
1472 lines (1265 loc) · 59.8 KB
/
random.clj
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
(ns fastmath.random
"Various random and noise functions.
Namespace defines various random number generators (RNGs), different types of random functions, sequence generators and noise functions.
### RNGs
You can use a selection of various RNGs defined in [Apache Commons Math](http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/random/package-summary.html) library.
Currently supported RNGs:
* `:jdk` - default java.util.Random
* `:mersenne` - MersenneTwister
* `:isaac` - ISAAC
* `:well512a`, `:well1024a`, `:well19937a`, `:well19937c`, `:well44497a`, `:well44497b` - several WELL variants
To create your RNG use [[rng]] multimethod. Pass RNG name and (optional) seed. Returned RNG is equipped with [[RNGProto]] protocol with methods: [[irandom]], [[lrandom]], [[frandom]] [[drandom]], [[grandom]], [[brandom]] which return random primitive value with given RNG.
```
(let [rng (rng :isaac 1337)]
(irandom rng))
```
For conveniency default RNG (`:jdk`) with following functions are created: [[irand]], [[lrand]], [[frand]], [[drand]], [[grand]], [[brand]].
Each prefix denotes returned type:
* i - int
* l - long
* f - float
* d - double
* g - gaussian (double)
* b - boolean
Check individual function for parameters description.
### Random Vector Sequences
Couple of functions to generate sequences of numbers or vectors.
To create generator call [[sequence-generator]] with generator name and vector size [1,4].
Following generators are available:
* `:halton` - Halton low-discrepancy sequence; range [0,1]
* `:sobol` - Sobol low-discrepancy sequence; range [0,1]
* `:r2` - R2 low-discrepancy sequence; range [0,1], [more...](http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/)
* `:sphere` - uniformly random distributed on unit sphere
* `:gaussian` - gaussian distributed (mean=0, stddev=1)
* `:default` - uniformly random; range:[0,1]
`:halton`, `:sobol` and `:r2` can be also randomly jittered according to this [article](http://extremelearning.com.au/a-simple-method-to-construct-isotropic-quasirandom-blue-noise-point-sequences/). Call [[jittered-sequence-generator]].
After creation you get lazy sequence
### Noise
List of continuous noise functions (1d, 2d and 3d):
* `:value` - value noise
* `:gradient` - gradient noise (improved Ken Perlin version)
* `:simplex` - simplex noise
First two (`:value` and `:gradient`) can use 4 different interpolation types: `:none`, `:linear`, `:hermite` (cubic) and `:quintic`.
All can be combined in following variants:
* Noise - pure noise value, create with [[single-noise]]
* FBM - fractal brownian motion, create with [[fbm-noise]]
* Billow - billow noise, [[billow-noise]]
* RidgedMulti - ridged multi, [[ridgedmulti-noise]]
Noise creation requires detailed configuration which is simple map of following keys:
* `:seed` - seed as integer
* `:noise-type` - type of noise: `:value`, `:gradient` (default), `:simplex`
* `:interpolation` - type of interpolation (for value and gradient): `:none`, `:linear`, `:hermite` (default) or `:quintic`
* `:octaves` - number of octaves for combined noise (like FBM), default: 6
* `:lacunarity` - scaling factor for combined noise, default: 2.00
* `:gain` - amplitude scaling factor for combined noise, default: 0.5
* `:normalize?` - should be normalized to `[0,1]` range (true, default) or to `[-1,1]` range (false)
For usage convenience 3 ready to use functions are prepared. Returning value from `[0,1]` range:
* [[noise]] - Perlin Noise (gradient noise, 6 octaves, quintic interpolation)
* [[vnoise]] - Value Noise (as in Processing, 6 octaves, hermite interpolation)
* [[simplex]] - Simplex Noise (6 octaves)
For random noise generation you can use [[random-noise-cfg]] and [[random-noise-fn]]. Both can be feed with configuration. Additional configuration:
* `:generator` can be set to one of the noise variants, defaults to `:fbm`
* `:warp-scale` - 0.0 - do not warp, >0.0 warp
* `:warp-depth` - depth for warp (default 1.0, if warp-scale is positive)
#### Discrete Noise
[[discrete-noise]] is a 1d or 2d hash function for given integers. Returns double from `[0,1]` range.
### Distribution
Various real and integer distributions. See [[DistributionProto]] and [[RNGProto]] for functions.
To create distribution call [[distribution]] multimethod with name as a keyword and map as parameters."
{:metadoc/categories {:rand "Random number generation"
:noise "Noise functions"
:gen "Random sequence generation"
:dist "Distributions"}}
(:require [fastmath.core :as m]
[fastmath.vector :as v]
[fastmath.kernel :as k]
[fastmath.protocols :as prot])
(:import [org.apache.commons.math3.random RandomGenerator ISAACRandom JDKRandomGenerator MersenneTwister
Well512a Well1024a Well19937a Well19937c Well44497a Well44497b
RandomVectorGenerator HaltonSequenceGenerator SobolSequenceGenerator UnitSphereRandomVectorGenerator
EmpiricalDistribution SynchronizedRandomGenerator]
[fastmath.java R2]
[umontreal.ssj.probdist ContinuousDistribution DiscreteDistributionInt InverseGammaDist AndersonDarlingDistQuick ChiDist ChiSquareNoncentralDist CramerVonMisesDist ErlangDist FatigueLifeDist FoldedNormalDist FrechetDist HyperbolicSecantDist InverseGaussianDist HypoExponentialDist HypoExponentialDistEqual JohnsonSBDist JohnsonSLDist JohnsonSUDist KolmogorovSmirnovDistQuick KolmogorovSmirnovPlusDist LogarithmicDist LoglogisticDist NormalInverseGaussianDist Pearson6Dist PowerDist RayleighDist WatsonGDist WatsonUDist]
[umontreal.ssj.probdistmulti DirichletDist]
[fastmath.java.noise Billow RidgedMulti FBM NoiseConfig Noise Discrete]
[smile.stat.distribution Distribution DiscreteDistribution NegativeBinomialDistribution]
[org.apache.commons.math3.distribution AbstractRealDistribution RealDistribution BetaDistribution CauchyDistribution ChiSquaredDistribution EnumeratedRealDistribution ExponentialDistribution FDistribution GammaDistribution, GumbelDistribution, LaplaceDistribution, LevyDistribution, LogisticDistribution, LogNormalDistribution, NakagamiDistribution, NormalDistribution, ParetoDistribution, TDistribution, TriangularDistribution, UniformRealDistribution WeibullDistribution MultivariateNormalDistribution]
[org.apache.commons.math3.distribution IntegerDistribution AbstractIntegerDistribution BinomialDistribution EnumeratedIntegerDistribution, GeometricDistribution, HypergeometricDistribution, PascalDistribution, PoissonDistribution, UniformIntegerDistribution, ZipfDistribution]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
;; protocol proxies
(defn frandom
"Random double number with provided RNG"
{:metadoc/categories #{:rand}}
(^double [rng] (prot/frandom rng))
(^double [rng mx] (prot/frandom rng mx))
(^double [rng mn mx] (prot/frandom rng mn mx)))
(defn drandom
"Random double number with provided RNG"
{:metadoc/categories #{:rand}}
(^double [rng] (prot/drandom rng))
(^double [rng mx] (prot/drandom rng mx))
(^double [rng mn mx] (prot/drandom rng mn mx)))
(defn grandom
"Random gaussian double number with provided RNG"
{:metadoc/categories #{:rand}}
(^double [rng] (prot/grandom rng))
(^double [rng stddev] (prot/grandom rng stddev))
(^double [rng mean stddev] (prot/grandom rng mean stddev)))
(defn irandom
"Random integer number with provided RNG"
{:metadoc/categories #{:rand}}
(^long [rng] (prot/irandom rng))
(^long [rng mx] (prot/irandom rng mx))
(^long [rng mn ^long mx] (prot/irandom rng mn mx)))
(defn lrandom
"Random long number with provided RNG"
{:metadoc/categories #{:rand}}
(^long [rng] (prot/lrandom rng))
(^long [rng mx] (prot/lrandom rng mx))
(^long [rng mn mx] (prot/lrandom rng mn mx)))
(defn brandom
"Random boolean with provided RNG"
{:metadoc/categories #{:rand}}
([rng] (prot/brandom rng))
([rng p] (prot/brandom rng p)))
(defn set-seed!
"Sets seed. Returns `rng`."
{:metadoc/categories #{:rand}}
[rng v] (prot/set-seed! rng v))
(defn ->seq
"Returns lazy sequence of random samples (can be limited to optional `n` values)."
{:metadoc/categories #{:rand}}
([rng] (prot/->seq rng))
([rng n] (prot/->seq rng n)))
;; Type hinted functions generating random value
(defn- next-random-value-long
"Generate next long.
* arity 0 - from 0 to maximum long value
* arity 1 - from 0 to provided integer (excluded)
* arity 2 - from the provided range (included, excluded)"
(^long [^RandomGenerator r] (.nextLong r))
(^long [^RandomGenerator r ^long mx] (mod (.nextLong r) mx))
(^long [r ^long mn ^long mx]
(let [diff (- mx mn)]
(if (zero? diff) mn
(+ mn (next-random-value-long r diff))))))
(defn- next-random-value-double
"Generate next double.
* arity 0 - from 0 to 1 (exluded)
* arity 1 - from 0 to provided double (excluded)
* arity 2 - from the provided range (included, excluded)"
(^double [^RandomGenerator r] (.nextDouble r))
(^double [^RandomGenerator r ^double mx] (* (.nextDouble r) mx))
(^double [r ^double mn ^double mx]
(let [diff (- mx mn)]
(if (zero? diff) mn
(+ mn (next-random-value-double r diff))))))
(defn- next-random-value-gaussian
"Generate next random value from normal distribution.
* arity 0 - N(0,1)
* arity 1 - N(0,par)
* arity 2 - N(par1,par2)"
(^double [^RandomGenerator r] (.nextGaussian r))
(^double [^RandomGenerator r ^double mx] (* (.nextGaussian r) mx))
(^double [r ^double mn ^double mx]
(let [diff (- mx mn)]
(if (zero? diff) mn
(+ mn (next-random-value-gaussian r diff))))))
;; Extend RandomGenerator interface with functions created by macro `next-random-value-fn`. This way all RNG classes are enriched with new, more convenient functions.
;;
;; Note that `grandom` is under special care due to different [mn mx] range meaning.
(extend RandomGenerator
prot/RNGProto
{:irandom (comp unchecked-int next-random-value-long)
:lrandom next-random-value-long
:frandom (comp float next-random-value-double)
:drandom next-random-value-double
:grandom (fn
([t] (next-random-value-gaussian t))
([t std] (next-random-value-gaussian t std))
([t ^double mean ^double std] (next-random-value-gaussian t mean (+ mean std))))
:brandom (fn
([^RandomGenerator t] (.nextBoolean t))
([t ^double thr] (< (next-random-value-double t) thr)))
:set-seed! #(do
(.setSeed ^RandomGenerator %1 (long %2))
%1)
:->seq (fn
([^RandomGenerator t] (repeatedly #(next-random-value-double t)))
([^RandomGenerator t n] (repeatedly n #(next-random-value-double t))))})
;; Helper macro which creates RNG object of given class and/or seed.
(defmacro ^:private create-object-with-seed
"Create object of the class with (or not) given seed. Used to create RNG."
[cl seed]
`(if-let [arg# ~seed]
(new ~cl (int arg#))
(new ~cl)))
(defmulti rng
"Create RNG for given name (as keyword) and optional seed. Return object enhanced with [[RNGProto]]. See: [[rngs-list]] for names."
{:metadoc/categories #{:rand}}
(fn [m & _] m))
(defmethod rng :mersenne [_ & [seed]]
(create-object-with-seed MersenneTwister seed))
(defmethod rng :isaac [_ & [seed]]
(create-object-with-seed ISAACRandom seed))
(defmethod rng :well512a [_ & [seed]]
(create-object-with-seed Well512a seed))
(defmethod rng :well1024a [_ & [seed]]
(create-object-with-seed Well1024a seed))
(defmethod rng :well19937a [_ & [seed]]
(create-object-with-seed Well19937a seed))
(defmethod rng :well19937c [_ & [seed]]
(create-object-with-seed Well19937c seed))
(defmethod rng :well44497a [_ & [seed]]
(create-object-with-seed Well44497a seed))
(defmethod rng :well44497b [_ & [seed]]
(create-object-with-seed Well44497b seed))
(defmethod rng :jdk [_ & [seed]]
(create-object-with-seed JDKRandomGenerator seed))
(defmethod rng :default [_ & [seed]]
(rng :jdk seed))
(defn synced-rng
"Create synchronized RNG for given name and optional seed. Wraps [[rng]] method."
{:metadoc/categories #{:rand}}
([m] (SynchronizedRandomGenerator. (rng m)))
([m seed] (SynchronizedRandomGenerator. (rng m seed))))
;; List of randomizers
(defonce ^{:metadoc/categories #{:rand}
:doc "List of all possible RNGs."}
rngs-list (remove #{:default} (keys (methods rng))))
;; ### Default RNG
(defonce ^{:doc "Default RNG - JDK"
:metadoc/categories #{:rand}}
default-rng (rng :jdk))
(def ^{:doc "Random boolean with default RNG.
Returns true or false with equal probability. You can set `p` probability for `true`"
:metadoc/categories #{:rand}}
brand (partial prot/brandom default-rng))
(defn frand
"Random double number with default RNG.
As default returns random float from `[0,1)` range.
When `mx` is passed, range is set to `[0, mx)`. When `mn` is passed, range is set to `[mn, mx)`."
{:metadoc/categories #{:rand}}
(^double [] (prot/frandom default-rng))
(^double [mx] (prot/frandom default-rng mx))
(^double [mn mx] (prot/frandom default-rng mn mx)))
(defn drand
"Random double number with default RNG.
As default returns random double from `[0,1)` range.
When `mx` is passed, range is set to `[0, mx)`. When `mn` is passed, range is set to `[mn, mx)`."
{:metadoc/categories #{:rand}}
(^double [] (prot/drandom default-rng))
(^double [mx] (prot/drandom default-rng mx))
(^double [mn mx] (prot/drandom default-rng mn mx)))
(defn grand
"Random gaussian double number with default RNG.
As default returns random double from `N(0,1)`.
When `std` is passed, `N(0,std)` is used. When `mean` is passed, distribution is set to `N(mean, std)`."
{:metadoc/categories #{:rand}}
(^double [] (prot/grandom default-rng))
(^double [stddev] (prot/grandom default-rng stddev))
(^double [mean stddev] (prot/grandom default-rng mean stddev)))
(defn irand
"Random integer number with default RNG.
As default returns random integer from full integer range.
When `mx` is passed, range is set to `[0, mx)`. When `mn` is passed, range is set to `[mn, mx)`."
{:metadoc/categories #{:rand}}
(^long [] (prot/irandom default-rng))
(^long [mx] (prot/irandom default-rng mx))
(^long [mn mx] (prot/irandom default-rng mn mx)))
(defn lrand
"Random long number with default RNG.
As default returns random long from full integer range.
When `mx` is passed, range is set to `[0, mx)`. When `mn` is passed, range is set to `[mn, mx)`."
{:metadoc/categories #{:rand}}
(^long [] (prot/lrandom default-rng))
(^long [mx] (prot/lrandom default-rng mx))
(^long [mn mx] (prot/lrandom default-rng mn mx)))
(defmacro randval
"Retrun value with given probability (default 0.5)"
{:metadoc/categories #{:rand}}
([v1 v2]
`(if (prot/brandom default-rng) ~v1 ~v2))
([prob v1 v2]
`(if (prot/brandom default-rng ~prob) ~v1 ~v2))
([prob]
`(prot/brandom default-rng ~prob))
([]
`(prot/brandom default-rng)))
(defn flip
"Returns 1 with given probability, 0 otherwise"
{:metadoc/categories #{:rand}}
(^long [p]
(randval p 1 0))
(^long []
(randval 0.5 1 0)))
(defn flipb
"Returns true with given probability, false otherwise"
{:metadoc/categories #{:rand}}
([p] (randval p))
([] (randval)))
;; generators
(defn- rv-generators
"Generators from commons math and custom classes."
[seq-generator ^long dimensions]
(let [s (case seq-generator
:halton (m/constrain dimensions 1 40)
:sobol (m/constrain dimensions 1 1000)
:r2 (m/constrain dimensions 1 4)
dimensions)
^RandomVectorGenerator g (case seq-generator
:halton (HaltonSequenceGenerator. s)
:sobol (SobolSequenceGenerator. s)
:sphere (UnitSphereRandomVectorGenerator. s)
:r2 (R2. s))]
(repeatedly (case s
1 #(aget (.nextVector g) 0)
2 #(v/array->vec2 (.nextVector g))
3 #(v/array->vec3 (.nextVector g))
4 #(v/array->vec4 (.nextVector g))
#(vec (.nextVector g))))))
;; R2
;; http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
(defn- random-generators
"Random generators"
[seq-generator ^long dimensions]
(let [g (case seq-generator
:default drand
:gaussian grand)]
(repeatedly (case dimensions
1 g
2 (partial v/generate-vec2 g)
3 (partial v/generate-vec3 g)
4 (partial v/generate-vec4 g)
#(vec (repeatedly dimensions g))))))
;; jittering
;; http://extremelearning.com.au/a-simple-method-to-construct-isotropic-quasirandom-blue-noise-point-sequences/
(defn- jitter-generator
"Generate random jitter"
[seq-generator ^long dimensions ^double jitter]
(let [[^double d0 ^double i0 ^double f ^double p] (case seq-generator
:r2 [0.76 0.7 0.25 -0.5]
:halton [0.9 0.7 0.25 -0.5]
:sobol [0.16 0.58 0.4 -0.2]
[0.5 0.5 0.25 -0.5])
c (* jitter m/SQRTPI d0 f)
g (random-generators :default dimensions)]
(map-indexed (fn [^long i v] (v/mult v (* c (m/pow (- (inc i) i0) p)))) g)))
;; Sequence creators
(defmulti
^{:doc "Create Sequence generator. See [[sequence-generators-list]] for names.
Values:
* `:r2`, `:halton`, `:sobol`, `:default` - range `[0-1] for each dimension`
* `:gaussian` - from `N(0,1)` distribution
* `:sphere` - from surface of unit sphere (ie. euclidean distance from origin equals 1.0)
Possible dimensions:
* `:r2` - 1-4
* `:halton` - 1-40
* `:sobol` - 1-1000
* the rest - 1+
See also [[jittered-sequence-generator]]."
:metadoc/categories #{:gen}}
sequence-generator (fn [seq-generator _] seq-generator))
(defmethod sequence-generator :halton [seq-generator dimensions] (rv-generators seq-generator dimensions))
(defmethod sequence-generator :sobol [seq-generator dimensions] (rv-generators seq-generator dimensions))
(defmethod sequence-generator :r2 [seq-generator dimensions] (rv-generators seq-generator dimensions))
(defmethod sequence-generator :sphere [seq-generator dimensions] (rv-generators seq-generator dimensions))
(defmethod sequence-generator :gaussian [seq-generator dimensions] (random-generators seq-generator dimensions))
(defmethod sequence-generator :default [seq-generator dimensions] (random-generators seq-generator dimensions))
(defn jittered-sequence-generator
"Create jittered sequence generator.
Suitable for `:r2`, `:sobol` and `:halton` sequences.
`jitter` parameter range is from `0` (no jitter) to `1` (full jitter). Default: 0.25.
See also [[sequence-generator]]."
([seq-generator ^long dimensions] (jittered-sequence-generator seq-generator dimensions 0.25))
([seq-generator ^long dimensions ^double jitter]
(let [s (sequence-generator seq-generator dimensions)
[j mod-fn] (if (#{:sphere :gaussian} seq-generator)
(let [j (sequence-generator :gaussian dimensions)
jitter-low (* m/SQRTPI 0.5 0.25 jitter)]
[j (if (m/one? dimensions)
(fn [^double v ^double vj] (+ v (* jitter-low vj)))
(fn [v vj] (v/add v (v/mult vj jitter-low))))])
(let [j (jitter-generator seq-generator dimensions jitter)]
[j (if (m/one? dimensions)
(fn [^double v ^double vj] (m/frac (+ v vj)))
(fn [v vj] (v/fmap (v/add v vj) m/frac)))]))]
(map mod-fn s j))))
(def ^{:doc "List of random sequence generator. See [[sequence-generator]]."
:metadoc/categories #{:gen}}
sequence-generators-list (keys (methods sequence-generator)))
;; ## Noise
(def ^{:doc "List of possible noise interpolations as a map of names and values."
:metadoc/categories #{:noise}}
noise-interpolations {:none NoiseConfig/INTERPOLATE_NONE
:linear NoiseConfig/INTERPOLATE_LINEAR
:hermite NoiseConfig/INTERPOLATE_HERMITE
:quintic NoiseConfig/INTERPOLATE_QUINTIC})
(def ^{:doc "List of possible noise types as a map of names and values."
:metadoc/categories #{:noise}}
noise-types {:value NoiseConfig/NOISE_VALUE
:gradient NoiseConfig/NOISE_GRADIENT
:simplex NoiseConfig/NOISE_SIMPLEX})
(defn- noise-config-obj
"Create noise configuration object based on map."
[{:keys [seed noise-type interpolation octaves lacunarity gain normalize?]}]
(NoiseConfig. seed
(or (noise-types noise-type) NoiseConfig/NOISE_GRADIENT)
(or (noise-interpolations interpolation) NoiseConfig/INTERPOLATE_HERMITE)
octaves lacunarity gain normalize?))
(defn- noise-config
"Create FBM noise function for given configuration."
([] (noise-config {}))
([cfg]
(noise-config-obj (merge {:seed (irand)
:noise-type :gradient
:interpolation :hermite
:octaves 6
:lacunarity 2.00
:gain 0.5
:normalize? true} cfg))))
(defonce ^:private perlin-noise-config (noise-config {:interpolation :quintic}))
(defonce ^:private simplex-noise-config (noise-config {:noise-type :simplex}))
(defonce ^:private value-noise-config (noise-config {:noise-type :value}))
(defn vnoise
"Value Noise.
6 octaves, Hermite interpolation (cubic, h01)."
{:metadoc/categories #{:noise}}
(^double [^double x] (FBM/noise value-noise-config x))
(^double [^double x ^double y] (FBM/noise value-noise-config x y))
(^double [^double x ^double y ^double z] (FBM/noise value-noise-config x y z)))
(defn noise
"Improved Perlin Noise.
6 octaves, quintic interpolation."
{:metadoc/categories #{:noise}}
(^double [^double x] (FBM/noise perlin-noise-config x))
(^double [^double x ^double y] (FBM/noise perlin-noise-config x y))
(^double [^double x ^double y ^double z] (FBM/noise perlin-noise-config x y z)))
(defn simplex
"Simplex noise. 6 octaves."
{:metadoc/categories #{:noise}}
(^double [^double x] (FBM/noise simplex-noise-config x))
(^double [^double x ^double y] (FBM/noise simplex-noise-config x y))
(^double [^double x ^double y ^double z] (FBM/noise simplex-noise-config x y z)))
(defmacro ^:private gen-noise-function
"Generate various noise as static function"
[noise-type method]
(let [nm (symbol (str noise-type "-noise"))]
`(defn ~nm
~(str "Create " noise-type " noise function with optional configuration.")
{:metadoc/categories #{:noise}}
([] (~nm {}))
([cfg#]
(let [ncfg# (noise-config cfg#)]
(fn
(^double [x#] (~method ncfg# x#))
(^double [x# y#] (~method ncfg# x# y#))
(^double [x# y# z#] (~method ncfg# x# y# z#))))))))
(gen-noise-function single Noise/noise)
(gen-noise-function fbm FBM/noise)
(gen-noise-function billow Billow/noise)
(gen-noise-function ridgedmulti RidgedMulti/noise)
(defn- make-warp-1d
[noise ^double scale ^long depth]
(let [warp-noise-1d-proto (fn warp-noise-1d
(^double [^double x ^long depth]
(if (zero? depth)
(noise x)
(let [q1 (* scale ^double (warp-noise-1d (+ x depth 0.321) (dec depth)))]
(noise (+ x q1))))))]
(fn [^double x] (warp-noise-1d-proto x depth))))
(defn- make-warp-2d
[noise ^double scale ^long depth]
(let [warp-noise-2d-proto (fn warp-noise-2d
(^double [^double x ^double y ^long depth]
(if (zero? depth)
(noise x y)
(let [q1 (* scale ^double (warp-noise-2d (+ x depth 0.321) (+ y depth 4.987) (dec depth)))
q2 (* scale ^double (warp-noise-2d (+ x depth 3.591) (+ y depth -2.711) (dec depth)))]
(noise (+ x q1) (+ y q2))))))]
(fn [^double x ^double y] (warp-noise-2d-proto x y depth))))
(defn- make-warp-3d
[noise ^double scale ^long depth]
(let [warp-noise-3d-proto (fn warp-noise-3d
(^double [^double x ^double y ^double z ^long depth]
(if (zero? depth)
(noise x y)
(let [q1 (* scale ^double (warp-noise-3d (+ x depth 0.321) (+ y depth 4.987) (+ z depth 2.12) (dec depth)))
q2 (* scale ^double (warp-noise-3d (+ x depth 3.591) (+ y depth -2.711) (+ z depth -5.4321) (dec depth)))
q3 (* scale ^double (warp-noise-3d (+ x depth -1.591) (+ y depth 12.1711) (+ z depth 3.1) (dec depth)))]
(noise (+ x q1) (+ y q2) (+ z q3))))))]
(fn [^double x ^double y ^double z] (warp-noise-3d-proto x y z depth))))
(defn warp-noise-fn
"Create warp noise (see [Inigo Quilez article](http://www.iquilezles.org/www/articles/warp/warp.htm)).
Parameters:
* noise function, default: vnoise
* scale factor, default: 4.0
* depth (1 or 2), default 1
Normalization of warp noise depends on normalization of noise function."
{:metadoc/categories #{:noise}}
([noise ^double scale ^long depth]
(let [n1 (make-warp-1d noise scale depth)
n2 (make-warp-2d noise scale depth)
n3 (make-warp-3d noise scale depth)]
(fn
(^double [^double x] (n1 x))
(^double [^double x ^double y] (n2 x y))
(^double [^double x ^double y ^double z] (n3 x y z)))))
([noise ^double scale] (warp-noise-fn noise scale 1))
([noise] (warp-noise-fn noise 4.0 1))
([] (warp-noise-fn vnoise 4.0 1)))
(defonce ^{:doc "List of possible noise generators as a map of names and functions."
:metadoc/categories #{:noise}}
noise-generators
{:fbm fbm-noise
:single single-noise
:billow billow-noise
:ridgemulti ridgedmulti-noise})
(defn random-noise-cfg
"Create random noise configuration.
Optional map with fixed values."
{:metadoc/categories #{:noise}}
([pre-config]
(merge {:seed (irand)
:generator (rand-nth [:single :fbm :billow :ridgemulti])
:noise-type (rand-nth (keys noise-types))
:interpolation (rand-nth (keys noise-interpolations))
:octaves (irand 1 10)
:lacunarity (drand 1.5 2.5)
:gain (drand 0.2 0.8)
:warp-scale (randval 0.8 0.0 (randval 0.5 4.0 (drand 0.1 10)))
:warp-depth (randval 0.8 1 (irand 1 4))
:normalize? true} pre-config))
([] (random-noise-cfg nil)))
(defn random-noise-fn
"Create random noise function from all possible options.
Optionally provide own configuration `cfg`. In this case one of 4 different blending methods will be selected."
{:metadoc/categories #{:noise}}
([cfg]
(let [cfg (random-noise-cfg cfg)
gen-fn (noise-generators (get cfg :generator :fbm))
noise (gen-fn cfg)]
(if (pos? ^double (:warp-scale cfg))
(warp-noise-fn noise (:warp-scale cfg) (:warp-depth cfg))
noise)))
([] (random-noise-fn nil)))
;; ### Discrete noise
(defn discrete-noise
"Discrete noise. Parameters:
* X (long)
* Y (long, optional)
Returns double value from [0,1] range"
{:metadoc/categories #{:noise}}
(^double [^long X ^long Y] (Discrete/value X Y))
(^double [^long X] (Discrete/value X 0)))
;; Distribution
;; protocol proxies
(defn cdf
"Cumulative probability."
{:metadoc/categories #{:dist}}
(^double [d v] (prot/cdf d v))
(^double [d v1 v2] (prot/cdf d v1 v2)))
(defn pdf
"Density"
{:metadoc/categories #{:dist}}
^double [d v] (prot/pdf d v))
(defn lpdf
"Log density"
{:metadoc/categories #{:dist}}
^double [d v] (prot/lpdf d v))
(defn icdf
"Inverse cumulative probability"
{:metadoc/categories #{:dist}}
[d ^double v] (prot/icdf d v))
(defn probability
"Probability (PMF)"
{:metadoc/categories #{:dist}}
^double [d v] (prot/probability d v))
(defn sample
"Random sample"
{:metadoc/categories #{:dist}}
[d] (prot/sample d))
(defn dimensions
"Distribution dimensionality"
{:metadoc/categories #{:dist}}
^long [d] (prot/dimensions d))
(defn source-object
"Returns Java or proxy object from backend library (if available)"
{:metadoc/categories #{:dist}}
[d] (prot/source-object d))
(defn continuous?
"Does distribution support continuous domain?"
{:metadoc/categories #{:dist}}
[d] (prot/continuous? d))
(defn observe1
"Log of probability/density of the value. Alias for [[lpdf]]."
{:metadoc/categories #{:dist}}
^double [d v]
(prot/lpdf d v))
(defn log-likelihood
"Log likelihood of samples"
{:metadoc/categories #{:dist}}
^double [d vs]
(reduce (fn [^double s ^double v] (if (m/invalid-double? s)
(reduced s)
(+ s v))) 0.0 (map #(prot/lpdf d %) vs)))
(defmacro observe
"Log likelihood of samples. Alias for [[log-likelihood]]."
{:metadoc/categories #{:dist}}
[d vs]
`(log-likelihood ~d ~vs))
(defn likelihood
"Likelihood of samples"
{:metadoc/categories #{:dist}}
^double [d vs]
(m/exp (log-likelihood d vs)))
(defn mean
"Distribution mean"
{:metadoc/categories #{:dist}}
^double [d] (prot/mean d))
(defn means
"Distribution means (for multivariate distributions)"
{:metadoc/categories #{:dist}}
[d] (prot/means d))
(defn variance
"Distribution variance"
{:metadoc/categories #{:dist}}
^double [d] (prot/variance d))
(defn covariance
"Distribution covariance matrix (for multivariate distributions)"
{:metadoc/categories #{:dist}}
[d] (prot/covariance d))
(defn lower-bound
"Distribution lowest supported value"
{:metadoc/categories #{:dist}}
^double [d] (prot/lower-bound d))
(defn upper-bound
"Distribution highest supported value"
{:metadoc/categories #{:dist}}
^double [d] (prot/upper-bound d))
(defn distribution-id
"Distribution identifier as keyword."
{:metadoc/categories #{:dist}}
[d] (prot/distribution-id d))
(defn distribution-parameters
"Distribution highest supported value.
When `all?` is true, technical parameters are included, ie: `:rng` and `:inverser-cumm-accuracy`."
{:metadoc/categories #{:dist}}
([d] (distribution-parameters d false))
([d all?]
(if-not all?
(-> (prot/distribution-parameters d)
(set)
(disj :rng :inverse-cumm-accuracy)
(vec))
(prot/distribution-parameters d))))
;; apache commons math
(extend RealDistribution
prot/DistributionProto
{:cdf (fn
(^double [^RealDistribution d ^double v] (.cumulativeProbability d v))
(^double [^RealDistribution d ^double v1 ^double v2] (.cumulativeProbability d v1 v2)))
:pdf (fn ^double [^RealDistribution d ^double v] (.density d v))
:lpdf (fn ^double [^AbstractRealDistribution d ^double v] (.logDensity d v))
:icdf (fn ^double [^RealDistribution d ^double p] (.inverseCumulativeProbability d p))
:probability (fn ^double [^RealDistribution d ^double p] (.density d p))
:sample (fn ^double [^RealDistribution d] (.sample d))
:dimensions (constantly 1)
:source-object identity
:continuous? (constantly true)}
prot/UnivariateDistributionProto
{:mean (fn ^double [^RealDistribution d] (.getNumericalMean d))
:variance (fn ^double [^RealDistribution d] (.getNumericalVariance d))
:lower-bound (fn ^double [^RealDistribution d] (.getSupportLowerBound d))
:upper-bound (fn ^double [^RealDistribution d] (.getSupportUpperBound d))}
prot/RNGProto
{:drandom (fn ^double [^RealDistribution d] (.sample d))
:frandom (fn ^double [^RealDistribution d] (unchecked-float (.sample d)))
:lrandom (fn ^long [^RealDistribution d] (unchecked-long (.sample d)))
:irandom (fn ^long [^RealDistribution d] (unchecked-int (.sample d)))
:->seq (fn
([^RealDistribution d] (repeatedly #(.sample d)))
([^RealDistribution d n] (repeatedly n #(.sample d))))
:set-seed! (fn [^RealDistribution d ^double seed] (.reseedRandomGenerator d seed) d)})
;; ssj
(defn- reify-continuous-ssj
[^ContinuousDistribution d ^RandomGenerator rng nm & ks]
(let [kss (vec (conj ks :rng))]
(reify
prot/DistributionProto
(pdf [_ v] (.density d v))
(lpdf [_ v] (m/log (.density d v)))
(cdf [_ v] (.cdf d v))
(cdf [_ v1 v2] (- (.cdf d v2) (.cdf d v1)))
(icdf [_ v] (.inverseF d v))
(probability [_ v] (.density d v))
(sample [_] (.inverseF d (prot/drandom rng)))
(dimensions [_] 1)
(source-object [_] d)
(continuous? [_] true)
prot/DistributionIdProto
(distribution-id [_] nm)
(distribution-parameters [_] kss)
prot/UnivariateDistributionProto
(mean [_] (.getMean d))
(variance [_] (.getVariance d))
(lower-bound [_] (.getXinf d))
(upper-bound [_] (.getXsup d))
prot/RNGProto
(drandom [_] (.inverseF d (prot/drandom rng)))
(frandom [_] (unchecked-float (.inverseF d (prot/drandom rng))))
(lrandom [_] (unchecked-long (.inverseF d (prot/drandom rng))))
(irandom [_] (unchecked-int (.inverseF d (prot/drandom rng))))
(->seq [_] (repeatedly #(.inverseF d (prot/drandom rng))))
(->seq [_ n] (repeatedly n #(.inverseF d (prot/drandom rng))))
(set-seed! [d seed] (prot/set-seed! rng seed) d))))
(defn- reify-integer-ssj
[^DiscreteDistributionInt d ^RandomGenerator rng nm & ks]
(let [kss (vec (conj ks :rng))]
(reify
prot/DistributionProto
(pdf [_ v] (.prob d (m/floor v)))
(lpdf [_ v] (m/log (.prob d (m/floor v))))
(cdf [_ v] (.cdf d (m/floor v)))
(cdf [_ v1 v2] (- (.cdf d (m/floor v2)) (.cdf d (m/floor v1))))
(icdf [_ v] (.inverseF d v))
(probability [_ v] (.prob d (m/floor v)))
(sample [_] (.inverseF d (prot/drandom rng)))
(dimensions [_] 1)
(source-object [_] d)
(continuous? [_] false)
prot/DistributionIdProto
(distribution-id [_] nm)
(distribution-parameters [_] kss)
prot/UnivariateDistributionProto
(mean [_] (.getMean d))
(variance [_] (.getVariance d))
(lower-bound [_] (.getXinf d))
(upper-bound [_] (.getXsup d))
prot/RNGProto
(drandom [_] (.inverseF d (prot/drandom rng)))
(frandom [_] (unchecked-float (.inverseF d (prot/drandom rng))))
(lrandom [_] (unchecked-long (.inverseF d (prot/drandom rng))))
(irandom [_] (unchecked-int (.inverseF d (prot/drandom rng))))
(->seq [_] (repeatedly #(.inverseF d (prot/drandom rng))))
(->seq [_ n] (repeatedly n #(.inverseF d (prot/drandom rng))))
(set-seed! [d seed] (prot/set-seed! rng seed) d))))
;; smile
(extend DiscreteDistribution
prot/DistributionProto
{:cdf (fn
(^double [^Distribution d ^double v] (.cdf d (m/floor v)))
(^double [^Distribution d ^double v1 ^double v2] (- (.cdf d (m/floor v2)) (.cdf d (m/floor v1)))))
:pdf (fn ^double [^Distribution d ^double v] (.p d (m/floor v)))
:lpdf (fn ^double [^Distribution d ^double v] (.logp d (m/floor v)))
:icdf (fn ^double [^Distribution d ^double p] (.quantile d p))
:probability (fn ^double [^Distribution d ^double v] (.p d (m/floor v)))
:sample (fn ^double [^Distribution d] (.rand d))
:dimensions (constantly 1)
:source-object identity
:continuous? (constantly false)}
prot/UnivariateDistributionProto
{:mean (fn ^double [^Distribution d] (.mean d))
:variance (fn ^double [^Distribution d] (.var d))}
prot/RNGProto
{:drandom (fn ^double [^Distribution d] (.rand d))
:frandom (fn ^double [^Distribution d] (unchecked-float (.rand d)))
:lrandom (fn ^long [^Distribution d] (unchecked-long (.rand d)))
:irandom (fn ^long [^Distribution d] (unchecked-int (.rand d)))
:->seq (fn
([^Distribution d] (repeatedly #(.rand d)))
([^Distribution d n] (repeatedly n #(.rand d))))})
(extend IntegerDistribution
prot/DistributionProto
{:cdf (fn
(^double [^IntegerDistribution d ^double v] (.cumulativeProbability d (m/floor v)))
(^double [^IntegerDistribution d ^double v1 ^double v2] (.cumulativeProbability d (m/floor v1) (m/floor v2))))
:icdf (fn ^long [^IntegerDistribution d ^double p] (.inverseCumulativeProbability d p))
:pdf (fn ^double [^IntegerDistribution d ^double p] (.probability d (m/floor p)))
:lpdf (fn ^double [^AbstractIntegerDistribution d ^double p] (.logProbability d (m/floor p)))
:probability (fn ^double [^IntegerDistribution d ^double p] (.probability d (m/floor p)))
:sample (fn ^long [^IntegerDistribution d] (.sample d))
:dimensions (constantly 1)
:source-object identity
:continuous? (constantly false)}
prot/UnivariateDistributionProto
{:mean (fn ^double [^IntegerDistribution d] (.getNumericalMean d))
:variance (fn ^double [^IntegerDistribution d] (.getNumericalVariance d))
:lower-bound (fn ^long [^IntegerDistribution d] (.getSupportLowerBound d))
:upper-bound (fn ^long [^IntegerDistribution d] (.getSupportUpperBound d))}
prot/RNGProto
{:drandom (fn ^double [^IntegerDistribution d] (unchecked-double (.sample d)))
:frandom (fn ^double [^IntegerDistribution d] (unchecked-float (.sample d)))
:lrandom (fn ^long [^IntegerDistribution d] (unchecked-long (.sample d)))
:irandom (fn ^long [^IntegerDistribution d] (.sample d))
:->seq (fn
([^IntegerDistribution d] (repeatedly #(.sample d)))
([^IntegerDistribution d n] (repeatedly n #(.sample d))))
:set-seed! (fn [^IntegerDistribution d ^double seed] (.reseedRandomGenerator d seed) d)})
(extend MultivariateNormalDistribution
prot/DistributionProto
{:pdf (fn ^double [^MultivariateNormalDistribution d v] (.density d (m/seq->double-array v)))
:lpdf (fn ^double [^MultivariateNormalDistribution d v] (m/log (.density d (m/seq->double-array v))))
:sample (fn [^MultivariateNormalDistribution d] (vec (.sample d)))
:dimensions (fn ^long [^MultivariateNormalDistribution d] (.getDimension d))
:source-object identity
:continuous? (constantly true)}
prot/MultivariateDistributionProto
{:means (fn [^MultivariateNormalDistribution d] (vec (.getMeans d)))
:covariance (fn [^MultivariateNormalDistribution d]
(let [^org.apache.commons.math3.linear.Array2DRowRealMatrix cv (.getCovariances d)]
(m/double-double-array->seq (.getDataRef cv))))}
prot/RNGProto
{:drandom (fn [^MultivariateNormalDistribution d] (vec (.sample d)))
:frandom (fn [^MultivariateNormalDistribution d] (mapv unchecked-float (.sample d)))
:lrandom (fn [^MultivariateNormalDistribution d] (mapv unchecked-long (.sample d)))
:irandom (fn [^MultivariateNormalDistribution d] (mapv unchecked-int (.sample d)))
:->seq (fn
([^MultivariateNormalDistribution d] (repeatedly #(vec (.sample d))))
([^MultivariateNormalDistribution d n] (repeatedly n #(vec (.sample d)))))
:set-seed! (fn [^MultivariateNormalDistribution d ^double seed] (.reseedRandomGenerator d seed) d)})
(defmulti
^{:doc "Create distribution object.
* First parameter is distribution as a `:key`.
* Second parameter is a map with configuration.
All distributions accept `rng` under `:rng` key (default: [[default-rng]]) and some of them accept `inverse-cumm-accuracy` (default set to `1e-9`)."
:metadoc/categories #{:dist}}
distribution (fn ([k _] k) ([k] k)))
(defmacro ^:private make-acm-distr
[nm obj ks vs]
(let [or-map (zipmap ks vs)]
`(do
(extend ~obj
prot/DistributionIdProto
{:distribution-id (fn [d#] ~nm)
:distribution-parameters (fn [d#] [~@(conj (map keyword ks) :rng)])})
(defmethod distribution ~nm
([n# {:keys [~@ks]
:or ~or-map
:as all#}]
(let [^RandomGenerator r# (or (:rng all#) (rng :jvm))]
(new ~obj r# ~@ks)))
([n#] (distribution ~nm {}))))))
(make-acm-distr :beta BetaDistribution