Skip to content

Commit e43c80c

Browse files
committed
Added unit test for adaptive random search.
1 parent ce892ef commit e43c80c

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#! usr/bin/env python3
2+
3+
import adaptive_random_search as ars
4+
5+
import unittest
6+
7+
class AdaptiveRandomSearchTests(unittest.TestCase):
8+
9+
def test_objective_function(self):
10+
#integer
11+
self.assertEqual(99**2, ars.objective_function([99]))
12+
#float
13+
self.assertEqual(0.1**2.0, ars.objective_function([0.1]))
14+
#vector
15+
self.assertEqual((1**2) + (2**2) + (3**2), ars.objective_function([1,2,3]))
16+
17+
def test_rand_in_bounds(self):
18+
x = ars.rand_in_bounds(0, 20)
19+
self.assertTrue(x >= 0)
20+
self.assertTrue(x < 20)
21+
22+
x = ars.rand_in_bounds(-20, -1)
23+
self.assertTrue(x >= -20)
24+
self.assertTrue(x < -1)
25+
26+
x = ars.rand_in_bounds(-10, 20)
27+
self.assertTrue(x >= -10)
28+
self.assertTrue(x < 20)
29+
30+
def test_random_vector(self):
31+
bounds, trials, size = [-3, 3], 300, 20
32+
minmax = [bounds for i in range(size)]
33+
34+
for i in range(trials):
35+
vector, total = ars.random_vector(minmax), 0.0
36+
self.assertEqual(size, len(vector))
37+
38+
for v in vector:
39+
self.assertTrue(v >= bounds[0])
40+
self.assertTrue(v < bounds[1])
41+
total += v
42+
43+
#TODO: test with total
44+
45+
def test_take_step(self):
46+
p = ars.take_step([[0, 100]], [50], 3.3)
47+
self.assertTrue(p[0] >= 50 - 3.3)
48+
self.assertTrue(p[0] <= 50 + 3.3)
49+
50+
p = ars.take_step([[0, 1]], [0], 3.3)
51+
self.assertTrue(p[0] >= 0)
52+
self.assertTrue(p[0] < 1)
53+
54+
def test_large_step_size(self):
55+
# Test using small factor
56+
s = ars.large_step_size(0, 1, 2, 3, 100)
57+
self.assertEqual(1*2, s)
58+
59+
# Test using large factor
60+
s = ars.large_step_size(100, 1, 2, 3, 100)
61+
self.assertEqual(1*3, s)
62+
63+
def test_take_steps(self):
64+
vector_content = 5
65+
for i in range(20):
66+
step1, step2 = ars.take_steps([[0,10]], {"vector":[vector_content]}, 1, 3)
67+
self.assertTrue(step1["vector"] is not None)
68+
self.assertTrue(step1["cost"] is not None)
69+
self.assertTrue(step1["vector"][0] >= vector_content - 1)
70+
self.assertTrue(step1["vector"][0] < vector_content + 1)
71+
72+
self.assertTrue(step2["vector"] is not None)
73+
self.assertTrue(step2["cost"] is not None)
74+
self.assertTrue(step2["vector"][0] >= vector_content - 3)
75+
self.assertTrue(step2["vector"][0] < vector_content + 3)
76+
77+
#TODO : Test search
78+
79+
if __name__ == "__main__":
80+
tests = unittest.TestLoader().loadTestsFromTestCase(AdaptiveRandomSearchTests)
81+
unittest.TextTestRunner(verbosity=2).run(tests)

0 commit comments

Comments
 (0)