-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_hillclimb.py
98 lines (78 loc) · 2.81 KB
/
test_hillclimb.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
import hillclimb
def objective_function(i):
return i
max_evaluations=500
def test_simple_hillclimb():
'''
test whether given a really simple move
operator that just increments the number given
we always end up with with largest number
we can get after the number of evaluations
we specify
'''
def move_operator(i):
yield i+1
def init_function():
return 1
num_evaluations,best_score,best=hillclimb.hillclimb(init_function,move_operator,objective_function,max_evaluations)
assert num_evaluations == max_evaluations
assert best == max_evaluations
assert best_score == max_evaluations
def test_peak_hillclimb():
'''
check we hit the peak value (and don't iterate more than we need to)
'''
def move_operator(i):
if i < 100:
yield i+1
def init_function():
return 1
num_evaluations,best_score,best=hillclimb.hillclimb(init_function,move_operator,objective_function,max_evaluations)
assert num_evaluations <= max_evaluations
assert num_evaluations == 100
assert best == 100
assert best_score == 100
def test_hillclimb_and_restart():
'''
see whether we restart on each number correctly
'''
def move_operator(i):
# even numbers only go up to 50
if i % 2 == 0 and i < 50:
yield i+2
elif i % 2 != 0 and i < 100: # odd numbers go higher
yield i+2
def init_function_gen():
yield 2 # start off on the even numbers then restart on odds
while True:
yield 3
init_gen=init_function_gen()
init_function=lambda: init_gen.next()
num_evaluations,best_score,best=hillclimb.hillclimb_and_restart(init_function,move_operator,objective_function,max_evaluations)
# should have used all iterations
assert num_evaluations == max_evaluations
# should have jumped onto odd numbers
assert best == 101
assert best_score == 101
def test_hillclimb_and_restart_getting_worse():
'''
see whether we restart on each number correctly
'''
def move_operator(i):
# even numbers only go up to 50
if i % 2 == 0 and i < 50:
yield i+2
elif i % 2 != 0 and i < 100: # odd numbers go higher
yield i+2
def init_function_gen():
yield 3 # start off on the odd numbers then restart on evens
while True:
yield 2
init_gen=init_function_gen()
init_function=lambda: init_gen.next()
num_evaluations,best_score,best=hillclimb.hillclimb_and_restart(init_function,move_operator,objective_function,max_evaluations)
# should have used all iterations
assert num_evaluations == max_evaluations
# should have retained score from odd numbers
assert best == 101
assert best_score == 101