-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathtest_continuous.py
2391 lines (2124 loc) · 82.4 KB
/
test_continuous.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 2023 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 functools as ft
import warnings
import numpy as np
import numpy.testing as npt
import pytensor
import pytensor.tensor as pt
import pytest
import scipy.special as sp
import scipy.stats as st
from pytensor.compile.mode import Mode
import pymc as pm
from pymc.distributions.continuous import Normal, Uniform, get_tau_sigma, interpolated
from pymc.distributions.dist_math import clipped_beta_rvs
from pymc.logprob.basic import icdf, logcdf, logp
from pymc.logprob.utils import ParameterValueError
from pymc.pytensorf import floatX
from pymc.testing import (
BaseTestDistributionRandom,
Circ,
Domain,
R,
Rplus,
Rplusbig,
Rplusunif,
Runif,
Unit,
assert_moment_is_expected,
check_icdf,
check_logcdf,
check_logp,
continuous_random_tester,
seeded_numpy_distribution_builder,
seeded_scipy_distribution_builder,
select_by_precision,
)
from tests.logprob.utils import create_pytensor_params, scipy_logprob_tester
try:
from polyagamma import polyagamma_cdf, polyagamma_pdf, random_polyagamma
_polyagamma_not_installed = False
except ImportError: # pragma: no cover
_polyagamma_not_installed = True
def polyagamma_pdf(*args, **kwargs):
raise RuntimeError("polyagamma package is not installed!")
def polyagamma_cdf(*args, **kwargs):
raise RuntimeError("polyagamma package is not installed!")
def random_polyagamma(*args, **kwargs):
raise RuntimeError("polyagamma package is not installed!")
class TestBoundedContinuous:
def get_dist_params_and_interval_bounds(self, model, rv_name):
rv = model.named_vars[rv_name]
dist_params = rv.owner.inputs
lower_interval, upper_interval = model.rvs_to_transforms[rv].args_fn(*rv.owner.inputs)
return (
dist_params,
lower_interval,
upper_interval,
)
def test_upper_bounded(self):
bounded_rv_name = "lower_bounded"
with pm.Model() as model:
pm.TruncatedNormal(bounded_rv_name, mu=1, sigma=2, lower=None, upper=3)
(
(_, _, _, _, _, lower, upper),
lower_interval,
upper_interval,
) = self.get_dist_params_and_interval_bounds(model, bounded_rv_name)
assert lower.value == -np.inf
assert upper.value == 3
assert lower_interval is None
assert upper_interval.value == 3
def test_lower_bounded(self):
bounded_rv_name = "upper_bounded"
with pm.Model() as model:
pm.TruncatedNormal(bounded_rv_name, mu=1, sigma=2, lower=-2, upper=None)
(
(_, _, _, _, _, lower, upper),
lower_interval,
upper_interval,
) = self.get_dist_params_and_interval_bounds(model, bounded_rv_name)
assert lower.value == -2
assert upper.value == np.inf
assert lower_interval.value == -2
assert upper_interval is None
def test_lower_bounded_vector(self):
bounded_rv_name = "upper_bounded"
with pm.Model() as model:
pm.TruncatedNormal(
bounded_rv_name,
mu=np.array([1, 1]),
sigma=np.array([2, 3]),
lower=np.array([-1.0, 0]),
upper=None,
)
(
(_, _, _, _, _, lower, upper),
lower_interval,
upper_interval,
) = self.get_dist_params_and_interval_bounds(model, bounded_rv_name)
assert np.array_equal(lower.value, [-1, 0])
assert upper.value == np.inf
assert np.array_equal(lower_interval.value, [-1, 0])
assert upper_interval is None
def test_lower_bounded_broadcasted(self):
bounded_rv_name = "upper_bounded"
with pm.Model() as model:
pm.TruncatedNormal(
bounded_rv_name,
mu=np.array([1, 1]),
sigma=np.array([2, 3]),
lower=-1,
upper=np.array([np.inf, np.inf]),
)
(
(_, _, _, _, _, lower, upper),
lower_interval,
upper_interval,
) = self.get_dist_params_and_interval_bounds(model, bounded_rv_name)
assert lower.value == -1
assert np.array_equal(upper.value, [np.inf, np.inf])
assert lower_interval.value == -1
assert upper_interval is None
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
class TestMatchesScipy:
def test_uniform(self):
check_logp(
pm.Uniform,
Runif,
{"lower": -Rplusunif, "upper": Rplusunif},
lambda value, lower, upper: st.uniform.logpdf(value, lower, upper - lower),
skip_paramdomain_outside_edge_test=True,
)
check_logcdf(
pm.Uniform,
Runif,
{"lower": -Rplusunif, "upper": Rplusunif},
lambda value, lower, upper: st.uniform.logcdf(value, lower, upper - lower),
skip_paramdomain_outside_edge_test=True,
)
check_icdf(
pm.Uniform,
{"lower": -Rplusunif, "upper": Rplusunif},
lambda q, lower, upper: st.uniform.ppf(q=q, loc=lower, scale=upper - lower),
skip_paramdomain_outside_edge_test=True,
)
# Custom logp / logcdf check for invalid parameters
invalid_dist = pm.Uniform.dist(lower=1, upper=0)
with pytensor.config.change_flags(mode=Mode("py")):
with pytest.raises(ParameterValueError):
logp(invalid_dist, np.array(0.5)).eval()
with pytest.raises(ParameterValueError):
logcdf(invalid_dist, np.array(0.5)).eval()
with pytest.raises(ParameterValueError):
icdf(invalid_dist, np.array(0.5)).eval()
def test_triangular(self):
check_logp(
pm.Triangular,
Runif,
{"lower": -Rplusunif, "c": Runif, "upper": Rplusunif},
lambda value, c, lower, upper: st.triang.logpdf(value, c - lower, lower, upper - lower),
skip_paramdomain_outside_edge_test=True,
)
check_logcdf(
pm.Triangular,
Runif,
{"lower": -Rplusunif, "c": Runif, "upper": Rplusunif},
lambda value, c, lower, upper: st.triang.logcdf(value, c - lower, lower, upper - lower),
skip_paramdomain_outside_edge_test=True,
)
check_icdf(
pm.Triangular,
{"lower": -Rplusunif, "c": Runif, "upper": Rplusunif},
lambda q, c, lower, upper: st.triang.ppf(q, c - lower, lower, upper - lower),
skip_paramdomain_outside_edge_test=True,
)
# Custom logp/logcdf check for values outside of domain
valid_dist = pm.Triangular.dist(lower=0, upper=1, c=0.9, size=2)
with pytensor.config.change_flags(mode=Mode("py")):
assert np.all(logp(valid_dist, np.array([-1, 2])).eval() == -np.inf)
assert np.all(logcdf(valid_dist, np.array([-1, 2])).eval() == [-np.inf, 0])
# Custom logcdf check for invalid parameters.
# Invalid logp checks for triangular are being done in aeppl
invalid_dist = pm.Triangular.dist(lower=1, upper=0, c=0.1)
with pytensor.config.change_flags(mode=Mode("py")):
with pytest.raises(ParameterValueError):
logcdf(invalid_dist, 2).eval()
invalid_dist = pm.Triangular.dist(lower=0, upper=1, c=2.0)
with pytensor.config.change_flags(mode=Mode("py")):
with pytest.raises(ParameterValueError):
logcdf(invalid_dist, 2).eval()
@pytest.mark.skipif(
condition=_polyagamma_not_installed,
reason="`polyagamma package is not available/installed.",
)
def test_polyagamma(self):
check_logp(
pm.PolyaGamma,
Rplus,
{"h": Rplus, "z": R},
lambda value, h, z: polyagamma_pdf(value, h, z, return_log=True),
decimal=select_by_precision(float64=6, float32=-1),
)
check_logcdf(
pm.PolyaGamma,
Rplus,
{"h": Rplus, "z": R},
lambda value, h, z: polyagamma_cdf(value, h, z, return_log=True),
decimal=select_by_precision(float64=6, float32=-1),
)
def test_flat(self):
check_logp(pm.Flat, R, {}, lambda value: 0)
with pm.Model():
x = pm.Flat("a")
check_logcdf(pm.Flat, R, {}, lambda value: np.log(0.5))
# Check infinite cases individually.
assert 0.0 == logcdf(pm.Flat.dist(), np.inf).eval()
assert -np.inf == logcdf(pm.Flat.dist(), -np.inf).eval()
def test_half_flat(self):
check_logp(pm.HalfFlat, Rplus, {}, lambda value: 0)
with pm.Model():
x = pm.HalfFlat("a", size=2)
check_logcdf(pm.HalfFlat, Rplus, {}, lambda value: -np.inf)
# Check infinite cases individually.
assert 0.0 == logcdf(pm.HalfFlat.dist(), np.inf).eval()
assert -np.inf == logcdf(pm.HalfFlat.dist(), -np.inf).eval()
def test_normal(self):
check_logp(
pm.Normal,
R,
{"mu": R, "sigma": Rplus},
lambda value, mu, sigma: st.norm.logpdf(value, mu, sigma),
decimal=select_by_precision(float64=6, float32=1),
)
check_logcdf(
pm.Normal,
R,
{"mu": R, "sigma": Rplus},
lambda value, mu, sigma: st.norm.logcdf(value, mu, sigma),
decimal=select_by_precision(float64=6, float32=1),
)
check_icdf(
pm.Normal,
{"mu": R, "sigma": Rplus},
lambda q, mu, sigma: st.norm.ppf(q, mu, sigma),
)
def test_half_normal(self):
check_logp(
pm.HalfNormal,
Rplus,
{"sigma": Rplus},
lambda value, sigma: st.halfnorm.logpdf(value, scale=sigma),
decimal=select_by_precision(float64=6, float32=-1),
)
check_logcdf(
pm.HalfNormal,
Rplus,
{"sigma": Rplus},
lambda value, sigma: st.halfnorm.logcdf(value, scale=sigma),
)
check_icdf(
pm.HalfNormal,
{"sigma": Rplus},
lambda q, sigma: st.halfnorm.ppf(q, scale=sigma),
)
def test_chisquared_logp(self):
check_logp(
pm.ChiSquared,
Rplus,
{"nu": Rplus},
lambda value, nu: st.chi2.logpdf(value, df=nu),
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="Fails on float32 due to numerical issues",
)
def test_chisquared_logcdf(self):
check_logcdf(
pm.ChiSquared,
Rplus,
{"nu": Rplus},
lambda value, nu: st.chi2.logcdf(value, df=nu),
)
def test_wald_logp(self):
check_logp(
pm.Wald,
Rplus,
{"mu": Rplus, "alpha": Rplus},
lambda value, mu, alpha: st.invgauss.logpdf(value, mu=mu, loc=alpha),
decimal=select_by_precision(float64=6, float32=1),
)
def test_wald_logcdf(self):
check_logcdf(
pm.Wald,
Rplus,
{"mu": Rplus, "alpha": Rplus},
lambda value, mu, alpha: st.invgauss.logcdf(value, mu=mu, loc=alpha),
)
@pytest.mark.parametrize(
"value,mu,lam,phi,alpha,logp",
[
(0.5, 0.001, 0.5, None, 0.0, -124500.7257914),
(1.0, 0.5, 0.001, None, 0.0, -4.3733162),
(2.0, 1.0, None, None, 0.0, -2.2086593),
(5.0, 2.0, 2.5, None, 0.0, -3.4374500),
(7.5, 5.0, None, 1.0, 0.0, -3.2199074),
(15.0, 10.0, None, 0.75, 0.0, -4.0360623),
(50.0, 15.0, None, 0.66666, 0.0, -6.1801249),
(0.5, 0.001, 0.5, None, 0.0, -124500.7257914),
(1.0, 0.5, 0.001, None, 0.5, -3.3330954),
(2.0, 1.0, None, None, 1.0, -0.9189385),
(5.0, 2.0, 2.5, None, 2.0, -2.2128783),
(7.5, 5.0, None, 1.0, 2.5, -2.5283764),
(15.0, 10.0, None, 0.75, 5.0, -3.3653647),
(50.0, 15.0, None, 0.666666, 10.0, -5.6481874),
],
)
def test_wald_logp_custom_points(self, value, mu, lam, phi, alpha, logp):
# Log probabilities calculated using the dIG function from the R package gamlss.
# See e.g., doi: 10.1111/j.1467-9876.2005.00510.x, or
# http://www.gamlss.org/.
with pm.Model() as model:
pm.Wald("wald", mu=mu, lam=lam, phi=phi, alpha=alpha, transform=None)
point = {"wald": value}
decimals = select_by_precision(float64=6, float32=1)
npt.assert_almost_equal(
model.compile_logp()(point), logp, decimal=decimals, err_msg=str(point)
)
def test_beta_logp(self):
check_logp(
pm.Beta,
Unit,
{"alpha": Rplus, "beta": Rplus},
lambda value, alpha, beta: st.beta.logpdf(value, alpha, beta),
)
def beta_mu_sigma(value, mu, sigma):
kappa = mu * (1 - mu) / sigma**2 - 1
return st.beta.logpdf(value, mu * kappa, (1 - mu) * kappa)
# The mu/sigma parametrization is not always valid
safe_mu_domain = Domain([0, 0.3, 0.5, 0.8, 1])
safe_sigma_domain = Domain([0, 0.05, 0.1, np.inf])
check_logp(
pm.Beta,
Unit,
{"mu": safe_mu_domain, "sigma": safe_sigma_domain},
beta_mu_sigma,
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="Fails on float32 due to numerical issues",
)
def test_beta_logcdf(self):
check_logcdf(
pm.Beta,
Unit,
{"alpha": Rplus, "beta": Rplus},
lambda value, alpha, beta: st.beta.logcdf(value, alpha, beta),
)
def test_kumaraswamy(self):
# Scipy does not have a built-in Kumaraswamy
def scipy_log_pdf(value, a, b):
return (
np.log(a) + np.log(b) + (a - 1) * np.log(value) + (b - 1) * np.log(1 - value**a)
)
def scipy_log_cdf(value, a, b):
return pm.math.log1mexp_numpy(b * np.log1p(-(value**a)), negative_input=True)
check_logp(
pm.Kumaraswamy,
Unit,
{"a": Rplus, "b": Rplus},
scipy_log_pdf,
)
check_logcdf(
pm.Kumaraswamy,
Unit,
{"a": Rplus, "b": Rplus},
scipy_log_cdf,
)
def test_exponential(self):
check_logp(
pm.Exponential,
Rplus,
{"lam": Rplus},
lambda value, lam: st.expon.logpdf(value, 0, 1 / lam),
)
check_logcdf(
pm.Exponential,
Rplus,
{"lam": Rplus},
lambda value, lam: st.expon.logcdf(value, 0, 1 / lam),
)
check_icdf(
pm.Exponential,
{"lam": Rplus},
lambda q, lam: st.expon.ppf(q, loc=0, scale=1 / lam),
)
def test_exponential_wrong_arguments(self):
msg = "Incompatible parametrization. Can't specify both lam and scale"
with pytest.raises(ValueError, match=msg):
pm.Exponential.dist(lam=0.5, scale=5)
msg = "Incompatible parametrization. Must specify either lam or scale"
with pytest.raises(ValueError, match=msg):
pm.Exponential.dist()
def test_laplace(self):
check_logp(
pm.Laplace,
R,
{"mu": R, "b": Rplus},
lambda value, mu, b: st.laplace.logpdf(value, mu, b),
)
check_logcdf(
pm.Laplace,
R,
{"mu": R, "b": Rplus},
lambda value, mu, b: st.laplace.logcdf(value, mu, b),
)
check_icdf(pm.Laplace, {"mu": R, "b": Rplus}, lambda q, mu, b: st.laplace.ppf(q, mu, b))
def test_laplace_asymmetric(self):
check_logp(
pm.AsymmetricLaplace,
R,
{"b": Rplus, "kappa": Rplus, "mu": R},
laplace_asymmetric_logpdf,
decimal=select_by_precision(float64=6, float32=2),
)
def test_lognormal(self):
check_logp(
pm.LogNormal,
Rplus,
{"mu": R, "tau": Rplusbig},
lambda value, mu, tau: floatX(st.lognorm.logpdf(value, tau**-0.5, 0, np.exp(mu))),
)
check_logp(
pm.LogNormal,
Rplus,
{"mu": R, "sigma": Rplusbig},
lambda value, mu, sigma: floatX(st.lognorm.logpdf(value, sigma, 0, np.exp(mu))),
)
check_logcdf(
pm.LogNormal,
Rplus,
{"mu": R, "tau": Rplusbig},
lambda value, mu, tau: st.lognorm.logcdf(value, tau**-0.5, 0, np.exp(mu)),
)
check_logcdf(
pm.LogNormal,
Rplus,
{"mu": R, "sigma": Rplusbig},
lambda value, mu, sigma: st.lognorm.logcdf(value, sigma, 0, np.exp(mu)),
)
check_icdf(
pm.LogNormal,
{"mu": R, "tau": Rplusbig},
lambda q, mu, tau: floatX(st.lognorm.ppf(q, tau**-0.5, 0, np.exp(mu))),
)
# Because we exponentiate the normal quantile function, setting sigma >= 9.5
# return extreme values that results in relative errors above 4 digits
# we circumvent it by keeping it below or equal to 9.
custom_rplusbig = Domain([0, 0.5, 0.9, 0.99, 1, 1.5, 2, 9, np.inf])
check_icdf(
pm.LogNormal,
{"mu": R, "sigma": custom_rplusbig},
lambda q, mu, sigma: floatX(st.lognorm.ppf(q, sigma, 0, np.exp(mu))),
decimal=select_by_precision(float64=4, float32=3),
)
def test_studentt_logp(self):
check_logp(
pm.StudentT,
R,
{"nu": Rplus, "mu": R, "lam": Rplus},
lambda value, nu, mu, lam: st.t.logpdf(value, nu, mu, lam**-0.5),
)
check_logp(
pm.StudentT,
R,
{"nu": Rplus, "mu": R, "sigma": Rplus},
lambda value, nu, mu, sigma: st.t.logpdf(value, nu, mu, sigma),
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="Fails on float32 due to numerical issues",
)
def test_studentt_logcdf(self):
check_logcdf(
pm.StudentT,
R,
{"nu": Rplus, "mu": R, "lam": Rplus},
lambda value, nu, mu, lam: st.t.logcdf(value, nu, mu, lam**-0.5),
)
check_logcdf(
pm.StudentT,
R,
{"nu": Rplus, "mu": R, "sigma": Rplus},
lambda value, nu, mu, sigma: st.t.logcdf(value, nu, mu, sigma),
)
def test_cauchy(self):
check_logp(
pm.Cauchy,
R,
{"alpha": R, "beta": Rplusbig},
lambda value, alpha, beta: st.cauchy.logpdf(value, alpha, beta),
)
check_logcdf(
pm.Cauchy,
R,
{"alpha": R, "beta": Rplusbig},
lambda value, alpha, beta: st.cauchy.logcdf(value, alpha, beta),
)
check_icdf(
pm.Cauchy,
{"alpha": R, "beta": Rplusbig},
lambda q, alpha, beta: st.cauchy.ppf(q, alpha, beta),
)
def test_half_cauchy(self):
check_logp(
pm.HalfCauchy,
Rplus,
{"beta": Rplusbig},
lambda value, beta: st.halfcauchy.logpdf(value, scale=beta),
)
check_logcdf(
pm.HalfCauchy,
Rplus,
{"beta": Rplusbig},
lambda value, beta: st.halfcauchy.logcdf(value, scale=beta),
)
check_icdf(
pm.HalfCauchy, {"beta": Rplusbig}, lambda q, beta: st.halfcauchy.ppf(q, scale=beta)
)
def test_gamma_logp(self):
check_logp(
pm.Gamma,
Rplus,
{"alpha": Rplusbig, "beta": Rplusbig},
lambda value, alpha, beta: st.gamma.logpdf(value, alpha, scale=1.0 / beta),
)
def test_fun(value, mu, sigma):
return st.gamma.logpdf(value, mu**2 / sigma**2, scale=1.0 / (mu / sigma**2))
check_logp(
pm.Gamma,
Rplus,
{"mu": Rplusbig, "sigma": Rplusbig},
test_fun,
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="Fails on float32 due to numerical issues",
)
def test_gamma_logcdf(self):
check_logcdf(
pm.Gamma,
Rplus,
{"alpha": Rplusbig, "beta": Rplusbig},
lambda value, alpha, beta: st.gamma.logcdf(value, alpha, scale=1.0 / beta),
)
def test_inverse_gamma_logp(self):
check_logp(
pm.InverseGamma,
Rplus,
{"alpha": Rplus, "beta": Rplus},
lambda value, alpha, beta: st.invgamma.logpdf(value, alpha, scale=beta),
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="Fails on float32 due to numerical issues",
)
def test_inverse_gamma_logcdf(self):
check_logcdf(
pm.InverseGamma,
Rplus,
{"alpha": Rplus, "beta": Rplus},
lambda value, alpha, beta: st.invgamma.logcdf(value, alpha, scale=beta),
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="Fails on float32 due to scaling issues",
)
def test_inverse_gamma_alt_params(self):
def test_fun(value, mu, sigma):
alpha, beta = pm.InverseGamma._get_alpha_beta(None, None, mu, sigma)
return st.invgamma.logpdf(value, alpha, scale=beta)
check_logp(
pm.InverseGamma,
Rplus,
{"mu": Rplus, "sigma": Rplus},
test_fun,
decimal=select_by_precision(float64=4, float32=3),
)
def test_pareto(self):
check_logp(
pm.Pareto,
Rplus,
{"alpha": Rplusbig, "m": Rplusbig},
lambda value, alpha, m: st.pareto.logpdf(value, alpha, scale=m),
)
check_logcdf(
pm.Pareto,
Rplus,
{"alpha": Rplusbig, "m": Rplusbig},
lambda value, alpha, m: st.pareto.logcdf(value, alpha, scale=m),
)
check_icdf(
pm.Pareto,
{"alpha": Rplusbig, "m": Rplusbig},
lambda q, alpha, m: st.pareto.ppf(q, alpha, scale=m),
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="Fails on float32 due to numerical issues",
)
def test_weibull_logp(self):
# SciPy has new (?) precision issues at {alpha=20, beta=2, x=100}
# We circumvent it by skipping alpha=20:
rplusbig = Domain([0, 0.5, 0.9, 0.99, 1, 1.5, 2, np.inf])
check_logp(
pm.Weibull,
Rplus,
{"alpha": rplusbig, "beta": Rplusbig},
lambda value, alpha, beta: st.exponweib.logpdf(value, 1, alpha, scale=beta),
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="Fails on float32 due to inf issues",
)
def test_weibull_logcdf(self):
check_logcdf(
pm.Weibull,
Rplus,
{"alpha": Rplusbig, "beta": Rplusbig},
lambda value, alpha, beta: st.exponweib.logcdf(value, 1, alpha, scale=beta),
)
def test_weibull_icdf(self):
check_icdf(
pm.Weibull,
{"alpha": Rplusbig, "beta": Rplusbig},
lambda q, alpha, beta: st.exponweib.ppf(q, 1, alpha, scale=beta),
)
def test_half_studentt(self):
# this is only testing for nu=1 (halfcauchy)
check_logp(
pm.HalfStudentT,
Rplus,
{"sigma": Rplus},
lambda value, sigma: st.halfcauchy.logpdf(value, 0, sigma),
extra_args={"nu": 1},
)
def test_skew_normal(self):
check_logp(
pm.SkewNormal,
R,
{"mu": R, "sigma": Rplusbig, "alpha": R},
lambda value, alpha, mu, sigma: st.skewnorm.logpdf(value, alpha, mu, sigma),
decimal=select_by_precision(float64=5, float32=3),
)
@pytest.mark.parametrize(
"value,mu,sigma,nu,logcdf_val",
[
(0.5, -50.000, 0.500, 0.500, 0.0000000),
(1.0, -1.000, 0.001, 0.001, 0.0000000),
(2.0, 0.001, 1.000, 1.000, -0.2365674),
(5.0, 0.500, 2.500, 2.500, -0.2886489),
(7.5, 2.000, 5.000, 5.000, -0.5655104),
(15.0, 5.000, 7.500, 7.500, -0.4545255),
(50.0, 50.000, 10.000, 10.000, -1.433714),
(1000.0, 500.000, 10.000, 20.000, -1.573708e-11),
(0.01, 0.01, 100.0, 0.01, -0.69314718), # Fails in scipy version
(-0.43402407, 0.0, 0.1, 0.1, -13.59615423), # Previous 32-bit version failed here
(-0.72402009, 0.0, 0.1, 0.1, -31.26571842), # Previous 64-bit version failed here
],
)
def test_ex_gaussian_cdf(self, value, mu, sigma, nu, logcdf_val):
"""Log probabilities calculated using the pexGAUS function from the R package gamlss.
See e.g., doi: 10.1111/j.1467-9876.2005.00510.x, or http://www.gamlss.org/."""
npt.assert_almost_equal(
logcdf(pm.ExGaussian.dist(mu=mu, sigma=sigma, nu=nu), value).eval(),
logcdf_val,
decimal=select_by_precision(float64=6, float32=2),
err_msg=str((value, mu, sigma, nu, logcdf_val)),
)
def test_ex_gaussian_cdf_outside_edges(self):
check_logcdf(
pm.ExGaussian,
R,
{"mu": R, "sigma": Rplus, "nu": Rplus},
None,
skip_paramdomain_inside_edge_test=True, # Valid values are tested above
)
@pytest.mark.skipif(condition=(pytensor.config.floatX == "float32"), reason="Fails on float32")
def test_vonmises(self):
check_logp(
pm.VonMises,
Circ,
{"mu": R, "kappa": Rplus},
lambda value, mu, kappa: floatX(st.vonmises.logpdf(value, kappa, loc=mu)),
)
def test_gumbel(self):
check_logp(
pm.Gumbel,
R,
{"mu": R, "beta": Rplusbig},
lambda value, mu, beta: st.gumbel_r.logpdf(value, loc=mu, scale=beta),
)
check_logcdf(
pm.Gumbel,
R,
{"mu": R, "beta": Rplusbig},
lambda value, mu, beta: st.gumbel_r.logcdf(value, loc=mu, scale=beta),
)
check_icdf(
pm.Gumbel,
{"mu": R, "beta": Rplusbig},
lambda q, mu, beta: st.gumbel_r.ppf(q, loc=mu, scale=beta),
)
def test_logistic(self):
check_logp(
pm.Logistic,
R,
{"mu": R, "s": Rplus},
lambda value, mu, s: st.logistic.logpdf(value, mu, s),
decimal=select_by_precision(float64=6, float32=1),
)
check_logcdf(
pm.Logistic,
R,
{"mu": R, "s": Rplus},
lambda value, mu, s: st.logistic.logcdf(value, mu, s),
decimal=select_by_precision(float64=6, float32=1),
)
check_icdf(
pm.Logistic,
{"mu": R, "s": Rplus},
lambda q, mu, s: st.logistic.ppf(q, mu, s),
decimal=select_by_precision(float64=6, float32=1),
)
def test_logitnormal(self):
check_logp(
pm.LogitNormal,
Unit,
{"mu": R, "sigma": Rplus},
lambda value, mu, sigma: (
st.norm.logpdf(sp.logit(value), mu, sigma) - (np.log(value) + np.log1p(-value))
),
decimal=select_by_precision(float64=6, float32=1),
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="Some combinations underflow to -inf in float32 in pymc version",
)
def test_rice(self):
check_logp(
pm.Rice,
Rplus,
{"b": Rplus, "sigma": Rplusbig},
lambda value, b, sigma: st.rice.logpdf(value, b=b, loc=0, scale=sigma),
)
if pytensor.config.floatX == "float32":
raise Exception("Flaky test: It passed this time, but XPASS is not allowed.")
def test_rice_nu(self):
check_logp(
pm.Rice,
Rplus,
{"nu": Rplus, "sigma": Rplusbig},
lambda value, nu, sigma: st.rice.logpdf(value, b=nu / sigma, loc=0, scale=sigma),
)
def test_moyal_logp(self):
# Using a custom domain, because the standard `R` domain underflows with scipy in float64
value_domain = Domain([-np.inf, -1.5, -1, -0.01, 0.0, 0.01, 1, 1.5, np.inf])
check_logp(
pm.Moyal,
value_domain,
{"mu": R, "sigma": Rplusbig},
lambda value, mu, sigma: floatX(st.moyal.logpdf(value, mu, sigma)),
)
@pytest.mark.skipif(
condition=(pytensor.config.floatX == "float32"),
reason="PyMC underflows earlier than scipy on float32",
)
def test_moyal_logcdf(self):
# SciPy has new (?) precision issues at {mu=-2.1, sigma=0.5, x=2.1}
# We circumvent it by skipping sigma=0.5:
rplusbig = Domain([0, 0.9, 0.99, 1, 1.5, 2, 20, np.inf])
check_logcdf(
pm.Moyal,
R,
{"mu": R, "sigma": rplusbig},
lambda value, mu, sigma: floatX(st.moyal.logcdf(value, mu, sigma)),
)
if pytensor.config.floatX == "float32":
raise Exception("Flaky test: It passed this time, but XPASS is not allowed.")
def test_moyal_icdf(self):
check_icdf(
pm.Moyal,
{"mu": R, "sigma": Rplusbig},
lambda q, mu, sigma: floatX(st.moyal.ppf(q, mu, sigma)),
)
def test_interpolated(self):
for mu in R.vals:
for sigma in Rplus.vals:
# pylint: disable=cell-var-from-loop
xmin = mu - 5 * sigma
xmax = mu + 5 * sigma
class TestedInterpolated(pm.Interpolated):
rv_op = interpolated
@classmethod
def dist(cls, **kwargs):
x_points = np.linspace(xmin, xmax, 100000)
pdf_points = st.norm.pdf(x_points, loc=mu, scale=sigma)
return super().dist(x_points=x_points, pdf_points=pdf_points, **kwargs)
def ref_pdf(value):
return np.where(
np.logical_and(value >= xmin, value <= xmax),
st.norm.logpdf(value, mu, sigma),
-np.inf * np.ones(value.shape),
)
check_logp(TestedInterpolated, R, {}, ref_pdf)
@pytest.mark.parametrize("transform", [pm.util.UNSET, None])
def test_interpolated_transform(self, transform):
# Issue: https://github.com/pymc-devs/pymc/issues/5048
x_points = np.linspace(0, 10, 10)
pdf_points = st.norm.pdf(x_points, loc=1, scale=1)
with pm.Model() as m:
x = pm.Interpolated("x", x_points, pdf_points, transform=transform)
if transform is pm.util.UNSET:
assert np.isfinite(m.compile_logp()({"x_interval__": -1.0}))
assert np.isfinite(m.compile_logp()({"x_interval__": 11.0}))
else:
assert not np.isfinite(m.compile_logp()({"x": -1.0}))
assert not np.isfinite(m.compile_logp()({"x": 11.0}))
def test_truncated_normal(self):
def scipy_logp(value, mu, sigma, lower, upper):
return st.truncnorm.logpdf(
value, (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma
)
check_logp(
pm.TruncatedNormal,
R,
{"mu": R, "sigma": Rplusbig, "lower": -Rplusbig, "upper": Rplusbig},
scipy_logp,
decimal=select_by_precision(float64=6, float32=1),
skip_paramdomain_outside_edge_test=True,
)
check_logp(
pm.TruncatedNormal,
R,
{"mu": R, "sigma": Rplusbig, "upper": Rplusbig},
ft.partial(scipy_logp, lower=-np.inf),
decimal=select_by_precision(float64=6, float32=1),
skip_paramdomain_outside_edge_test=True,
)
check_logp(
pm.TruncatedNormal,
R,
{"mu": R, "sigma": Rplusbig, "lower": -Rplusbig},
ft.partial(scipy_logp, upper=np.inf),
decimal=select_by_precision(float64=6, float32=1),
skip_paramdomain_outside_edge_test=True,
)
# This is a regression test for #6128: Check that having one out-of-bound value
# in an input array does not set all logp values to -inf
dist = pm.TruncatedNormal.dist(mu=1, sigma=2, lower=0, upper=3)
logp = pm.logp(dist, [-2.0, 1.0, 4.0]).eval()
assert np.isinf(logp[0])
assert np.isfinite(logp[1])
assert np.isinf(logp[2])
def test_get_tau_sigma(self):
# Fail on warnings
with warnings.catch_warnings():
warnings.simplefilter("error")
sigma = np.array(2)
npt.assert_almost_equal(get_tau_sigma(sigma=sigma), [1.0 / sigma**2, sigma])
tau = np.array(2)
npt.assert_almost_equal(get_tau_sigma(tau=tau), [tau, tau**-0.5])
tau, _ = get_tau_sigma(sigma=pt.constant(-2))
npt.assert_almost_equal(tau.eval(), -0.25)
_, sigma = get_tau_sigma(tau=pt.constant(-2))
npt.assert_almost_equal(sigma.eval(), -np.sqrt(1 / 2))
sigma = [1, 2]
npt.assert_almost_equal(
get_tau_sigma(sigma=sigma), [1.0 / np.array(sigma) ** 2, np.array(sigma)]
)
@pytest.mark.parametrize(
"value,mu,sigma,nu,logp",
[
(0.5, -50.000, 0.500, 0.500, -99.8068528),
(1.0, -1.000, 0.001, 0.001, -1992.5922447),
(2.0, 0.001, 1.000, 1.000, -1.6720416),
(5.0, 0.500, 2.500, 2.500, -2.4543644),