forked from pymc-devs/pymc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_distributions.py
2832 lines (2454 loc) · 100 KB
/
test_distributions.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
import aesara
import aesara.tensor as at
import numpy as np
import numpy.random as nr
import pytest
import scipy.stats
import scipy.stats.distributions as sp
from aesara.compile.mode import Mode
from aesara.graph.basic import ancestors
from aesara.tensor.random.op import RandomVariable
from aesara.tensor.var import TensorVariable
from numpy import array, inf, log
from numpy.testing import assert_allclose, assert_almost_equal, assert_equal
from packaging.version import parse
from scipy import __version__ as scipy_version
from scipy import integrate
from scipy.special import erf, logit
import pymc3 as pm
from pymc3.aesaraf import change_rv_size, floatX
from pymc3.distributions import (
AR1,
CAR,
AsymmetricLaplace,
Bernoulli,
Beta,
BetaBinomial,
Binomial,
Bound,
Categorical,
Cauchy,
ChiSquared,
Constant,
DensityDist,
Dirichlet,
DirichletMultinomial,
DiscreteUniform,
DiscreteWeibull,
ExGaussian,
Exponential,
Flat,
Gamma,
Geometric,
Gumbel,
HalfCauchy,
HalfFlat,
HalfNormal,
HalfStudentT,
HyperGeometric,
Interpolated,
InverseGamma,
KroneckerNormal,
Kumaraswamy,
Laplace,
LKJCorr,
Logistic,
LogitNormal,
Lognormal,
MatrixNormal,
Moyal,
Multinomial,
MvNormal,
MvStudentT,
NegativeBinomial,
Normal,
OrderedLogistic,
OrderedProbit,
Pareto,
Poisson,
Rice,
SkewNormal,
StudentT,
Triangular,
TruncatedNormal,
Uniform,
VonMises,
Wald,
Weibull,
ZeroInflatedBinomial,
ZeroInflatedNegativeBinomial,
ZeroInflatedPoisson,
continuous,
logcdf,
logpt,
)
from pymc3.math import kronecker, logsumexp
from pymc3.model import Deterministic, Model, Point
from pymc3.tests.helpers import select_by_precision
from pymc3.vartypes import continuous_types
SCIPY_VERSION = parse(scipy_version)
def get_lkj_cases():
"""
Log probabilities calculated using the formulas in:
http://www.sciencedirect.com/science/article/pii/S0047259X09000876
"""
tri = np.array([0.7, 0.0, -0.7])
return [
(tri, 1, 3, 1.5963125911388549),
(tri, 3, 3, -7.7963493376312742),
(tri, 0, 3, -np.inf),
(np.array([1.1, 0.0, -0.7]), 1, 3, -np.inf),
(np.array([0.7, 0.0, -1.1]), 1, 3, -np.inf),
]
LKJ_CASES = get_lkj_cases()
class Domain:
def __init__(self, vals, dtype=None, edges=None, shape=None):
avals = array(vals, dtype=dtype)
if dtype is None and not str(avals.dtype).startswith("int"):
avals = avals.astype(aesara.config.floatX)
vals = [array(v, dtype=avals.dtype) for v in vals]
if edges is None:
edges = array(vals[0]), array(vals[-1])
vals = vals[1:-1]
if shape is None:
shape = avals[0].shape
self.vals = vals
self.shape = shape
self.lower, self.upper = edges
self.dtype = avals.dtype
def __add__(self, other):
return Domain(
[v + other for v in self.vals],
self.dtype,
(self.lower + other, self.upper + other),
self.shape,
)
def __mul__(self, other):
try:
return Domain(
[v * other for v in self.vals],
self.dtype,
(self.lower * other, self.upper * other),
self.shape,
)
except TypeError:
return Domain(
[v * other for v in self.vals],
self.dtype,
(self.lower, self.upper),
self.shape,
)
def __neg__(self):
return Domain([-v for v in self.vals], self.dtype, (-self.lower, -self.upper), self.shape)
def product(domains, n_samples=-1):
"""Get an iterator over a product of domains.
Args:
domains: a dictionary of (name, object) pairs, where the objects
must be "domain-like", as in, have a `.vals` property
n_samples: int, maximum samples to return. -1 to return whole product
Returns:
list of the cartesian product of the domains
"""
try:
names, domains = zip(*domains.items())
except ValueError: # domains.items() is empty
return [{}]
all_vals = [zip(names, val) for val in itertools.product(*[d.vals for d in domains])]
if n_samples > 0 and len(all_vals) > n_samples:
return (all_vals[j] for j in nr.choice(len(all_vals), n_samples, replace=False))
return all_vals
R = Domain([-inf, -2.1, -1, -0.01, 0.0, 0.01, 1, 2.1, inf])
Rplus = Domain([0, 0.01, 0.1, 0.9, 0.99, 1, 1.5, 2, 100, inf])
Rplusbig = Domain([0, 0.5, 0.9, 0.99, 1, 1.5, 2, 20, inf])
Rminusbig = Domain([-inf, -2, -1.5, -1, -0.99, -0.9, -0.5, -0.01, 0])
Unit = Domain([0, 0.001, 0.1, 0.5, 0.75, 0.99, 1])
Circ = Domain([-np.pi, -2.1, -1, -0.01, 0.0, 0.01, 1, 2.1, np.pi])
Runif = Domain([-1, -0.4, 0, 0.4, 1])
Rdunif = Domain([-10, 0, 10.0])
Rplusunif = Domain([0, 0.5, inf])
Rplusdunif = Domain([2, 10, 100], "int64")
I = Domain([-1000, -3, -2, -1, 0, 1, 2, 3, 1000], "int64")
NatSmall = Domain([0, 3, 4, 5, 1000], "int64")
Nat = Domain([0, 1, 2, 3, 2000], "int64")
NatBig = Domain([0, 1, 2, 3, 5000, 50000], "int64")
PosNat = Domain([1, 2, 3, 2000], "int64")
Bool = Domain([0, 0, 1, 1], "int64")
def build_model(distfam, valuedomain, vardomains, extra_args=None):
if extra_args is None:
extra_args = {}
with Model() as m:
param_vars = {}
for v, dom in vardomains.items():
v_at = aesara.shared(np.asarray(dom.vals[0]))
v_at.name = v
param_vars[v] = v_at
param_vars.update(extra_args)
distfam(
"value",
**param_vars,
transform=None,
)
return m, param_vars
def laplace_asymmetric_logpdf(value, kappa, b, mu):
kapinv = 1 / kappa
value = value - mu
lPx = value * b * np.where(value >= 0, -kappa, kapinv)
lPx += np.log(b / (kappa + kapinv))
return lPx
def integrate_nd(f, domain, shape, dtype):
if shape == () or shape == (1,):
if dtype in continuous_types:
return integrate.quad(f, domain.lower, domain.upper, epsabs=1e-8)[0]
else:
return sum(f(j) for j in range(domain.lower, domain.upper + 1))
elif shape == (2,):
def f2(a, b):
return f([a, b])
return integrate.dblquad(
f2,
domain.lower[0],
domain.upper[0],
lambda _: domain.lower[1],
lambda _: domain.upper[1],
)[0]
elif shape == (3,):
def f3(a, b, c):
return f([a, b, c])
return integrate.tplquad(
f3,
domain.lower[0],
domain.upper[0],
lambda _: domain.lower[1],
lambda _: domain.upper[1],
lambda _, __: domain.lower[2],
lambda _, __: domain.upper[2],
)[0]
else:
raise ValueError("Dont know how to integrate shape: " + str(shape))
def multinomial_logpdf(value, n, p):
if value.sum() == n and (0 <= value).all() and (value <= n).all():
logpdf = scipy.special.gammaln(n + 1)
logpdf -= scipy.special.gammaln(value + 1).sum()
logpdf += logpow(p, value).sum()
return logpdf
else:
return -inf
def dirichlet_multinomial_logpmf(value, n, a):
value, n, a = [np.asarray(x) for x in [value, n, a]]
assert value.ndim == 1
assert n.ndim == 0
assert a.shape == value.shape
gammaln = scipy.special.gammaln
if value.sum() == n and (0 <= value).all() and (value <= n).all():
sum_a = a.sum(axis=-1)
const = gammaln(n + 1) + gammaln(sum_a) - gammaln(n + sum_a)
series = gammaln(value + a) - gammaln(value + 1) - gammaln(a)
return const + series.sum(axis=-1)
else:
return -inf
def beta_mu_sigma(value, mu, sigma):
kappa = mu * (1 - mu) / sigma ** 2 - 1
if kappa > 0:
return sp.beta.logpdf(value, mu * kappa, (1 - mu) * kappa)
else:
return -inf
class ProductDomain:
def __init__(self, domains):
self.vals = list(itertools.product(*[d.vals for d in domains]))
self.shape = (len(domains),) + domains[0].shape
self.lower = [d.lower for d in domains]
self.upper = [d.upper for d in domains]
self.dtype = domains[0].dtype
def Vector(D, n):
return ProductDomain([D] * n)
def SortedVector(n):
vals = []
np.random.seed(42)
for _ in range(10):
vals.append(np.sort(np.random.randn(n)))
return Domain(vals, edges=(None, None))
def UnitSortedVector(n):
vals = []
np.random.seed(42)
for _ in range(10):
vals.append(np.sort(np.random.rand(n)))
return Domain(vals, edges=(None, None))
def RealMatrix(n, m):
vals = []
np.random.seed(42)
for _ in range(10):
vals.append(np.random.randn(n, m))
return Domain(vals, edges=(None, None))
def simplex_values(n):
if n == 1:
yield array([1.0])
else:
for v in Unit.vals:
for vals in simplex_values(n - 1):
yield np.concatenate([[v], (1 - v) * vals])
def normal_logpdf_tau(value, mu, tau):
return normal_logpdf_cov(value, mu, np.linalg.inv(tau)).sum()
def normal_logpdf_cov(value, mu, cov):
return scipy.stats.multivariate_normal.logpdf(value, mu, cov).sum()
def normal_logpdf_chol(value, mu, chol):
return normal_logpdf_cov(value, mu, np.dot(chol, chol.T)).sum()
def normal_logpdf_chol_upper(value, mu, chol):
return normal_logpdf_cov(value, mu, np.dot(chol.T, chol)).sum()
def matrix_normal_logpdf_cov(value, mu, rowcov, colcov):
return scipy.stats.matrix_normal.logpdf(value, mu, rowcov, colcov)
def matrix_normal_logpdf_chol(value, mu, rowchol, colchol):
return matrix_normal_logpdf_cov(
value, mu, np.dot(rowchol, rowchol.T), np.dot(colchol, colchol.T)
)
def kron_normal_logpdf_cov(value, mu, covs, sigma):
cov = kronecker(*covs).eval()
if sigma is not None:
cov += sigma ** 2 * np.eye(*cov.shape)
return scipy.stats.multivariate_normal.logpdf(value, mu, cov).sum()
def kron_normal_logpdf_chol(value, mu, chols, sigma):
covs = [np.dot(chol, chol.T) for chol in chols]
return kron_normal_logpdf_cov(value, mu, covs, sigma=sigma)
def kron_normal_logpdf_evd(value, mu, evds, sigma):
covs = []
for eigs, Q in evds:
try:
eigs = eigs.eval()
except AttributeError:
pass
try:
Q = Q.eval()
except AttributeError:
pass
covs.append(np.dot(Q, np.dot(np.diag(eigs), Q.T)))
return kron_normal_logpdf_cov(value, mu, covs, sigma)
def betafn(a):
return floatX(scipy.special.gammaln(a).sum(-1) - scipy.special.gammaln(a.sum(-1)))
def logpow(v, p):
return np.choose(v == 0, [p * np.log(v), 0])
def discrete_weibull_logpmf(value, q, beta):
return floatX(
np.log(np.power(q, np.power(value, beta)) - np.power(q, np.power(value + 1, beta)))
)
def dirichlet_logpdf(value, a):
return floatX((-betafn(a) + logpow(value, a - 1).sum(-1)).sum())
def categorical_logpdf(value, p):
if value >= 0 and value <= len(p):
return floatX(np.log(np.moveaxis(p, -1, 0)[value]))
else:
return -inf
def mvt_logpdf(value, nu, Sigma, mu=0):
d = len(Sigma)
dist = np.atleast_2d(value) - mu
chol = np.linalg.cholesky(Sigma)
trafo = np.linalg.solve(chol, dist.T).T
logdet = np.log(np.diag(chol)).sum()
lgamma = scipy.special.gammaln
norm = lgamma((nu + d) / 2.0) - 0.5 * d * np.log(nu * np.pi) - lgamma(nu / 2.0)
logp = norm - logdet - (nu + d) / 2.0 * np.log1p((trafo * trafo).sum(-1) / nu)
return logp.sum()
def AR1_logpdf(value, k, tau_e):
tau = tau_e * (1 - k ** 2)
return (
sp.norm(loc=0, scale=1 / np.sqrt(tau)).logpdf(value[0])
+ sp.norm(loc=k * value[:-1], scale=1 / np.sqrt(tau_e)).logpdf(value[1:]).sum()
)
def invlogit(x, eps=sys.float_info.epsilon):
return (1.0 - 2.0 * eps) / (1.0 + np.exp(-x)) + eps
def orderedlogistic_logpdf(value, eta, cutpoints):
c = np.concatenate(([-np.inf], cutpoints, [np.inf]))
ps = np.array([invlogit(eta - cc) - invlogit(eta - cc1) for cc, cc1 in zip(c[:-1], c[1:])])
p = ps[value]
return np.where(np.all(ps >= 0), np.log(p), -np.inf)
def invprobit(x):
return (erf(x / np.sqrt(2)) + 1) / 2
def orderedprobit_logpdf(value, eta, cutpoints):
c = np.concatenate(([-np.inf], cutpoints, [np.inf]))
ps = np.array([invprobit(eta - cc) - invprobit(eta - cc1) for cc, cc1 in zip(c[:-1], c[1:])])
p = ps[value]
return np.where(np.all(ps >= 0), np.log(p), -np.inf)
class Simplex:
def __init__(self, n):
self.vals = list(simplex_values(n))
self.shape = (n,)
self.dtype = Unit.dtype
class MultiSimplex:
def __init__(self, n_dependent, n_independent):
self.vals = []
for simplex_value in itertools.product(simplex_values(n_dependent), repeat=n_independent):
self.vals.append(np.vstack(simplex_value))
self.shape = (n_independent, n_dependent)
self.dtype = Unit.dtype
def PdMatrix(n):
if n == 1:
return PdMatrix1
elif n == 2:
return PdMatrix2
elif n == 3:
return PdMatrix3
else:
raise ValueError("n out of bounds")
PdMatrix1 = Domain([np.eye(1), [[0.5]]], edges=(None, None))
PdMatrix2 = Domain([np.eye(2), [[0.5, 0.05], [0.05, 4.5]]], edges=(None, None))
PdMatrix3 = Domain([np.eye(3), [[0.5, 0.1, 0], [0.1, 1, 0], [0, 0, 2.5]]], edges=(None, None))
PdMatrixChol1 = Domain([np.eye(1), [[0.001]]], edges=(None, None))
PdMatrixChol2 = Domain([np.eye(2), [[0.1, 0], [10, 1]]], edges=(None, None))
PdMatrixChol3 = Domain([np.eye(3), [[0.1, 0, 0], [10, 100, 0], [0, 1, 10]]], edges=(None, None))
def PdMatrixChol(n):
if n == 1:
return PdMatrixChol1
elif n == 2:
return PdMatrixChol2
elif n == 3:
return PdMatrixChol3
else:
raise ValueError("n out of bounds")
PdMatrixCholUpper1 = Domain([np.eye(1), [[0.001]]], edges=(None, None))
PdMatrixCholUpper2 = Domain([np.eye(2), [[0.1, 10], [0, 1]]], edges=(None, None))
PdMatrixCholUpper3 = Domain(
[np.eye(3), [[0.1, 10, 0], [0, 100, 1], [0, 0, 10]]], edges=(None, None)
)
def PdMatrixCholUpper(n):
if n == 1:
return PdMatrixCholUpper1
elif n == 2:
return PdMatrixCholUpper2
elif n == 3:
return PdMatrixCholUpper3
else:
raise ValueError("n out of bounds")
def RandomPdMatrix(n):
A = np.random.rand(n, n)
return np.dot(A, A.T) + n * np.identity(n)
def test_hierarchical_logpt():
"""Make sure there are no random variables in a model's log-likelihood graph."""
with pm.Model() as m:
x = pm.Uniform("x", lower=0, upper=1)
y = pm.Uniform("y", lower=0, upper=x)
logpt_ancestors = list(ancestors([m.logpt]))
ops = {a.owner.op for a in logpt_ancestors if a.owner}
assert len(ops) > 0
assert not any(isinstance(o, RandomVariable) for o in ops)
assert x.tag.value_var in logpt_ancestors
assert y.tag.value_var in logpt_ancestors
def test_hierarchical_obs_logpt():
obs = np.array([0.5, 0.4, 5, 2])
with pm.Model() as model:
x = pm.Uniform("x", 0, 1, observed=obs)
pm.Uniform("y", x, 2, observed=obs)
logpt_ancestors = list(ancestors([model.logpt]))
ops = {a.owner.op for a in logpt_ancestors if a.owner}
assert len(ops) > 0
assert not any(isinstance(o, RandomVariable) for o in ops)
class TestMatchesScipy:
def check_logp(
self,
pymc3_dist,
domain,
paramdomains,
scipy_logp,
decimal=None,
n_samples=100,
extra_args=None,
scipy_args=None,
):
"""
Generic test for PyMC3 logp methods
Test PyMC3 logp and equivalent scipy logpmf/logpdf methods give similar
results for valid values and parameters inside the supported edges.
Edges are excluded by default, but can be artificially included by
creating a domain with repeated values (e.g., `Domain([0, 0, .5, 1, 1]`)
Parameters
----------
pymc3_dist: PyMC3 distribution
domain : Domain
Supported domain of distribution values
paramdomains : Dictionary of Parameter : Domain pairs
Supported domains of distribution parameters
scipy_logp : Scipy logpmf/logpdf method
Scipy logp method of equivalent pymc3_dist distribution
decimal : Int
Level of precision with which pymc3_dist and scipy logp are compared.
Defaults to 6 for float64 and 3 for float32
n_samples : Int
Upper limit on the number of valid domain and value combinations that
are compared between pymc3 and scipy methods. If n_samples is below the
total number of combinations, a random subset is evaluated. Setting
n_samples = -1, will return all possible combinations. Defaults to 100
extra_args : Dictionary with extra arguments needed to build pymc3 model
Dictionary is passed to helper function `build_model` from which
the pymc3 distribution logp is calculated
scipy_args : Dictionary with extra arguments needed to call scipy logp method
Usually the same as extra_args
"""
if decimal is None:
decimal = select_by_precision(float64=6, float32=3)
if extra_args is None:
extra_args = {}
if scipy_args is None:
scipy_args = {}
def logp_reference(args):
args.update(scipy_args)
return scipy_logp(**args)
model, param_vars = build_model(pymc3_dist, domain, paramdomains, extra_args)
logp = model.fastlogp_nojac
domains = paramdomains.copy()
domains["value"] = domain
for pt in product(domains, n_samples=n_samples):
pt = dict(pt)
pt_d = self._model_input_dict(model, param_vars, pt)
pt_logp = Point(pt_d, model=model)
pt_ref = Point(pt, filter_model_vars=False, model=model)
assert_almost_equal(
logp(pt_logp),
logp_reference(pt_ref),
decimal=decimal,
err_msg=str(pt),
)
def _model_input_dict(self, model, param_vars, pt):
"""Create a dict with only the necessary, transformed logp inputs."""
pt_d = {}
for k, v in pt.items():
rv_var = model.named_vars.get(k)
nv = param_vars.get(k, rv_var)
nv = getattr(nv.tag, "value_var", nv)
transform = getattr(nv.tag, "transform", None)
if transform:
# todo: the compiled graph behind this should be cached and
# reused (if it isn't already).
v = transform.forward(rv_var, v).eval()
if nv.name in param_vars:
# update the shared parameter variables in `param_vars`
param_vars[nv.name].set_value(v)
else:
# create an argument entry for the (potentially
# transformed) "value" variable
pt_d[nv.name] = v
return pt_d
def check_logcdf(
self,
pymc3_dist,
domain,
paramdomains,
scipy_logcdf,
decimal=None,
n_samples=100,
skip_paramdomain_inside_edge_test=False,
skip_paramdomain_outside_edge_test=False,
):
"""
Generic test for PyMC3 logcdf methods
The following tests are performed by default:
1. Test PyMC3 logcdf and equivalent scipy logcdf methods give similar
results for valid values and parameters inside the supported edges.
Edges are excluded by default, but can be artificially included by
creating a domain with repeated values (e.g., `Domain([0, 0, .5, 1, 1]`)
Can be skipped via skip_paramdomain_inside_edge_test
2. Test PyMC3 logcdf method returns -inf for invalid parameter values
outside the supported edges. Can be skipped via skip_paramdomain_outside_edge_test
3. Test PyMC3 logcdf method returns -inf and 0 for values below and
above the supported edge, respectively, when using valid parameters.
4. Test PyMC3 logcdf methods works with multiple value or returns
default informative TypeError
Parameters
----------
pymc3_dist: PyMC3 distribution
domain : Domain
Supported domain of distribution values
paramdomains : Dictionary of Parameter : Domain pairs
Supported domains of distribution parameters
scipy_logcdf : Scipy logcdf method
Scipy logcdf method of equivalent pymc3_dist distribution
decimal : Int
Level of precision with which pymc3_dist and scipy_logcdf are compared.
Defaults to 6 for float64 and 3 for float32
n_samples : Int
Upper limit on the number of valid domain and value combinations that
are compared between pymc3 and scipy methods. If n_samples is below the
total number of combinations, a random subset is evaluated. Setting
n_samples = -1, will return all possible combinations. Defaults to 100
skip_paramdomain_inside_edge_test : Bool
Whether to run test 1., which checks that pymc3 and scipy distributions
match for valid values and parameters inside the respective domain edges
skip_paramdomain_outside_edge_test : Bool
Whether to run test 2., which checks that pymc3 distribution logcdf
returns -inf for invalid parameter values outside the supported domain edge
Returns
-------
"""
# Test pymc3 and scipy distributions match for values and parameters
# within the supported domain edges (excluding edges)
if not skip_paramdomain_inside_edge_test:
domains = paramdomains.copy()
domains["value"] = domain
if decimal is None:
decimal = select_by_precision(float64=6, float32=3)
for pt in product(domains, n_samples=n_samples):
params = dict(pt)
scipy_cdf = scipy_logcdf(**params)
value = params.pop("value")
with Model() as m:
dist = pymc3_dist("y", **params)
params["value"] = value # for displaying in err_msg
with aesara.config.change_flags(on_opt_error="raise", mode=Mode("py")):
assert_almost_equal(
logcdf(dist, value).eval(),
scipy_cdf,
decimal=decimal,
err_msg=str(params),
)
valid_value = domain.vals[0]
valid_params = {param: paramdomain.vals[0] for param, paramdomain in paramdomains.items()}
valid_dist = pymc3_dist.dist(**valid_params)
# Natural domains do not have inf as the upper edge, but should also be ignored
nat_domains = (NatSmall, Nat, NatBig, PosNat)
# Test pymc3 distribution gives -inf for parameters outside the
# supported domain edges (excluding edgse)
if not skip_paramdomain_outside_edge_test:
# Step1: collect potential invalid parameters
invalid_params = {param: [None, None] for param in paramdomains}
for param, paramdomain in paramdomains.items():
if np.isfinite(paramdomain.lower):
invalid_params[param][0] = paramdomain.lower - 1
if np.isfinite(paramdomain.upper) and paramdomain not in nat_domains:
invalid_params[param][1] = paramdomain.upper + 1
# Step2: test invalid parameters, one a time
for invalid_param, invalid_edges in invalid_params.items():
for invalid_edge in invalid_edges:
if invalid_edge is not None:
test_params = valid_params.copy() # Shallow copy should be okay
test_params[invalid_param] = invalid_edge
# We need to remove `Assert`s introduced by checks like
# `assert_negative_support` and disable test values;
# otherwise, we won't be able to create the
# `RandomVariable`
with aesara.config.change_flags(compute_test_value="off"):
invalid_dist = pymc3_dist.dist(**test_params)
with aesara.config.change_flags(mode=Mode("py")):
assert_equal(
logcdf(invalid_dist, valid_value).eval(),
-np.inf,
err_msg=str(test_params),
)
# Test that values below domain edge evaluate to -np.inf
if np.isfinite(domain.lower):
below_domain = domain.lower - 1
with aesara.config.change_flags(mode=Mode("py")):
assert_equal(
logcdf(valid_dist, below_domain).eval(),
-np.inf,
err_msg=str(below_domain),
)
# Test that values above domain edge evaluate to 0
if domain not in nat_domains and np.isfinite(domain.upper):
above_domain = domain.upper + 1
with aesara.config.change_flags(mode=Mode("py")):
assert_equal(
logcdf(valid_dist, above_domain).eval(),
0,
err_msg=str(above_domain),
)
# Test that method works with multiple values or raises informative TypeError
with pytest.raises(TypeError), aesara.config.change_flags(mode=Mode("py")):
logcdf(valid_dist, np.array([valid_value, valid_value])).eval()
def check_selfconsistency_discrete_logcdf(
self, distribution, domain, paramdomains, decimal=None, n_samples=100
):
"""
Check that logcdf of discrete distributions matches sum of logps up to value
"""
domains = paramdomains.copy()
domains["value"] = domain
if decimal is None:
decimal = select_by_precision(float64=6, float32=3)
for pt in product(domains, n_samples=n_samples):
params = dict(pt)
value = params.pop("value")
values = np.arange(domain.lower, value + 1)
dist = distribution.dist(**params)
# This only works for scalar random variables
assert dist.owner.op.ndim_supp == 0
values_dist = change_rv_size(dist, values.shape)
with aesara.config.change_flags(mode=Mode("py")):
assert_almost_equal(
logcdf(dist, value).eval(),
logsumexp(logpt(values_dist, values), keepdims=False).eval(),
decimal=decimal,
err_msg=str(pt),
)
def check_int_to_1(self, model, value, domain, paramdomains, n_samples=10):
pdf = model.fastfn(exp(model.logpt))
for pt in product(paramdomains, n_samples=n_samples):
pt = Point(pt, value=value.tag.test_value, model=model)
bij = DictToVarBijection(value, (), pt)
pdfx = bij.mapf(pdf)
area = integrate_nd(pdfx, domain, value.dshape, value.dtype)
assert_almost_equal(area, 1, err_msg=str(pt))
def checkd(self, distfam, valuedomain, vardomains, checks=None, extra_args=None):
if checks is None:
checks = (self.check_int_to_1,)
if extra_args is None:
extra_args = {}
m = build_model(distfam, valuedomain, vardomains, extra_args=extra_args)
for check in checks:
check(m, m.named_vars["value"], valuedomain, vardomains)
def test_uniform(self):
self.check_logp(
Uniform,
Runif,
{"lower": -Rplusunif, "upper": Rplusunif},
lambda value, lower, upper: sp.uniform.logpdf(value, lower, upper - lower),
)
self.check_logcdf(
Uniform,
Runif,
{"lower": -Rplusunif, "upper": Rplusunif},
lambda value, lower, upper: sp.uniform.logcdf(value, lower, upper - lower),
skip_paramdomain_outside_edge_test=True,
)
# Custom logp / logcdf check for invalid parameters
invalid_dist = Uniform.dist(lower=1, upper=0)
with aesara.config.change_flags(mode=Mode("py")):
assert logpt(invalid_dist, np.array(0.5)).eval() == -np.inf
assert logcdf(invalid_dist, np.array(2.0)).eval() == -np.inf
@pytest.mark.xfail(reason="Distribution not refactored yet")
def test_triangular(self):
self.check_logp(
Triangular,
Runif,
{"lower": -Rplusunif, "c": Runif, "upper": Rplusunif},
lambda value, c, lower, upper: sp.triang.logpdf(value, c - lower, lower, upper - lower),
)
self.check_logcdf(
Triangular,
Runif,
{"lower": -Rplusunif, "c": Runif, "upper": Rplusunif},
lambda value, c, lower, upper: sp.triang.logcdf(value, c - lower, lower, upper - lower),
skip_paramdomain_outside_edge_test=True,
)
# Custom logp check for invalid value
valid_dist = Triangular.dist(lower=0, upper=1, c=2.0)
assert np.all(logpt(valid_dist, np.array([1.9, 2.0, 2.1])).tag.test_value == -np.inf)
# Custom logp / logcdf check for invalid parameters
invalid_dist = Triangular.dist(lower=1, upper=0, c=2.0)
with aesara.config.change_flags(mode=Mode("py")):
assert logpt(invalid_dist, 0.5).eval() == -np.inf
assert logcdf(invalid_dist, 2).eval() == -np.inf
@pytest.mark.xfail(reason="Bound not refactored yet")
def test_bound_normal(self):
PositiveNormal = Bound(Normal, lower=0.0)
self.check_logp(
PositiveNormal,
Rplus,
{"mu": Rplus, "sigma": Rplus},
lambda value, mu, sigma: sp.norm.logpdf(value, mu, sigma),
decimal=select_by_precision(float64=6, float32=-1),
)
with Model():
x = PositiveNormal("x", mu=0, sigma=1, transform=None)
assert np.isinf(logpt(x, -1).eval())
@pytest.mark.xfail(reason="Distribution not refactored yet")
def test_discrete_unif(self):
self.check_logp(
DiscreteUniform,
Rdunif,
{"lower": -Rplusdunif, "upper": Rplusdunif},
lambda value, lower, upper: sp.randint.logpmf(value, lower, upper + 1),
)
self.check_logcdf(
DiscreteUniform,
Rdunif,
{"lower": -Rplusdunif, "upper": Rplusdunif},
lambda value, lower, upper: sp.randint.logcdf(value, lower, upper + 1),
skip_paramdomain_outside_edge_test=True,
)
self.check_selfconsistency_discrete_logcdf(
DiscreteUniform,
Rdunif,
{"lower": -Rplusdunif, "upper": Rplusdunif},
)
# Custom logp / logcdf check for invalid parameters
invalid_dist = DiscreteUniform.dist(lower=1, upper=0)
with aesara.config.change_flags(mode=Mode("py")):
assert logpt(invalid_dist, 0.5).eval() == -np.inf
assert logcdf(invalid_dist, 2).eval() == -np.inf
@pytest.mark.xfail(reason="Distribution not refactored yet")
def test_flat(self):
self.check_logp(Flat, Runif, {}, lambda value: 0)
with Model():
x = Flat("a")
assert_allclose(x.tag.test_value, 0)
self.check_logcdf(Flat, R, {}, lambda value: np.log(0.5))
# Check infinite cases individually.
assert 0.0 == logcdf(Flat.dist(), np.inf).tag.test_value
assert -np.inf == logcdf(Flat.dist(), -np.inf).tag.test_value
@pytest.mark.xfail(reason="Distribution not refactored yet")
def test_half_flat(self):
self.check_logp(HalfFlat, Rplus, {}, lambda value: 0)
with Model():
x = HalfFlat("a", size=2)
assert_allclose(x.tag.test_value, 1)
assert x.tag.test_value.shape == (2,)
self.check_logcdf(HalfFlat, Rplus, {}, lambda value: -np.inf)
# Check infinite cases individually.
assert 0.0 == logcdf(HalfFlat.dist(), np.inf).tag.test_value
assert -np.inf == logcdf(HalfFlat.dist(), -np.inf).tag.test_value
def test_normal(self):
self.check_logp(
Normal,
R,
{"mu": R, "sigma": Rplus},
lambda value, mu, sigma: sp.norm.logpdf(value, mu, sigma),
decimal=select_by_precision(float64=6, float32=1),
)
self.check_logcdf(
Normal,
R,
{"mu": R, "sigma": Rplus},
lambda value, mu, sigma: sp.norm.logcdf(value, mu, sigma),
decimal=select_by_precision(float64=6, float32=1),
)
@pytest.mark.xfail(reason="Distribution not refactored yet")
def test_truncated_normal(self):
def scipy_logp(value, mu, sigma, lower, upper):
return sp.truncnorm.logpdf(
value, (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma
)
self.check_logp(
TruncatedNormal,
R,
{"mu": R, "sigma": Rplusbig, "lower": -Rplusbig, "upper": Rplusbig},