-
Notifications
You must be signed in to change notification settings - Fork 54
/
distributions_test.py
461 lines (383 loc) · 15.1 KB
/
distributions_test.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
import logging
import numpy as np
import pytest
from scipy.stats import beta, halfnorm, kstest, rayleigh
from exoplanet.compat import USING_PYMC3, pm
from exoplanet.distributions.distributions import (
angle,
impact_parameter,
quad_limb_dark,
unit_disk,
)
from exoplanet.distributions.eccentricity import kipping13, vaneylen19
class _Base:
random_seed = 20160911
def _sample(self, **kwargs):
logger = logging.getLogger("pymc3" if USING_PYMC3 else "pymc")
logger.propagate = False
logger.setLevel(logging.ERROR)
kwargs["draws"] = kwargs.get("draws", 1000)
kwargs["progressbar"] = kwargs.get("progressbar", False)
kwargs["random_seed"] = kwargs.get("random_seed", self.random_seed)
if USING_PYMC3:
kwargs["return_inferencedata"] = True
kwargs["compute_convergence_checks"] = False
return pm.sample(**kwargs)
def _model(self, **kwargs):
np.random.seed(self.random_seed)
return pm.Model(**kwargs)
class TestEccentricity(_Base):
random_seed = 19910626
def test_kipping13(self):
with self._model() as model:
kipping13("ecc", fixed=False, shape=(5, 2))
if USING_PYMC3:
assert "ecc_alpha" in model.named_vars
assert "ecc_beta" in model.named_vars
else:
assert "ecc::alpha" in model.named_vars
assert "ecc::beta" in model.named_vars
trace = self._sample()
ecc = trace.posterior["ecc"].values
assert np.all((0 <= ecc) & (ecc <= 1))
def test_kipping13_all(self):
with self._model():
kipping13("ecc", fixed=True, shape=2)
trace = self._sample()
ecc = trace.posterior["ecc"].values.flatten()
assert np.all((0 <= ecc) & (ecc <= 1))
cdf = lambda x: beta.cdf(x, 1.12, 3.09) # NOQA
s, p = kstest(ecc, cdf)
assert s < 0.05
def test_kipping13_long(self):
with self._model():
kipping13("ecc", fixed=True, long=True, shape=3)
trace = self._sample()
ecc = trace.posterior["ecc"].values.flatten()
assert np.all((0 <= ecc) & (ecc <= 1))
cdf = lambda x: beta.cdf(x, 1.12, 3.09) # NOQA
s, p = kstest(ecc, cdf)
assert s < 0.05
def test_kipping13_short(self):
with self._model():
kipping13("ecc", fixed=True, long=False, shape=4)
trace = self._sample()
ecc = trace.posterior["ecc"].values.flatten()
assert np.all((0 <= ecc) & (ecc <= 1))
cdf = lambda x: beta.cdf(x, 0.697, 3.27) # NOQA
s, p = kstest(ecc, cdf)
assert s < 0.05
@pytest.mark.parametrize(
"kwargs",
[dict(lower=0.1), dict(upper=0.5), dict(lower=0.3, upper=0.4)],
)
def test_kipping13_bounds(self, kwargs):
with self._model():
kipping13("ecc", **kwargs)
trace = self._sample()
ecc = trace.posterior["ecc"].values.flatten()
assert np.all(
(kwargs.get("lower", 0.0) <= ecc)
& (ecc <= kwargs.get("upper", 1.0))
)
@pytest.mark.parametrize(
"kwargs", [dict(lower=None, upper=None), dict(lower=0.2, upper=0.4)]
)
def test_kipping13_observed(self, kwargs):
has_bounds = (
kwargs.get("lower") is not None or kwargs.get("upper") is not None
)
with self._model() as model:
# We want to make sure to seed h and k inside the ecc_prior bounds
_lower = kwargs.get("lower", 0.0) or 0.0
_upper = kwargs.get("upper", 1.0) or 1.0
init_ecc = 0.5 * (_lower + _upper)
# Argument of periastron arbitrary to derive consistent h and k
init_h = np.sqrt(init_ecc) * np.cos(np.pi / 4)
init_k = np.sqrt(init_ecc) * np.sin(np.pi / 4)
secosw, sesinw = unit_disk(
"secosw", "sesinw", initval=[init_h, init_k]
)
ecc = pm.Deterministic("ecc", secosw**2 + sesinw**2)
if has_bounds and USING_PYMC3:
with pytest.raises(
NotImplementedError,
match="Passing an 'observed' eccentricity to a bounded prior is not"
" implemented with PyMC <= 3.",
):
ecc_prior = kipping13(
"ecc_prior", shape=2, observed=ecc, **kwargs
)
return
ecc_prior = kipping13("ecc_prior", shape=2, observed=ecc, **kwargs)
# Is the prior added to the model as a potential?
assert "ecc_prior" in model.named_vars
assert ecc_prior in model.potentials
# Is the prior taken into account when sampling the "posterior"?
idata = self._sample()
ecc_samples = idata.posterior["ecc"].values.flatten()
if not has_bounds:
cdf = lambda x: beta.cdf(x, 1.12, 3.09) # NOQA
s, p = kstest(ecc_samples, cdf)
assert s < 0.05
else:
assert np.all(
(kwargs.get("lower", 0.0) <= ecc_samples)
& (ecc_samples <= kwargs.get("upper", 1.0))
)
@pytest.mark.parametrize("kwargs", [dict(fixed=False), dict(multi=True)])
def test_vaneylen19(self, kwargs):
with self._model() as model:
vaneylen19("ecc", shape=(5, 2), **kwargs)
if not kwargs.get("fixed", True):
if USING_PYMC3:
assert "ecc_sigma_gauss" in model.named_vars
assert "ecc_sigma_rayleigh" in model.named_vars
assert "ecc_frac" in model.named_vars
else:
assert "ecc::sigma_gauss" in model.named_vars
assert "ecc::sigma_rayleigh" in model.named_vars
assert "ecc::frac" in model.named_vars
trace = self._sample()
ecc = trace.posterior["ecc"].values
assert np.all((0 <= ecc) & (ecc <= 1))
def test_vaneylen19_single(self):
with self._model():
vaneylen19("ecc", fixed=True, multi=False, shape=2)
trace = self._sample()
ecc = trace.posterior["ecc"].values.flatten()
assert np.all((0 <= ecc) & (ecc <= 1))
f = 0.76
cdf = lambda x: ( # NOQA
(1 - f) * halfnorm.cdf(x, scale=0.049)
+ f * rayleigh.cdf(x, scale=0.26)
)
s, p = kstest(ecc, cdf)
assert s < 0.05
def test_vaneylen19_multi(self):
with self._model():
vaneylen19("ecc", fixed=True, multi=True, shape=3)
trace = self._sample()
ecc = trace.posterior["ecc"].values.flatten()
assert np.all((0 <= ecc) & (ecc <= 1))
f = 0.08
cdf = lambda x: ( # NOQA
(1 - f) * halfnorm.cdf(x, scale=0.049)
+ f * rayleigh.cdf(x, scale=0.26)
)
s, p = kstest(ecc, cdf)
assert s < 0.05
@pytest.mark.parametrize(
"kwargs",
[dict(lower=0.1), dict(upper=0.5), dict(lower=0.3, upper=0.4)],
)
def test_vaneylen19_bounds(self, kwargs):
with self._model():
vaneylen19("ecc", **kwargs)
trace = self._sample()
ecc = trace.posterior["ecc"].values.flatten()
assert np.all(
(kwargs.get("lower", 0.0) <= ecc)
& (ecc <= kwargs.get("upper", 1.0))
)
@pytest.mark.parametrize(
"kwargs", [dict(lower=None, upper=None), dict(lower=0.2, upper=0.4)]
)
def test_vaneylen19_observed(self, kwargs):
with self._model() as model:
# We want to make sure to seed h and k inside the ecc_prior bounds
_lower = kwargs.get("lower", 0.0) or 0.0
_upper = kwargs.get("upper", 1.0) or 1.0
init_ecc = 0.5 * (_lower + _upper)
# Argument of periastron arbitrary to derive consistent h and k
init_h = np.sqrt(init_ecc) * np.cos(np.pi / 4)
init_k = np.sqrt(init_ecc) * np.sin(np.pi / 4)
print(init_h, init_k)
secosw, sesinw = unit_disk(
"secosw", "sesinw", initval=[init_h, init_k]
)
if USING_PYMC3:
ecc_prior = vaneylen19(
"ecc",
fixed=True,
multi=False,
observed=secosw**2 + sesinw**2,
**kwargs,
)
else:
ecc = pm.Deterministic("ecc", secosw**2 + sesinw**2)
ecc_prior = vaneylen19(
"ecc_prior",
fixed=True,
multi=False,
observed=ecc,
**kwargs,
)
if not USING_PYMC3:
# Is the prior added to the model as a potential?
assert "ecc_prior" in model.named_vars
assert ecc_prior in model.potentials
trace = self._sample()
ecc_samples = trace.posterior["ecc"].values.flatten()
if kwargs.get("lower") is None and kwargs.get("upper") is None:
assert np.all((0 <= ecc_samples) & (ecc_samples <= 1))
f = 0.76
cdf = lambda x: ( # NOQA
(1 - f) * halfnorm.cdf(x, scale=0.049)
+ f * rayleigh.cdf(x, scale=0.26)
)
s, p = kstest(ecc_samples, cdf)
assert s < 0.05
else:
assert np.all(
(kwargs.get("lower", 0.0) <= ecc_samples)
& (ecc_samples <= kwargs.get("upper", 1.0))
)
class TestUnitDisk(_Base):
random_seed = 19930609
def test_unit_disk(self):
with self._model():
h, k = unit_disk("h", "k")
pm.Deterministic("ecc", h**2 + k**2)
trace = self._sample()
h_samples = trace.posterior["h"].values.flatten()
k_samples = trace.posterior["k"].values.flatten()
ecc_samples = trace.posterior["ecc"].values.flatten()
# Check h and k in expected intervals
assert np.all(h_samples < 1.0)
assert np.all(h_samples > -1.0)
assert np.all(k_samples < 1.0)
assert np.all(k_samples > -1.0)
# Check radius (eccentricity) is physical
assert np.all(ecc_samples >= 0.0)
assert np.all(ecc_samples < 1.0)
# Check radius (eccentricity) is uniform
cdf = lambda x: np.clip(x, 0, 1) # NOQA
s, p = kstest(ecc_samples, cdf)
assert s < 0.05
@pytest.mark.parametrize(
"shape",
[2, (1, 3), (4, 5)],
)
def test_unit_disk_shape(self, shape):
shape_as_tuple = (shape,) if isinstance(shape, int) else shape
with self._model():
h, k = unit_disk("h", "k", shape=shape)
if USING_PYMC3:
assert h.tag.test_value.shape == shape_as_tuple
assert k.tag.test_value.shape == h.tag.test_value.shape
else:
assert h.type.shape == shape_as_tuple
assert k.type.shape == h.type.shape
@pytest.mark.parametrize(
"shape",
[3, (4, 1), (4, 5)],
)
def test_unit_disk_initval(self, shape):
shape_as_tuple = (shape,) if isinstance(shape, int) else shape
with self._model():
h, k = unit_disk(
"h", "k", shape=shape, initval=np.zeros((2,) + shape_as_tuple)
)
if USING_PYMC3:
assert h.tag.test_value.shape == shape_as_tuple
assert k.tag.test_value.shape == h.tag.test_value.shape
else:
assert h.type.shape == shape_as_tuple
assert k.type.shape == h.type.shape
class TestAngle(_Base):
random_seed = 19900101
def test_angle(self):
with self._model():
angle("theta")
trace = self._sample()
theta_samples = trace.posterior["theta"].values.flatten()
# Check h and k in expected intervals
assert np.all(np.abs(theta_samples) < np.pi)
# Check theta is uniform
cdf = lambda x: np.clip( # NOQA
(x + np.pi) / (2 * np.pi), -np.pi, np.pi
)
s, p = kstest(theta_samples, cdf)
assert s < 0.05
@pytest.mark.parametrize(
"shape",
[2, (1, 3), (4, 5)],
)
def test_angle_shape(self, shape):
shape_as_tuple = (shape,) if isinstance(shape, int) else shape
with self._model():
theta = angle("theta", shape=shape)
if USING_PYMC3:
assert theta.tag.test_value.shape == shape_as_tuple
else:
assert theta.type.shape == shape_as_tuple
@pytest.mark.parametrize(
"shape",
[3, (4, 1), (4, 5)],
)
def test_angle_initval(self, shape):
shape_as_tuple = (shape,) if isinstance(shape, int) else shape
with self._model():
theta = angle("theta", shape=shape, initval=np.zeros(shape))
if USING_PYMC3:
assert theta.tag.test_value.shape == shape_as_tuple
else:
assert theta.type.shape == shape_as_tuple
class TestPhysical(_Base):
random_seed = 19860925
def test_quad_limb_dark(self):
with self._model():
quad_limb_dark("u")
trace = self._sample()
u1 = trace.posterior["u"].values[..., 0].flatten()
u2 = trace.posterior["u"].values[..., 1].flatten()
# Make sure that the physical constraints are satisfied
assert np.all(u1 + u2 < 1)
assert np.all(u1 > 0)
assert np.all(u1 + 2 * u2 > 0)
# Make sure that the qs are uniform
q1 = (u1 + u2) ** 2
q2 = 0.5 * u1 / (u1 + u2)
cdf = lambda x: np.clip(x, 0, 1) # NOQA
for q in (q1, q2):
s, p = kstest(q, cdf)
assert s < 0.05
def test_impact(self):
lower = 0.1
upper = 1.0
shape = (5, 2)
with self._model():
r = pm.Uniform("r", lower=lower, upper=upper, shape=shape)
impact_parameter("b", r, shape=shape)
trace = self._sample()
u = trace.posterior["r"].values
u = np.reshape(u, u.shape[:2] + (-1,))
cdf = lambda x: np.clip((x - lower) / (upper - lower), 0, 1) # NOQA
for i in range(u.shape[-1]):
s, p = kstest(u[..., i].flatten(), cdf)
assert s < 0.05
assert np.all(
trace.posterior["b"].values <= 1 + trace.posterior["r"].values
)
@pytest.mark.skipif(
USING_PYMC3, reason="Automatic shape inference doesn't work in PyMC3"
)
def test_impact_shape_inference(self):
lower = 0.1
upper = 1.0
shape = (5, 2)
with self._model():
r = pm.Uniform("r", lower=lower, upper=upper, shape=shape)
impact_parameter("b", r)
trace = self._sample()
assert trace.posterior["b"].values.shape[-2:] == shape
u = trace.posterior["r"].values
u = np.reshape(u, u.shape[:2] + (-1,))
cdf = lambda x: np.clip((x - lower) / (upper - lower), 0, 1) # NOQA
for i in range(u.shape[-1]):
s, p = kstest(u[..., i].flatten(), cdf)
assert s < 0.05
assert np.all(
trace.posterior["b"].values <= 1 + trace.posterior["r"].values
)