forked from GalSim-developers/GalSim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_random.py
More file actions
2245 lines (2019 loc) · 85.5 KB
/
test_random.py
File metadata and controls
2245 lines (2019 loc) · 85.5 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
# Copyright (c) 2012-2026 by the GalSim developers team on GitHub
# https://github.com/GalSim-developers
#
# This file is part of GalSim: The modular galaxy image simulation toolkit.
# https://github.com/GalSim-developers/GalSim
#
# GalSim is free software: redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions, and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
#
import numpy as np
import os
import math
import warnings
import galsim
from galsim_test_helpers import *
from galsim.utilities import single_threaded
#
# Note: all tests below were generated using the python interface to the RNG. Eventually need tests
# for comparison against the C++!
#
precision = 10
# decimal point at which agreement is required for all double precision tests
precisionD = precision
precisionF = 5 # precision=10 does not make sense at single precision
precisionS = 1 # "precision" also a silly concept for ints, but allows all 4 tests to run in one go
precisionI = 1
# The number of values to generate when checking the mean and variance calculations.
# This is currently low enough to not dominate the time of the unit tests, but when changing
# something, it may be useful to add a couple zeros while testing.
nvals = 100000
testseed = 1000 # seed used for UniformDeviate for all tests
# Warning! If you change testseed, then all of the *Result variables below must change as well.
if is_jax_galsim():
uResult = (0.0303194914, 0.0910759047, 0.1208923360)
gMean = 4.7
gSigma = 3.2
gResult = (-1.3035798312, 0.4306917482, 0.9542795210)
bN = 10
bp = 0.7
bResult = (7, 6, 7)
pMean = 7
pResult = (5, 8, 6)
wA = 4.0
wB = 9.0
wResult = (3.7699892848, 5.0030654033, 5.3921485618)
gammaK = 1.5
gammaTheta = 4.5
gammaResult = (0.7985896238, 22.0508132116, 33.1369864688)
chi2N = 30
chi2Result = (19.2174896025, 47.3448788104, 55.8177548146)
else:
# the right answer for the first three uniform deviates produced from testseed
uResult = (0.11860922840423882, 0.21456799632869661, 0.43088198406621814)
# mean, sigma to use for Gaussian tests
gMean = 4.7
gSigma = 3.2
# the right answer for the first three Gaussian deviates produced from testseed
gResult = (6.3344979808161215, 6.2082355273987861, -0.069894693358302007)
# N, p to use for binomial tests
bN = 10
bp = 0.7
# the right answer for the first three binomial deviates produced from testseed
bResult = (9, 8, 7)
# mean to use for Poisson tests
pMean = 7
# the right answer for the first three Poisson deviates produced from testseed
pResult = (4, 5, 6)
# a & b to use for Weibull tests
wA = 4.
wB = 9.
# Tabulated results for Weibull
wResult = (5.3648053017485591, 6.3093033550873878, 7.7982696798921074)
# k & theta to use for Gamma tests
gammaK = 1.5
gammaTheta = 4.5
# Tabulated results for Gamma
gammaResult = (4.7375613139927157, 15.272973580418618, 21.485016362839747)
# n to use for Chi2 tests
chi2N = 30
# Tabulated results for Chi2
chi2Result = (32.209933900954049, 50.040002656028513, 24.301442486313896)
#function and min&max to use for DistDeviate function call tests
dmin=0.0
dmax=2.0
def dfunction(x):
return x*x
# Tabulated results for DistDeviate function call
dFunctionResult = (0.9826461346196363, 1.1973307331701328, 1.5105900949284945)
# x and p arrays and interpolant to use for DistDeviate LookupTable tests
dx=[0.0, 1.0, 1.000000001, 2.999999999, 3.0, 4.0]
dp=[0.1, 0.1, 0.0 , 0.0 , 0.1, 0.1]
dLookupTable=galsim.LookupTable(x=dx,f=dp,interpolant='linear')
# Tabulated results for DistDeviate LookupTable call
dLookupTableResult = (0.23721845680847731, 0.42913599265739233, 0.86176396813243539)
# File with the same values
dLookupTableFile = os.path.join('random_data','dLookupTable.dat')
@timer
def test_uniform():
"""Test uniform random number generator
"""
u = galsim.UniformDeviate(testseed)
u2 = u.duplicate()
u3 = galsim.UniformDeviate(u.serialize())
testResult = (u(), u(), u())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(uResult), precision,
err_msg='Wrong uniform random number sequence generated')
testResult = (u2(), u2(), u2())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(uResult), precision,
err_msg='Wrong uniform random number sequence generated with duplicate')
testResult = (u3(), u3(), u3())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(uResult), precision,
err_msg='Wrong uniform random number sequence generated from serialize')
# Check that the mean and variance come out right
u = galsim.UniformDeviate(testseed)
vals = [u() for i in range(nvals)]
mean = np.mean(vals)
var = np.var(vals)
mu = 1./2.
v = 1./12.
print('mean = ',mean,' true mean = ',mu)
print('var = ',var,' true var = ',v)
np.testing.assert_almost_equal(mean, mu, 1,
err_msg='Wrong mean from UniformDeviate')
np.testing.assert_almost_equal(var, v, 1,
err_msg='Wrong variance from UniformDeviate')
# Check discard
u2 = galsim.UniformDeviate(testseed)
u2.discard(nvals)
v1, v2 = u(), u2()
print('after %d vals, next one is %s, %s'%(nvals,v1,v2))
assert v1 == v2
assert u.has_reliable_discard
assert not u.generates_in_pairs
# Check seed, reset
u.seed(testseed)
testResult2 = (u(), u(), u())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong uniform random number sequence generated after seed')
u.reset(testseed)
testResult2 = (u(), u(), u())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong uniform random number sequence generated after reset(seed)')
rng = galsim.BaseDeviate(testseed)
u.reset(rng)
testResult2 = (u(), u(), u())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong uniform random number sequence generated after reset(rng)')
# Check raw
u2.reset(testseed)
u2.discard(3)
np.testing.assert_equal(u.raw(), u2.raw(),
err_msg='Uniform deviates generate different raw values')
rng2 = galsim.BaseDeviate(testseed)
rng2.discard(4)
np.testing.assert_equal(rng.raw(), rng2.raw(),
err_msg='BaseDeviates generate different raw values after discard')
# Check that two connected uniform deviates work correctly together.
u2 = galsim.UniformDeviate(testseed)
u.reset(u2)
testResult2 = (u(), u2(), u())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong uniform random number sequence generated using two uds')
u.seed(testseed)
testResult2 = (u2(), u(), u2())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong uniform random number sequence generated using two uds after seed')
# Check that seeding with the time works (although we cannot check the output).
# We're mostly just checking that this doesn't raise an exception.
# The output could be anything.
u.seed()
testResult2 = (u(), u(), u())
assert testResult2 != testResult
u.reset()
testResult3 = (u(), u(), u())
assert testResult3 != testResult
assert testResult3 != testResult2
u.reset()
testResult4 = (u(), u(), u())
assert testResult4 != testResult
assert testResult4 != testResult2
assert testResult4 != testResult3
u = galsim.UniformDeviate()
testResult5 = (u(), u(), u())
assert testResult5 != testResult
assert testResult5 != testResult2
assert testResult5 != testResult3
assert testResult5 != testResult4
# Test generate
u.seed(testseed)
test_array = np.empty(3)
if is_jax_galsim():
test_array = u.generate(test_array)
else:
u.generate(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(uResult), precision,
err_msg='Wrong uniform random number sequence from generate.')
# Test add_generate
u.seed(testseed)
if is_jax_galsim():
test_array = u.add_generate(test_array)
else:
u.add_generate(test_array)
np.testing.assert_array_almost_equal(
test_array, 2.*np.array(uResult), precision,
err_msg='Wrong uniform random number sequence from generate.')
# Test generate with a float32 array
u.seed(testseed)
test_array = np.empty(3, dtype=np.float32)
if is_jax_galsim():
test_array = u.generate(test_array)
else:
u.generate(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(uResult), precisionF,
err_msg='Wrong uniform random number sequence from generate.')
# Test add_generate
u.seed(testseed)
if is_jax_galsim():
test_array = u.add_generate(test_array)
else:
u.add_generate(test_array)
np.testing.assert_array_almost_equal(
test_array, 2.*np.array(uResult), precisionF,
err_msg='Wrong uniform random number sequence from generate.')
# Check that generated values are independent of number of threads.
u1 = galsim.UniformDeviate(testseed)
u2 = galsim.UniformDeviate(testseed)
v1 = np.empty(555)
v2 = np.empty(555)
with single_threaded():
if is_jax_galsim():
v1 = u1.generate(v1)
else:
u1.generate(v1)
with single_threaded(num_threads=10):
if is_jax_galsim():
v2 = u2.generate(v2)
else:
u2.generate(v2)
np.testing.assert_array_equal(v1, v2)
with single_threaded():
if is_jax_galsim():
v1 = u1.add_generate(v1)
else:
u1.add_generate(v1)
with single_threaded(num_threads=10):
if is_jax_galsim():
v2 = u2.add_generate(v2)
else:
u2.add_generate(v2)
np.testing.assert_array_equal(v1, v2)
# Check picklability
check_pickle(u, lambda x: x.serialize(), random=True)
check_pickle(u, lambda x: (x(), x(), x(), x()), random=True)
check_pickle(u, random=True)
check_pickle(rng, random=True)
assert 'UniformDeviate' in repr(u)
assert 'UniformDeviate' in str(u)
assert isinstance(eval(repr(u)), galsim.UniformDeviate)
assert isinstance(eval(str(u)), galsim.UniformDeviate)
assert isinstance(eval(repr(rng)), galsim.BaseDeviate)
assert isinstance(eval(str(rng)), galsim.BaseDeviate)
# Check that we can construct a UniformDeviate from None, and that it depends on dev/random.
u1 = galsim.UniformDeviate(None)
u2 = galsim.UniformDeviate(None)
assert u1 != u2, "Consecutive UniformDeviate(None) compared equal!"
# We shouldn't be able to construct a UniformDeviate from anything but a BaseDeviate, int, str,
# or None.
assert_raises(TypeError, galsim.UniformDeviate, dict())
assert_raises(TypeError, galsim.UniformDeviate, list())
assert_raises(TypeError, galsim.UniformDeviate, set())
assert_raises(TypeError, u.seed, '123')
assert_raises(TypeError, u.seed, 12.3)
@timer
def test_gaussian():
"""Test Gaussian random number generator
"""
g = galsim.GaussianDeviate(testseed, mean=gMean, sigma=gSigma)
g2 = g.duplicate()
g3 = galsim.GaussianDeviate(g.serialize(), mean=gMean, sigma=gSigma)
testResult = (g(), g(), g())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(gResult), precision,
err_msg='Wrong Gaussian random number sequence generated')
testResult = (g2(), g2(), g2())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(gResult), precision,
err_msg='Wrong Gaussian random number sequence generated with duplicate')
testResult = (g3(), g3(), g3())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(gResult), precision,
err_msg='Wrong Gaussian random number sequence generated from serialize')
# Check that the mean and variance come out right
g = galsim.GaussianDeviate(testseed, mean=gMean, sigma=gSigma)
vals = [g() for i in range(nvals)]
mean = np.mean(vals)
var = np.var(vals)
mu = gMean
v = gSigma**2
print('mean = ',mean,' true mean = ',mu)
print('var = ',var,' true var = ',v)
np.testing.assert_almost_equal(mean, mu, 1,
err_msg='Wrong mean from GaussianDeviate')
np.testing.assert_almost_equal(var, v, 0,
err_msg='Wrong variance from GaussianDeviate')
# Check discard
g2 = galsim.GaussianDeviate(testseed, mean=gMean, sigma=gSigma)
g2.discard(nvals)
v1,v2 = g(),g2()
print('after %d vals, next one is %s, %s'%(nvals,v1,v2))
assert v1 == v2
if is_jax_galsim():
# jax doesn't have this issue
assert g.has_reliable_discard
assert not g.generates_in_pairs
else:
# Note: For Gaussian, this only works if nvals is even.
g2 = galsim.GaussianDeviate(testseed, mean=gMean, sigma=gSigma)
g2.discard(nvals+1, suppress_warnings=True)
v1,v2 = g(),g2()
print('after %d vals, next one is %s, %s'%(nvals+1,v1,v2))
assert v1 != v2
assert g.has_reliable_discard
assert g.generates_in_pairs
# If don't explicitly suppress the warning, then a warning is emitted when n is odd.
g2 = galsim.GaussianDeviate(testseed, mean=gMean, sigma=gSigma)
if is_jax_galsim():
pass
else:
# jax doesn't do this
with assert_warns(galsim.GalSimWarning):
g2.discard(nvals+1)
# Check seed, reset
g.seed(testseed)
testResult2 = (g(), g(), g())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong Gaussian random number sequence generated after seed')
g.reset(testseed)
testResult2 = (g(), g(), g())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong Gaussian random number sequence generated after reset(seed)')
rng = galsim.BaseDeviate(testseed)
g.reset(rng)
testResult2 = (g(), g(), g())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong Gaussian random number sequence generated after reset(rng)')
ud = galsim.UniformDeviate(testseed)
g.reset(ud)
testResult = (g(), g(), g())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong Gaussian random number sequence generated after reset(ud)')
# Check that two connected Gaussian deviates work correctly together.
g2 = galsim.GaussianDeviate(testseed, mean=gMean, sigma=gSigma)
g.reset(g2)
# Note: GaussianDeviate generates two values at a time, so we have to compare them in pairs.
testResult2 = (g(), g(), g2())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong Gaussian random number sequence generated using two gds')
g.seed(testseed)
# For the same reason, after seeding one, we need to manually clear the other's cache:
g2.clearCache()
testResult2 = (g2(), g2(), g())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong Gaussian random number sequence generated using two gds after seed')
# Check that seeding with the time works (although we cannot check the output).
# We're mostly just checking that this doesn't raise an exception.
# The output could be anything.
g.seed()
testResult2 = (g(), g(), g())
assert testResult2 != testResult
g.reset()
testResult3 = (g(), g(), g())
assert testResult3 != testResult
assert testResult3 != testResult2
g.reset()
testResult4 = (g(), g(), g())
assert testResult4 != testResult
assert testResult4 != testResult2
assert testResult4 != testResult3
g = galsim.GaussianDeviate(mean=gMean, sigma=gSigma)
testResult5 = (g(), g(), g())
assert testResult5 != testResult
assert testResult5 != testResult2
assert testResult5 != testResult3
assert testResult5 != testResult4
# Test generate
g.seed(testseed)
test_array = np.empty(3)
if is_jax_galsim():
test_array = g.generate(test_array)
else:
g.generate(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(gResult), precision,
err_msg='Wrong Gaussian random number sequence from generate.')
# Test generate_from_variance.
g2 = galsim.GaussianDeviate(testseed, mean=5, sigma=0.3)
g3 = galsim.GaussianDeviate(testseed, mean=5, sigma=0.3)
test_array = np.empty(3)
test_array.fill(gSigma**2)
if is_jax_galsim():
test_array = g2.generate_from_variance(test_array)
else:
g2.generate_from_variance(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(gResult)-gMean, precision,
err_msg='Wrong Gaussian random number sequence from generate_from_variance.')
# After running generate_from_variance, it should be back to using the specified mean, sigma.
# Note: need to round up to even number for discard, since gd generates 2 at a time.
if is_jax_galsim():
g3.discard(len(test_array))
else:
g3.discard((len(test_array)+1)//2 * 2)
print('g2,g3 = ',g2(),g3())
assert g2() == g3()
# Test generate with a float32 array.
g.seed(testseed)
test_array = np.empty(3, dtype=np.float32)
if is_jax_galsim():
test_array = g.generate(test_array)
else:
g.generate(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(gResult), precisionF,
err_msg='Wrong Gaussian random number sequence from generate.')
# Test generate_from_variance.
g2.seed(testseed)
test_array = np.empty(3, dtype=np.float32)
test_array.fill(gSigma**2)
if is_jax_galsim():
test_array = g2.generate_from_variance(test_array)
else:
g2.generate_from_variance(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(gResult)-gMean, precisionF,
err_msg='Wrong Gaussian random number sequence from generate_from_variance.')
# Check that generated values are independent of number of threads.
g1 = galsim.GaussianDeviate(testseed, mean=53, sigma=1.3)
g2 = galsim.GaussianDeviate(testseed, mean=53, sigma=1.3)
v1 = np.empty(555)
v2 = np.empty(555)
with single_threaded():
if is_jax_galsim():
v1 = g1.generate(v1)
else:
g1.generate(v1)
with single_threaded(num_threads=10):
if is_jax_galsim():
v2 = g2.generate(v2)
else:
g2.generate(v2)
np.testing.assert_array_equal(v1, v2)
with single_threaded():
if is_jax_galsim():
v1 = g1.add_generate(v1)
else:
g1.add_generate(v1)
with single_threaded(num_threads=10):
if is_jax_galsim():
v2 = g2.add_generate(v2)
else:
g2.add_generate(v2)
np.testing.assert_array_equal(v1, v2)
ud = galsim.UniformDeviate(testseed + 3)
ud.generate(v1)
v1 += 6.7
if is_jax_galsim():
# jax galsim makes a copy
v2 = v1.copy()
else:
v2[:] = v1
with single_threaded():
if is_jax_galsim():
v1 = g1.generate_from_variance(v1)
else:
g1.generate_from_variance(v1)
with single_threaded(num_threads=10):
if is_jax_galsim():
v2 = g2.generate_from_variance(v2)
else:
g2.generate_from_variance(v2)
np.testing.assert_array_equal(v1, v2)
# Check picklability
check_pickle(g, lambda x: (x.serialize(), x.mean, x.sigma), random=True)
check_pickle(g, lambda x: (x(), x(), x(), x()), random=True)
check_pickle(g, random=True)
assert 'GaussianDeviate' in repr(g)
assert 'GaussianDeviate' in str(g)
assert isinstance(eval(repr(g)), galsim.GaussianDeviate)
assert isinstance(eval(str(g)), galsim.GaussianDeviate)
# Check that we can construct a GaussianDeviate from None, and that it depends on dev/random.
g1 = galsim.GaussianDeviate(None)
g2 = galsim.GaussianDeviate(None)
assert g1 != g2, "Consecutive GaussianDeviate(None) compared equal!"
# We shouldn't be able to construct a GaussianDeviate from anything but a BaseDeviate, int, str,
# or None.
assert_raises(TypeError, galsim.GaussianDeviate, dict())
assert_raises(TypeError, galsim.GaussianDeviate, list())
assert_raises(TypeError, galsim.GaussianDeviate, set())
assert_raises(ValueError, galsim.GaussianDeviate, testseed, mean=1, sigma=-1)
@timer
def test_binomial():
"""Test binomial random number generator
"""
b = galsim.BinomialDeviate(testseed, N=bN, p=bp)
b2 = b.duplicate()
b3 = galsim.BinomialDeviate(b.serialize(), N=bN, p=bp)
testResult = (b(), b(), b())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(bResult), precision,
err_msg='Wrong binomial random number sequence generated')
testResult = (b2(), b2(), b2())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(bResult), precision,
err_msg='Wrong binomial random number sequence generated with duplicate')
testResult = (b3(), b3(), b3())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(bResult), precision,
err_msg='Wrong binomial random number sequence generated from serialize')
# Check that the mean and variance come out right
b = galsim.BinomialDeviate(testseed, N=bN, p=bp)
vals = [b() for i in range(nvals)]
mean = np.mean(vals)
var = np.var(vals)
mu = bN*bp
v = bN*bp*(1.-bp)
print('mean = ',mean,' true mean = ',mu)
print('var = ',var,' true var = ',v)
np.testing.assert_almost_equal(mean, mu, 1,
err_msg='Wrong mean from BinomialDeviate')
np.testing.assert_almost_equal(var, v, 1,
err_msg='Wrong variance from BinomialDeviate')
# Check discard
b2 = galsim.BinomialDeviate(testseed, N=bN, p=bp)
b2.discard(nvals)
v1,v2 = b(),b2()
print('after %d vals, next one is %s, %s'%(nvals,v1,v2))
assert v1 == v2
assert b.has_reliable_discard
assert not b.generates_in_pairs
# Check seed, reset
b.seed(testseed)
testResult2 = (b(), b(), b())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong binomial random number sequence generated after seed')
b.reset(testseed)
testResult2 = (b(), b(), b())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong binomial random number sequence generated after reset(seed)')
rng = galsim.BaseDeviate(testseed)
b.reset(rng)
testResult2 = (b(), b(), b())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong binomial random number sequence generated after reset(rng)')
ud = galsim.UniformDeviate(testseed)
b.reset(ud)
testResult = (b(), b(), b())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong binomial random number sequence generated after reset(ud)')
# Check that two connected binomial deviates work correctly together.
b2 = galsim.BinomialDeviate(testseed, N=bN, p=bp)
b.reset(b2)
testResult2 = (b(), b2(), b())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong binomial random number sequence generated using two bds')
b.seed(testseed)
testResult2 = (b2(), b(), b2())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong binomial random number sequence generated using two bds after seed')
# Check that seeding with the time works (although we cannot check the output).
# We're mostly just checking that this doesn't raise an exception.
# The output could be anything. However, in this case, there are few enough options
# for the output that occasionally two of these match. So we don't do the normal
# testResult2 != testResult, etc.
b.seed()
testResult2 = (b(), b(), b())
#assert testResult2 != testResult
b.reset()
testResult3 = (b(), b(), b())
#assert testResult3 != testResult
#assert testResult3 != testResult2
b.reset()
testResult4 = (b(), b(), b())
#assert testResult4 != testResult
#assert testResult4 != testResult2
#assert testResult4 != testResult3
b = galsim.BinomialDeviate(N=bN, p=bp)
testResult5 = (b(), b(), b())
#assert testResult5 != testResult
#assert testResult5 != testResult2
#assert testResult5 != testResult3
#assert testResult5 != testResult4
# Test generate
b.seed(testseed)
test_array = np.empty(3)
if is_jax_galsim():
test_array = b.generate(test_array)
else:
b.generate(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(bResult), precision,
err_msg='Wrong binomial random number sequence from generate.')
# Test generate with an int array
b.seed(testseed)
test_array = np.empty(3, dtype=int)
if is_jax_galsim():
test_array = b.generate(test_array)
else:
b.generate(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(bResult), precisionI,
err_msg='Wrong binomial random number sequence from generate.')
# Check that generated values are independent of number of threads.
b1 = galsim.BinomialDeviate(testseed, N=17, p=0.7)
b2 = galsim.BinomialDeviate(testseed, N=17, p=0.7)
v1 = np.empty(555)
v2 = np.empty(555)
with single_threaded():
if is_jax_galsim():
v1 = b1.generate(v1)
else:
b1.generate(v1)
with single_threaded(num_threads=10):
if is_jax_galsim():
v2 = b2.generate(v2)
else:
b2.generate(v2)
np.testing.assert_array_equal(v1, v2)
with single_threaded():
if is_jax_galsim():
v1 = b1.add_generate(v1)
else:
b1.add_generate(v1)
with single_threaded(num_threads=10):
if is_jax_galsim():
v2 = b2.add_generate(v2)
else:
b2.add_generate(v2)
np.testing.assert_array_equal(v1, v2)
# Check picklability
check_pickle(b, lambda x: (x.serialize(), x.n, x.p), random=True)
check_pickle(b, lambda x: (x(), x(), x(), x()), random=True)
check_pickle(b, random=True)
assert 'BinomialDeviate' in repr(b)
assert 'BinomialDeviate' in str(b)
assert isinstance(eval(repr(b)), galsim.BinomialDeviate)
assert isinstance(eval(str(b)), galsim.BinomialDeviate)
# Check that we can construct a BinomialDeviate from None, and that it depends on dev/random.
b1 = galsim.BinomialDeviate(None)
b2 = galsim.BinomialDeviate(None)
assert b1 != b2, "Consecutive BinomialDeviate(None) compared equal!"
# We shouldn't be able to construct a BinomialDeviate from anything but a BaseDeviate, int, str,
# or None.
assert_raises(TypeError, galsim.BinomialDeviate, dict())
assert_raises(TypeError, galsim.BinomialDeviate, list())
assert_raises(TypeError, galsim.BinomialDeviate, set())
@timer
def test_poisson():
"""Test Poisson random number generator
"""
p = galsim.PoissonDeviate(testseed, mean=pMean)
p2 = p.duplicate()
p3 = galsim.PoissonDeviate(p.serialize(), mean=pMean)
testResult = (p(), p(), p())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(pResult), precision,
err_msg='Wrong Poisson random number sequence generated')
testResult = (p2(), p2(), p2())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(pResult), precision,
err_msg='Wrong Poisson random number sequence generated with duplicate')
testResult = (p3(), p3(), p3())
np.testing.assert_array_almost_equal(
np.array(testResult), np.array(pResult), precision,
err_msg='Wrong Poisson random number sequence generated from serialize')
# Check that the mean and variance come out right
p = galsim.PoissonDeviate(testseed, mean=pMean)
vals = [p() for i in range(nvals)]
mean = np.mean(vals)
var = np.var(vals)
mu = pMean
v = pMean
print('mean = ',mean,' true mean = ',mu)
print('var = ',var,' true var = ',v)
np.testing.assert_almost_equal(mean, mu, 1,
err_msg='Wrong mean from PoissonDeviate')
np.testing.assert_almost_equal(var, v, 1,
err_msg='Wrong variance from PoissonDeviate')
# Check discard
p2 = galsim.PoissonDeviate(testseed, mean=pMean)
p2.discard(nvals, suppress_warnings=True)
v1,v2 = p(),p2()
print('With mean = %d, after %d vals, next one is %s, %s'%(pMean,nvals,v1,v2))
assert v1 == v2
# With a very small mean value, Poisson reliably only uses 1 rng per value.
# But at only slightly larger means, it sometimes uses two rngs for a single value.
# Basically anything >= 10 causes this next test to have v1 != v2
high_mean = 10
p = galsim.PoissonDeviate(testseed, mean=high_mean)
p2 = galsim.PoissonDeviate(testseed, mean=high_mean)
vals = [p() for i in range(nvals)]
p2.discard(nvals, suppress_warnings=True)
v1,v2 = p(),p2()
print('With mean = %d, after %d vals, next one is %s, %s'%(high_mean,nvals,v1,v2))
if is_jax_galsim():
# jax always discards reliably
assert v1 == v2
assert p.has_reliable_discard
else:
assert v1 != v2
assert not p.has_reliable_discard
assert not p.generates_in_pairs
# Discard normally emits a warning for Poisson
p2 = galsim.PoissonDeviate(testseed, mean=pMean)
if is_jax_galsim():
# jax always discards reliably
p2.discard(nvals)
else:
with assert_warns(galsim.GalSimWarning):
p2.discard(nvals)
# Check seed, reset
p = galsim.PoissonDeviate(testseed, mean=pMean)
p.seed(testseed)
testResult2 = (p(), p(), p())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong poisson random number sequence generated after seed')
p.reset(testseed)
testResult2 = (p(), p(), p())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong poisson random number sequence generated after reset(seed)')
rng = galsim.BaseDeviate(testseed)
p.reset(rng)
testResult2 = (p(), p(), p())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong poisson random number sequence generated after reset(rng)')
ud = galsim.UniformDeviate(testseed)
p.reset(ud)
testResult = (p(), p(), p())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong poisson random number sequence generated after reset(ud)')
# Check that two connected poisson deviates work correctly together.
p2 = galsim.PoissonDeviate(testseed, mean=pMean)
p.reset(p2)
testResult2 = (p(), p2(), p())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong poisson random number sequence generated using two pds')
p.seed(testseed)
testResult2 = (p2(), p(), p2())
np.testing.assert_array_equal(
np.array(testResult), np.array(testResult2),
err_msg='Wrong poisson random number sequence generated using two pds after seed')
# Check that seeding with the time works (although we cannot check the output).
# We're mostly just checking that this doesn't raise an exception.
# The output could be anything. However, in this case, there are few enough options
# for the output that occasionally two of these match. So we don't do the normal
# testResult2 != testResult, etc.
p.seed()
testResult2 = (p(), p(), p())
#assert testResult2 != testResult
p.reset()
testResult3 = (p(), p(), p())
#assert testResult3 != testResult
#assert testResult3 != testResult2
p.reset()
testResult4 = (p(), p(), p())
#assert testResult4 != testResult
#assert testResult4 != testResult2
#assert testResult4 != testResult3
p = galsim.PoissonDeviate(mean=pMean)
testResult5 = (p(), p(), p())
#assert testResult5 != testResult
#assert testResult5 != testResult2
#assert testResult5 != testResult3
#assert testResult5 != testResult4
# Test generate
p.seed(testseed)
test_array = np.empty(3)
if is_jax_galsim():
test_array = p.generate(test_array)
else:
p.generate(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(pResult), precision,
err_msg='Wrong poisson random number sequence from generate.')
# Test generate with an int array
p.seed(testseed)
test_array = np.empty(3, dtype=int)
if is_jax_galsim():
test_array = p.generate(test_array)
else:
p.generate(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(pResult), precisionI,
err_msg='Wrong poisson random number sequence from generate.')
# Test generate_from_expectation
p2 = galsim.PoissonDeviate(testseed, mean=77)
test_array = np.array([pMean]*3, dtype=int)
if is_jax_galsim():
test_array = p2.generate_from_expectation(test_array)
else:
p2.generate_from_expectation(test_array)
np.testing.assert_array_almost_equal(
test_array, np.array(pResult), precisionI,
err_msg='Wrong poisson random number sequence from generate_from_expectation.')
# After generating, it should be back to mean=77
test_array2 = np.array([p2() for i in range(100)])
print('test_array2 = ',test_array2)
print('mean = ',test_array2.mean())
assert np.isclose(test_array2.mean(), 77, atol=2)
# Check that generated values are independent of number of threads.
# This should be trivial, since Poisson disables multi-threading, but check anyway.
p1 = galsim.PoissonDeviate(testseed, mean=77)
p2 = galsim.PoissonDeviate(testseed, mean=77)
v1 = np.empty(555)
v2 = np.empty(555)
with single_threaded():
if is_jax_galsim():
v1 = p1.generate(v1)
else:
p1.generate(v1)
with single_threaded(num_threads=10):
if is_jax_galsim():
v2 = p2.generate(v2)
else:
p2.generate(v2)
np.testing.assert_array_equal(v1, v2)
with single_threaded():
if is_jax_galsim():
v1 = p1.add_generate(v1)
else:
p1.add_generate(v1)
with single_threaded(num_threads=10):
if is_jax_galsim():
v2 = p2.add_generate(v2)
else:
p2.add_generate(v2)
np.testing.assert_array_equal(v1, v2)
# Check picklability
check_pickle(p, lambda x: (x.serialize(), x.mean), random=True)
check_pickle(p, lambda x: (x(), x(), x(), x()), random=True)
check_pickle(p, random=True)
assert 'PoissonDeviate' in repr(p)
assert 'PoissonDeviate' in str(p)
assert isinstance(eval(repr(p)), galsim.PoissonDeviate)
assert isinstance(eval(str(p)), galsim.PoissonDeviate)
# Check that we can construct a PoissonDeviate from None, and that it depends on dev/random.
p1 = galsim.PoissonDeviate(None)
p2 = galsim.PoissonDeviate(None)
assert p1 != p2, "Consecutive PoissonDeviate(None) compared equal!"
# We shouldn't be able to construct a PoissonDeviate from anything but a BaseDeviate, int, str,
# or None.
assert_raises(TypeError, galsim.PoissonDeviate, dict())
assert_raises(TypeError, galsim.PoissonDeviate, list())
assert_raises(TypeError, galsim.PoissonDeviate, set())
@timer
def test_poisson_highmean(run_slow):
"""Test Poisson random number generator with high (>2^30) mean (cf. Issue #881)
It turns out that the boost poisson deviate class that we use maxes out at 2^31 and wraps
around to -2^31. We have code to automatically switch over to using a Gaussian deviate
instead if the mean > 2^30 (factor of 2 from the problem to be safe). Check that this
works properly.
"""
mean_vals =[ 2**30 + 50, # Uses Gaussian
2**30 - 50, # Uses Poisson
2**30, # Uses Poisson (highest value of mean that does)
2**31, # This is where problems happen if not using Gaussian
5.e20, # Definitely would have problems with normal implementation.
]