-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathtest_utilities.py
110 lines (83 loc) · 2.81 KB
/
test_utilities.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
"""
Tests for util/random.py
Functions
---------
probvec
sample_without_replacement
"""
import numbers
import numpy as np
from numpy.testing import (assert_array_equal, assert_allclose, assert_raises,
assert_)
from numba import njit
from quantecon.random import probvec, sample_without_replacement, draw
# probvec #
class TestProbvec:
def setup_method(self):
self.m, self.k = 2, 3 # m vectors of dimension k
seed = 1234
self.out_parallel = probvec(self.m, self.k, random_state=seed)
self.out_cpu = \
probvec(self.m, self.k, random_state=seed, parallel=False)
def test_shape(self):
for out in [self.out_parallel, self.out_cpu]:
assert_(out.shape == (self.m, self.k))
def test_parallel_cpu(self):
assert_array_equal(self.out_parallel, self.out_cpu)
# sample_without_replacement #
def test_sample_without_replacement_shape():
assert_array_equal(sample_without_replacement(2, 0).shape, (0,))
n, k, m = 5, 3, 4
assert_array_equal(
sample_without_replacement(n, k).shape,
(k,)
)
assert_array_equal(
sample_without_replacement(n, k, num_trials=m).shape,
(m, k)
)
def test_sample_without_replacement_uniqueness():
n = 10
a = sample_without_replacement(n, n)
b = np.unique(a)
assert_(len(b) == n)
def test_sample_without_replacement_value_error():
# n <= 0
assert_raises(ValueError, sample_without_replacement, 0, 2)
assert_raises(ValueError, sample_without_replacement, -1, -1)
# k > n
assert_raises(ValueError, sample_without_replacement, 2, 3)
# draw #
@njit
def draw_jitted(cdf, size=None):
return draw(cdf, size)
class TestDraw:
def setup_method(self):
self.pmf = np.array([0.4, 0.1, 0.5])
self.cdf = np.cumsum(self.pmf)
self.n = len(self.pmf)
self.draw_funcs = [draw, draw_jitted]
def test_return_types(self):
for func in self.draw_funcs:
out = func(self.cdf)
assert_(isinstance(out, numbers.Integral))
size = 10
for func in self.draw_funcs:
out = func(self.cdf, size)
assert_(out.shape == (size,))
def test_return_values(self):
for func in self.draw_funcs:
out = func(self.cdf)
assert_(out in range(self.n))
size = 10
for func in self.draw_funcs:
out = func(self.cdf, size)
assert_(np.isin(out, range(self.n)).all())
def test_lln(self):
size = 1000000
for func in self.draw_funcs:
out = func(self.cdf, size)
hist, bin_edges = np.histogram(out, bins=self.n, density=True)
pmf_computed = hist * np.diff(bin_edges)
atol = 1e-2
assert_allclose(pmf_computed, self.pmf, atol=atol)