forked from pymc-devs/pymc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_distributions_random.py
1884 lines (1588 loc) · 67.8 KB
/
test_distributions_random.py
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 2020 The PyMC Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import sys
from contextlib import ExitStack as does_not_raise
import aesara
import numpy as np
import numpy.random as nr
import pytest
import scipy.stats as st
from scipy import linalg
from scipy.special import expit
import pymc3 as pm
from pymc3.aesaraf import change_rv_size, floatX, intX
from pymc3.distributions.dist_math import clipped_beta_rvs
from pymc3.distributions.shape_utils import to_tuple
from pymc3.exceptions import ShapeError
from pymc3.tests.helpers import SeededTest
from pymc3.tests.test_distributions import (
Domain,
I,
Nat,
NatSmall,
PdMatrix,
PdMatrixChol,
PdMatrixCholUpper,
R,
RandomPdMatrix,
RealMatrix,
Rplus,
Rplusbig,
Rplusdunif,
Runif,
Simplex,
Unit,
Vector,
build_model,
product,
)
def pymc3_random(
dist,
paramdomains,
ref_rand,
valuedomain=Domain([0]),
size=10000,
alpha=0.05,
fails=10,
extra_args=None,
model_args=None,
):
if model_args is None:
model_args = {}
model, param_vars = build_model(dist, valuedomain, paramdomains, extra_args)
model_dist = change_rv_size(model.named_vars["value"], size, expand=True)
pymc_rand = aesara.function([], model_dist)
domains = paramdomains.copy()
for pt in product(domains, n_samples=100):
pt = pm.Point(pt, model=model)
pt.update(model_args)
# Update the shared parameter variables in `param_vars`
for k, v in pt.items():
nv = param_vars.get(k, model.named_vars.get(k))
if nv.name in param_vars:
param_vars[nv.name].set_value(v)
p = alpha
# Allow KS test to fail (i.e., the samples be different)
# a certain number of times. Crude, but necessary.
f = fails
while p <= alpha and f > 0:
s0 = pymc_rand()
s1 = floatX(ref_rand(size=size, **pt))
_, p = st.ks_2samp(np.atleast_1d(s0).flatten(), np.atleast_1d(s1).flatten())
f -= 1
assert p > alpha, str(pt)
def pymc3_random_discrete(
dist,
paramdomains,
valuedomain=Domain([0]),
ref_rand=None,
size=100000,
alpha=0.05,
fails=20,
):
model, param_vars = build_model(dist, valuedomain, paramdomains)
model_dist = change_rv_size(model.named_vars["value"], size, expand=True)
pymc_rand = aesara.function([], model_dist)
domains = paramdomains.copy()
for pt in product(domains, n_samples=100):
pt = pm.Point(pt, model=model)
p = alpha
# Update the shared parameter variables in `param_vars`
for k, v in pt.items():
nv = param_vars.get(k, model.named_vars.get(k))
if nv.name in param_vars:
param_vars[nv.name].set_value(v)
# Allow Chisq test to fail (i.e., the samples be different)
# a certain number of times.
f = fails
while p <= alpha and f > 0:
o = pymc_rand()
e = intX(ref_rand(size=size, **pt))
o = np.atleast_1d(o).flatten()
e = np.atleast_1d(e).flatten()
observed = dict(zip(*np.unique(o, return_counts=True)))
expected = dict(zip(*np.unique(e, return_counts=True)))
for e in expected.keys():
expected[e] = (observed.get(e, 0), expected[e])
k = np.array([v for v in expected.values()])
if np.all(k[:, 0] == k[:, 1]):
p = 1.0
else:
_, p = st.chisquare(k[:, 0], k[:, 1])
f -= 1
assert p > alpha, str(pt)
class BaseTestCases:
class BaseTestCase(SeededTest):
shape = 5
# the following are the default values of the distribution that take effect
# when the parametrized shape/size in the test case is None.
# For every distribution that defaults to non-scalar shapes they must be
# specified by the inheriting Test class. example: TestGaussianRandomWalk
default_shape = ()
default_size = ()
def setup_method(self, *args, **kwargs):
super().setup_method(*args, **kwargs)
self.model = pm.Model()
def get_random_variable(self, shape, with_vector_params=False, name=None):
""" Creates a RandomVariable of the parametrized distribution. """
if with_vector_params:
params = {
key: value * np.ones(self.shape, dtype=np.dtype(type(value)))
for key, value in self.params.items()
}
else:
params = self.params
if name is None:
name = self.distribution.__name__
with self.model:
try:
if shape is None:
# in the test case parametrization "None" means "no specified (default)"
return self.distribution(name, transform=None, **params)
else:
ndim_supp = self.distribution.rv_op.ndim_supp
if ndim_supp == 0:
size = shape
else:
size = shape[:-ndim_supp]
return self.distribution(name, size=size, transform=None, **params)
except TypeError:
if np.sum(np.atleast_1d(shape)) == 0:
pytest.skip("Timeseries must have positive shape")
raise
@staticmethod
def sample_random_variable(random_variable, size):
""" Draws samples from a RandomVariable using its .random() method. """
if size is None:
return random_variable.eval()
else:
return change_rv_size(random_variable, size, expand=True).eval()
@pytest.mark.parametrize("size", [None, (), 1, (1,), 5, (4, 5)], ids=str)
@pytest.mark.parametrize("shape", [None, ()], ids=str)
def test_scalar_distribution_shape(self, shape, size):
""" Draws samples of different [size] from a scalar [shape] RV. """
rv = self.get_random_variable(shape)
exp_shape = self.default_shape if shape is None else tuple(np.atleast_1d(shape))
exp_size = self.default_size if size is None else tuple(np.atleast_1d(size))
expected = exp_size + exp_shape
actual = np.shape(self.sample_random_variable(rv, size))
assert (
expected == actual
), f"Sample size {size} from {shape}-shaped RV had shape {actual}. Expected: {expected}"
# check that negative size raises an error
with pytest.raises(ValueError):
self.sample_random_variable(rv, size=-2)
with pytest.raises(ValueError):
self.sample_random_variable(rv, size=(3, -2))
@pytest.mark.parametrize("size", [None, ()], ids=str)
@pytest.mark.parametrize(
"shape", [None, (), (1,), (1, 1), (1, 2), (10, 11, 1), (9, 10, 2)], ids=str
)
def test_scalar_sample_shape(self, shape, size):
""" Draws samples of scalar [size] from a [shape] RV. """
rv = self.get_random_variable(shape)
exp_shape = self.default_shape if shape is None else tuple(np.atleast_1d(shape))
exp_size = self.default_size if size is None else tuple(np.atleast_1d(size))
expected = exp_size + exp_shape
actual = np.shape(self.sample_random_variable(rv, size))
assert (
expected == actual
), f"Sample size {size} from {shape}-shaped RV had shape {actual}. Expected: {expected}"
@pytest.mark.parametrize("size", [None, 3, (4, 5)], ids=str)
@pytest.mark.parametrize("shape", [None, 1, (10, 11, 1)], ids=str)
def test_vector_params(self, shape, size):
shape = self.shape
rv = self.get_random_variable(shape, with_vector_params=True)
exp_shape = self.default_shape if shape is None else tuple(np.atleast_1d(shape))
exp_size = self.default_size if size is None else tuple(np.atleast_1d(size))
expected = exp_size + exp_shape
actual = np.shape(self.sample_random_variable(rv, size))
assert (
expected == actual
), f"Sample size {size} from {shape}-shaped RV had shape {actual}. Expected: {expected}"
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestGaussianRandomWalk(BaseTestCases.BaseTestCase):
distribution = pm.GaussianRandomWalk
params = {"mu": 1.0, "sigma": 1.0}
default_shape = (1,)
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestNormal(BaseTestCases.BaseTestCase):
distribution = pm.Normal
params = {"mu": 0.0, "tau": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestTruncatedNormal(BaseTestCases.BaseTestCase):
distribution = pm.TruncatedNormal
params = {"mu": 0.0, "tau": 1.0, "lower": -0.5, "upper": 0.5}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestTruncatedNormalLower(BaseTestCases.BaseTestCase):
distribution = pm.TruncatedNormal
params = {"mu": 0.0, "tau": 1.0, "lower": -0.5}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestTruncatedNormalUpper(BaseTestCases.BaseTestCase):
distribution = pm.TruncatedNormal
params = {"mu": 0.0, "tau": 1.0, "upper": 0.5}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestSkewNormal(BaseTestCases.BaseTestCase):
distribution = pm.SkewNormal
params = {"mu": 0.0, "sigma": 1.0, "alpha": 5.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestHalfNormal(BaseTestCases.BaseTestCase):
distribution = pm.HalfNormal
params = {"tau": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestUniform(BaseTestCases.BaseTestCase):
distribution = pm.Uniform
params = {"lower": 0.0, "upper": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestTriangular(BaseTestCases.BaseTestCase):
distribution = pm.Triangular
params = {"c": 0.5, "lower": 0.0, "upper": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestWald(BaseTestCases.BaseTestCase):
distribution = pm.Wald
params = {"mu": 1.0, "lam": 1.0, "alpha": 0.0}
class TestBeta(BaseTestCases.BaseTestCase):
distribution = pm.Beta
params = {"alpha": 1.0, "beta": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestKumaraswamy(BaseTestCases.BaseTestCase):
distribution = pm.Kumaraswamy
params = {"a": 1.0, "b": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestExponential(BaseTestCases.BaseTestCase):
distribution = pm.Exponential
params = {"lam": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestLaplace(BaseTestCases.BaseTestCase):
distribution = pm.Laplace
params = {"mu": 1.0, "b": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestAsymmetricLaplace(BaseTestCases.BaseTestCase):
distribution = pm.AsymmetricLaplace
params = {"kappa": 1.0, "b": 1.0, "mu": 0.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestLognormal(BaseTestCases.BaseTestCase):
distribution = pm.Lognormal
params = {"mu": 1.0, "tau": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestStudentT(BaseTestCases.BaseTestCase):
distribution = pm.StudentT
params = {"nu": 5.0, "mu": 0.0, "lam": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestPareto(BaseTestCases.BaseTestCase):
distribution = pm.Pareto
params = {"alpha": 0.5, "m": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestCauchy(BaseTestCases.BaseTestCase):
distribution = pm.Cauchy
params = {"alpha": 1.0, "beta": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestHalfCauchy(BaseTestCases.BaseTestCase):
distribution = pm.HalfCauchy
params = {"beta": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestGamma(BaseTestCases.BaseTestCase):
distribution = pm.Gamma
params = {"alpha": 1.0, "beta": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestInverseGamma(BaseTestCases.BaseTestCase):
distribution = pm.InverseGamma
params = {"alpha": 0.5, "beta": 0.5}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestChiSquared(BaseTestCases.BaseTestCase):
distribution = pm.ChiSquared
params = {"nu": 2.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestWeibull(BaseTestCases.BaseTestCase):
distribution = pm.Weibull
params = {"alpha": 1.0, "beta": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestExGaussian(BaseTestCases.BaseTestCase):
distribution = pm.ExGaussian
params = {"mu": 0.0, "sigma": 1.0, "nu": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestVonMises(BaseTestCases.BaseTestCase):
distribution = pm.VonMises
params = {"mu": 0.0, "kappa": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestGumbel(BaseTestCases.BaseTestCase):
distribution = pm.Gumbel
params = {"mu": 0.0, "beta": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestLogistic(BaseTestCases.BaseTestCase):
distribution = pm.Logistic
params = {"mu": 0.0, "s": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestLogitNormal(BaseTestCases.BaseTestCase):
distribution = pm.LogitNormal
params = {"mu": 0.0, "sigma": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestBinomial(BaseTestCases.BaseTestCase):
distribution = pm.Binomial
params = {"n": 5, "p": 0.5}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestBetaBinomial(BaseTestCases.BaseTestCase):
distribution = pm.BetaBinomial
params = {"n": 5, "alpha": 1.0, "beta": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestBernoulli(BaseTestCases.BaseTestCase):
distribution = pm.Bernoulli
params = {"p": 0.5}
class TestDiscreteWeibull(BaseTestCases.BaseTestCase):
distribution = pm.DiscreteWeibull
params = {"q": 0.25, "beta": 2.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestPoisson(BaseTestCases.BaseTestCase):
distribution = pm.Poisson
params = {"mu": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestNegativeBinomial(BaseTestCases.BaseTestCase):
distribution = pm.NegativeBinomial
params = {"mu": 1.0, "alpha": 1.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestConstant(BaseTestCases.BaseTestCase):
distribution = pm.Constant
params = {"c": 3}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestZeroInflatedPoisson(BaseTestCases.BaseTestCase):
distribution = pm.ZeroInflatedPoisson
params = {"theta": 1.0, "psi": 0.3}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestZeroInflatedNegativeBinomial(BaseTestCases.BaseTestCase):
distribution = pm.ZeroInflatedNegativeBinomial
params = {"mu": 1.0, "alpha": 1.0, "psi": 0.3}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestZeroInflatedBinomial(BaseTestCases.BaseTestCase):
distribution = pm.ZeroInflatedBinomial
params = {"n": 10, "p": 0.6, "psi": 0.3}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestDiscreteUniform(BaseTestCases.BaseTestCase):
distribution = pm.DiscreteUniform
params = {"lower": 0.0, "upper": 10.0}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestGeometric(BaseTestCases.BaseTestCase):
distribution = pm.Geometric
params = {"p": 0.5}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestHyperGeometric(BaseTestCases.BaseTestCase):
distribution = pm.HyperGeometric
params = {"N": 50, "k": 25, "n": 10}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
class TestMoyal(BaseTestCases.BaseTestCase):
distribution = pm.Moyal
params = {"mu": 0.0, "sigma": 1.0}
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestCategorical(BaseTestCases.BaseTestCase):
distribution = pm.Categorical
params = {"p": np.ones(BaseTestCases.BaseTestCase.shape)}
def get_random_variable(
self, shape, with_vector_params=False, **kwargs
): # don't transform categories
return super().get_random_variable(shape, with_vector_params=False, **kwargs)
def test_probability_vector_shape(self):
"""Check that if a 2d array of probabilities are passed to categorical correct shape is returned"""
p = np.ones((10, 5))
assert pm.Categorical.dist(p=p).random().shape == (10,)
assert pm.Categorical.dist(p=p).random(size=4).shape == (4, 10)
p = np.ones((3, 7, 5))
assert pm.Categorical.dist(p=p).random().shape == (3, 7)
assert pm.Categorical.dist(p=p).random(size=4).shape == (4, 3, 7)
@pytest.mark.skip(reason="This test is covered by Aesara")
class TestDirichlet(SeededTest):
@pytest.mark.parametrize(
"shape, size",
[
((2), (1)),
((2), (2)),
((2, 2), (2, 100)),
((3, 4), (3, 4)),
((3, 4), (3, 4, 100)),
((3, 4), (100)),
((3, 4), (1)),
],
)
def test_dirichlet_random_shape(self, shape, size):
out_shape = to_tuple(size) + to_tuple(shape)
assert pm.Dirichlet.dist(a=np.ones(shape)).random(size=size).shape == out_shape
class TestScalarParameterSamples(SeededTest):
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_bounded(self):
# A bit crude...
BoundedNormal = pm.Bound(pm.Normal, upper=0)
def ref_rand(size, tau):
return -st.halfnorm.rvs(size=size, loc=0, scale=tau ** -0.5)
pymc3_random(BoundedNormal, {"tau": Rplus}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_uniform(self):
def ref_rand(size, lower, upper):
return st.uniform.rvs(size=size, loc=lower, scale=upper - lower)
pymc3_random(pm.Uniform, {"lower": -Rplus, "upper": Rplus}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_normal(self):
def ref_rand(size, mu, sigma):
return st.norm.rvs(size=size, loc=mu, scale=sigma)
pymc3_random(pm.Normal, {"mu": R, "sigma": Rplus}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_truncated_normal(self):
def ref_rand(size, mu, sigma, lower, upper):
return st.truncnorm.rvs(
(lower - mu) / sigma, (upper - mu) / sigma, size=size, loc=mu, scale=sigma
)
pymc3_random(
pm.TruncatedNormal,
{"mu": R, "sigma": Rplusbig, "lower": -Rplusbig, "upper": Rplusbig},
ref_rand=ref_rand,
)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_truncated_normal_lower(self):
def ref_rand(size, mu, sigma, lower):
return st.truncnorm.rvs((lower - mu) / sigma, np.inf, size=size, loc=mu, scale=sigma)
pymc3_random(
pm.TruncatedNormal, {"mu": R, "sigma": Rplusbig, "lower": -Rplusbig}, ref_rand=ref_rand
)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_truncated_normal_upper(self):
def ref_rand(size, mu, sigma, upper):
return st.truncnorm.rvs(-np.inf, (upper - mu) / sigma, size=size, loc=mu, scale=sigma)
pymc3_random(
pm.TruncatedNormal, {"mu": R, "sigma": Rplusbig, "upper": Rplusbig}, ref_rand=ref_rand
)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_skew_normal(self):
def ref_rand(size, alpha, mu, sigma):
return st.skewnorm.rvs(size=size, a=alpha, loc=mu, scale=sigma)
pymc3_random(pm.SkewNormal, {"mu": R, "sigma": Rplus, "alpha": R}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_half_normal(self):
def ref_rand(size, tau):
return st.halfnorm.rvs(size=size, loc=0, scale=tau ** -0.5)
pymc3_random(pm.HalfNormal, {"tau": Rplus}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_wald(self):
# Cannot do anything too exciting as scipy wald is a
# location-scale model of the *standard* wald with mu=1 and lam=1
def ref_rand(size, mu, lam, alpha):
return st.wald.rvs(size=size, loc=alpha)
pymc3_random(
pm.Wald,
{"mu": Domain([1.0, 1.0, 1.0]), "lam": Domain([1.0, 1.0, 1.0]), "alpha": Rplus},
ref_rand=ref_rand,
)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_beta(self):
def ref_rand(size, alpha, beta):
return clipped_beta_rvs(a=alpha, b=beta, size=size)
pymc3_random(pm.Beta, {"alpha": Rplus, "beta": Rplus}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_exponential(self):
def ref_rand(size, lam):
return nr.exponential(scale=1.0 / lam, size=size)
pymc3_random(pm.Exponential, {"lam": Rplus}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_laplace(self):
def ref_rand(size, mu, b):
return st.laplace.rvs(mu, b, size=size)
pymc3_random(pm.Laplace, {"mu": R, "b": Rplus}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_laplace_asymmetric(self):
def ref_rand(size, kappa, b, mu):
u = np.random.uniform(size=size)
switch = kappa ** 2 / (1 + kappa ** 2)
non_positive_x = mu + kappa * np.log(u * (1 / switch)) / b
positive_x = mu - np.log((1 - u) * (1 + kappa ** 2)) / (kappa * b)
draws = non_positive_x * (u <= switch) + positive_x * (u > switch)
return draws
pymc3_random(pm.AsymmetricLaplace, {"b": Rplus, "kappa": Rplus, "mu": R}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_lognormal(self):
def ref_rand(size, mu, tau):
return np.exp(mu + (tau ** -0.5) * st.norm.rvs(loc=0.0, scale=1.0, size=size))
pymc3_random(pm.Lognormal, {"mu": R, "tau": Rplusbig}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_student_t(self):
def ref_rand(size, nu, mu, lam):
return st.t.rvs(nu, mu, lam ** -0.5, size=size)
pymc3_random(pm.StudentT, {"nu": Rplus, "mu": R, "lam": Rplus}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_cauchy(self):
def ref_rand(size, alpha, beta):
return st.cauchy.rvs(alpha, beta, size=size)
pymc3_random(pm.Cauchy, {"alpha": R, "beta": Rplusbig}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_half_cauchy(self):
def ref_rand(size, beta):
return st.halfcauchy.rvs(scale=beta, size=size)
pymc3_random(pm.HalfCauchy, {"beta": Rplusbig}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_gamma_alpha_beta(self):
def ref_rand(size, alpha, beta):
return st.gamma.rvs(alpha, scale=1.0 / beta, size=size)
pymc3_random(pm.Gamma, {"alpha": Rplusbig, "beta": Rplusbig}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_gamma_mu_sigma(self):
def ref_rand(size, mu, sigma):
return st.gamma.rvs(mu ** 2 / sigma ** 2, scale=sigma ** 2 / mu, size=size)
pymc3_random(pm.Gamma, {"mu": Rplusbig, "sigma": Rplusbig}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_inverse_gamma(self):
def ref_rand(size, alpha, beta):
return st.invgamma.rvs(a=alpha, scale=beta, size=size)
pymc3_random(pm.InverseGamma, {"alpha": Rplus, "beta": Rplus}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_pareto(self):
def ref_rand(size, alpha, m):
return st.pareto.rvs(alpha, scale=m, size=size)
pymc3_random(pm.Pareto, {"alpha": Rplusbig, "m": Rplusbig}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_ex_gaussian(self):
def ref_rand(size, mu, sigma, nu):
return nr.normal(mu, sigma, size=size) + nr.exponential(scale=nu, size=size)
pymc3_random(pm.ExGaussian, {"mu": R, "sigma": Rplus, "nu": Rplus}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_vonmises(self):
def ref_rand(size, mu, kappa):
return st.vonmises.rvs(size=size, loc=mu, kappa=kappa)
pymc3_random(pm.VonMises, {"mu": R, "kappa": Rplus}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_triangular(self):
def ref_rand(size, lower, upper, c):
scale = upper - lower
c_ = (c - lower) / scale
return st.triang.rvs(size=size, loc=lower, scale=scale, c=c_)
pymc3_random(
pm.Triangular, {"lower": Runif, "upper": Runif + 3, "c": Runif + 1}, ref_rand=ref_rand
)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_flat(self):
with pm.Model():
f = pm.Flat("f")
with pytest.raises(ValueError):
f.random(1)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_half_flat(self):
with pm.Model():
f = pm.HalfFlat("f")
with pytest.raises(ValueError):
f.random(1)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_binomial(self):
pymc3_random_discrete(pm.Binomial, {"n": Nat, "p": Unit}, ref_rand=st.binom.rvs)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
@pytest.mark.xfail(
sys.platform.startswith("win"),
reason="Known issue: https://github.com/pymc-devs/pymc3/pull/4269",
)
def test_beta_binomial(self):
pymc3_random_discrete(
pm.BetaBinomial, {"n": Nat, "alpha": Rplus, "beta": Rplus}, ref_rand=self._beta_bin
)
def _beta_bin(self, n, alpha, beta, size=None):
return st.binom.rvs(n, st.beta.rvs(a=alpha, b=beta, size=size))
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_bernoulli(self):
pymc3_random_discrete(
pm.Bernoulli, {"p": Unit}, ref_rand=lambda size, p=None: st.bernoulli.rvs(p, size=size)
)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_poisson(self):
pymc3_random_discrete(pm.Poisson, {"mu": Rplusbig}, size=500, ref_rand=st.poisson.rvs)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_negative_binomial(self):
def ref_rand(size, alpha, mu):
return st.nbinom.rvs(alpha, alpha / (mu + alpha), size=size)
pymc3_random_discrete(
pm.NegativeBinomial,
{"mu": Rplusbig, "alpha": Rplusbig},
size=100,
fails=50,
ref_rand=ref_rand,
)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_geometric(self):
pymc3_random_discrete(pm.Geometric, {"p": Unit}, size=500, fails=50, ref_rand=nr.geometric)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_hypergeometric(self):
def ref_rand(size, N, k, n):
return st.hypergeom.rvs(M=N, n=k, N=n, size=size)
pymc3_random_discrete(
pm.HyperGeometric,
{
"N": Domain([10, 11, 12, 13], "int64"),
"k": Domain([4, 5, 6, 7], "int64"),
"n": Domain([6, 7, 8, 9], "int64"),
},
size=500,
fails=50,
ref_rand=ref_rand,
)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_discrete_uniform(self):
def ref_rand(size, lower, upper):
return st.randint.rvs(lower, upper + 1, size=size)
pymc3_random_discrete(
pm.DiscreteUniform, {"lower": -NatSmall, "upper": NatSmall}, ref_rand=ref_rand
)
def test_discrete_weibull(self):
def ref_rand(size, q, beta):
u = np.random.uniform(size=size)
return np.ceil(np.power(np.log(1 - u) / np.log(q), 1.0 / beta)) - 1
pymc3_random_discrete(
pm.DiscreteWeibull, {"q": Unit, "beta": Rplusdunif}, ref_rand=ref_rand
)
@pytest.mark.skip(reason="This test is covered by Aesara")
@pytest.mark.parametrize("s", [2, 3, 4])
def test_categorical_random(self, s):
def ref_rand(size, p):
return nr.choice(np.arange(p.shape[0]), p=p, size=size)
pymc3_random_discrete(pm.Categorical, {"p": Simplex(s)}, ref_rand=ref_rand)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_constant_dist(self):
def ref_rand(size, c):
return c * np.ones(size, dtype=int)
pymc3_random_discrete(pm.Constant, {"c": I}, ref_rand=ref_rand)
@pytest.mark.skip(reason="This test is covered by Aesara")
def test_mv_normal(self):
def ref_rand(size, mu, cov):
return st.multivariate_normal.rvs(mean=mu, cov=cov, size=size)
def ref_rand_tau(size, mu, tau):
return ref_rand(size, mu, linalg.inv(tau))
def ref_rand_chol(size, mu, chol):
return ref_rand(size, mu, np.dot(chol, chol.T))
def ref_rand_uchol(size, mu, chol):
return ref_rand(size, mu, np.dot(chol.T, chol))
for n in [2, 3]:
pymc3_random(
pm.MvNormal,
{"mu": Vector(R, n), "cov": PdMatrix(n)},
size=100,
valuedomain=Vector(R, n),
ref_rand=ref_rand,
)
pymc3_random(
pm.MvNormal,
{"mu": Vector(R, n), "tau": PdMatrix(n)},
size=100,
valuedomain=Vector(R, n),
ref_rand=ref_rand_tau,
)
pymc3_random(
pm.MvNormal,
{"mu": Vector(R, n), "chol": PdMatrixChol(n)},
size=100,
valuedomain=Vector(R, n),
ref_rand=ref_rand_chol,
)
pymc3_random(
pm.MvNormal,
{"mu": Vector(R, n), "chol": PdMatrixCholUpper(n)},
size=100,
valuedomain=Vector(R, n),
ref_rand=ref_rand_uchol,
extra_args={"lower": False},
)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_matrix_normal(self):
def ref_rand(size, mu, rowcov, colcov):
return st.matrix_normal.rvs(mean=mu, rowcov=rowcov, colcov=colcov, size=size)
# def ref_rand_tau(size, mu, tau):
# return ref_rand(size, mu, linalg.inv(tau))
def ref_rand_chol(size, mu, rowchol, colchol):
return ref_rand(
size, mu, rowcov=np.dot(rowchol, rowchol.T), colcov=np.dot(colchol, colchol.T)
)
def ref_rand_chol_transpose(size, mu, rowchol, colchol):
colchol = colchol.T
return ref_rand(
size, mu, rowcov=np.dot(rowchol, rowchol.T), colcov=np.dot(colchol, colchol.T)
)
def ref_rand_uchol(size, mu, rowchol, colchol):
return ref_rand(
size, mu, rowcov=np.dot(rowchol.T, rowchol), colcov=np.dot(colchol.T, colchol)
)
for n in [2, 3]:
pymc3_random(
pm.MatrixNormal,
{"mu": RealMatrix(n, n), "rowcov": PdMatrix(n), "colcov": PdMatrix(n)},
size=100,
valuedomain=RealMatrix(n, n),
ref_rand=ref_rand,
)
# pymc3_random(pm.MatrixNormal, {'mu': RealMatrix(n, n), 'tau': PdMatrix(n)},
# size=n, valuedomain=RealMatrix(n, n), ref_rand=ref_rand_tau)
pymc3_random(
pm.MatrixNormal,
{"mu": RealMatrix(n, n), "rowchol": PdMatrixChol(n), "colchol": PdMatrixChol(n)},
size=100,
valuedomain=RealMatrix(n, n),
ref_rand=ref_rand_chol,
)
# pymc3_random(
# pm.MvNormal,
# {'mu': RealMatrix(n, n), 'rowchol': PdMatrixCholUpper(n), 'colchol': PdMatrixCholUpper(n)},
# size=n, valuedomain=RealMatrix(n, n), ref_rand=ref_rand_uchol,
# extra_args={'lower': False}
# )
# 2 sample test fails because cov becomes different if chol is transposed beforehand.
# This implicity means we need transpose of chol after drawing values in
# MatrixNormal.random method to match stats.matrix_normal.rvs method
with pytest.raises(AssertionError):
pymc3_random(
pm.MatrixNormal,
{
"mu": RealMatrix(n, n),
"rowchol": PdMatrixChol(n),
"colchol": PdMatrixChol(n),
},
size=100,
valuedomain=RealMatrix(n, n),
ref_rand=ref_rand_chol_transpose,
)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_kronecker_normal(self):
def ref_rand(size, mu, covs, sigma):
cov = pm.math.kronecker(covs[0], covs[1]).eval()
cov += sigma ** 2 * np.identity(cov.shape[0])
return st.multivariate_normal.rvs(mean=mu, cov=cov, size=size)
def ref_rand_chol(size, mu, chols, sigma):
covs = [np.dot(chol, chol.T) for chol in chols]
return ref_rand(size, mu, covs, sigma)
def ref_rand_evd(size, mu, evds, sigma):
covs = []
for eigs, Q in evds:
covs.append(np.dot(Q, np.dot(np.diag(eigs), Q.T)))
return ref_rand(size, mu, covs, sigma)
sizes = [2, 3]
sigmas = [0, 1]
for n, sigma in zip(sizes, sigmas):
N = n ** 2
covs = [RandomPdMatrix(n), RandomPdMatrix(n)]
chols = list(map(np.linalg.cholesky, covs))
evds = list(map(np.linalg.eigh, covs))
dom = Domain([np.random.randn(N) * 0.1], edges=(None, None), shape=N)
mu = Domain([np.random.randn(N) * 0.1], edges=(None, None), shape=N)
std_args = {"mu": mu}
cov_args = {"covs": covs}
chol_args = {"chols": chols}
evd_args = {"evds": evds}
if sigma is not None and sigma != 0:
std_args["sigma"] = Domain([sigma], edges=(None, None))
else:
for args in [cov_args, chol_args, evd_args]:
args["sigma"] = sigma
pymc3_random(
pm.KroneckerNormal,
std_args,
valuedomain=dom,
ref_rand=ref_rand,
extra_args=cov_args,
model_args=cov_args,
)
pymc3_random(
pm.KroneckerNormal,
std_args,