-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathtest_normal.py
49 lines (40 loc) · 1.75 KB
/
test_normal.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
from math import ceil
import stan
def test_normal_build():
"""Build (compile) a simple model."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
posterior = stan.build(program_code)
assert posterior is not None
def test_normal_sample():
"""Sample from normal distribution."""
program_code = "parameters {real y;} model {y ~ normal(0, 0.0001);}"
posterior = stan.build(program_code)
assert posterior is not None
fit = posterior.sample()
offset = len(fit.sample_and_sampler_param_names)
assert fit._draws.shape == (offset + 1, 1000, 4) # 4 chains, n samples, 1 param
df = fit.to_frame()
assert (df["y"] == fit._draws[offset, :, :].ravel()).all()
assert len(df["y"]) == 4000
assert -0.01 < df["y"].mean() < 0.01
assert -0.01 < df["y"].std() < 0.01
def test_normal_sample_chains():
"""Sample from normal distribution with more than one chain."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
posterior = stan.build(program_code)
assert posterior is not None
fit = posterior.sample(num_chains=3)
offset = len(fit.sample_and_sampler_param_names)
assert fit._draws.shape == (offset + 1, 1000, 3) # 1 param, n samples, 3 chains
df = fit.to_frame()
assert len(df["y"]) == 3000
assert -5 < df["y"].mean() < 5
def test_normal_sample_args():
"""Sample from normal distribution with build arguments."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
posterior = stan.build(program_code, random_seed=1)
assert posterior is not None
fit = posterior.sample(num_samples=350, num_warmup=350, num_thin=3, save_warmup=True)
df = fit.to_frame()
assert len(df["y"]) == ceil(350 / 3) * 2 * 4
assert -5 < df["y"].mean() < 5