/
local.py
325 lines (260 loc) · 10.8 KB
/
local.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
# coding=utf-8
from simpleai.search.utils import BoundedPriorityQueue, InverseTransformSampler
from simpleai.search.models import SearchNodeValueOrdered
import math
import random
def _all_expander(fringe, iteration, viewer):
'''
Expander that expands all nodes on the fringe.
'''
expanded_neighbors = [node.expand(local_search=True)
for node in fringe]
if viewer:
viewer.event('expanded', list(fringe), expanded_neighbors)
map(fringe.extend, expanded_neighbors)
def beam(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state.
'''
return _local_search(problem,
_all_expander,
iterations_limit=iterations_limit,
fringe_size=beam_size,
random_initial_states=True,
stop_when_no_better=iterations_limit==0,
viewer=viewer)
def _first_expander(fringe, iteration, viewer):
'''
Expander that expands only the first node on the fringe.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [neighbors])
fringe.extend(neighbors)
def beam_best_first(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search best first.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_first_expander,
iterations_limit=iterations_limit,
fringe_size=beam_size,
random_initial_states=True,
stop_when_no_better=iterations_limit==0,
viewer=viewer)
def hill_climbing(problem, iterations_limit=0, viewer=None):
'''
Hill climbing search.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_first_expander,
iterations_limit=iterations_limit,
fringe_size=1,
stop_when_no_better=True,
viewer=viewer)
def _random_best_expander(fringe, iteration, viewer):
'''
Expander that expands one randomly chosen nodes on the fringe that
is better than the current (first) node.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [neighbors])
betters = [n for n in neighbors
if n.value > current.value]
if betters:
chosen = random.choice(betters)
if viewer:
viewer.event('chosen_node', chosen)
fringe.append(chosen)
def hill_climbing_stochastic(problem, iterations_limit=0, viewer=None):
'''
Stochastic hill climbing.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_random_best_expander,
iterations_limit=iterations_limit,
fringe_size=1,
stop_when_no_better=iterations_limit==0,
viewer=viewer)
def hill_climbing_random_restarts(problem, restarts_limit, iterations_limit=0, viewer=None):
'''
Hill climbing with random restarts.
restarts_limit specifies the number of times hill_climbing will be runned.
If iterations_limit is specified, each hill_climbing will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state.
'''
restarts = 0
best = None
while restarts < restarts_limit:
new = _local_search(problem,
_first_expander,
iterations_limit=iterations_limit,
fringe_size=1,
random_initial_states=True,
stop_when_no_better=True,
viewer=viewer)
if not best or best.value < new.value:
best = new
restarts += 1
if viewer:
viewer.event('no_more_runs', best, 'returned after %i runs' % restarts_limit)
return best
# Math literally copied from aima-python
def _exp_schedule(iteration, k=20, lam=0.005, limit=100):
'''
Possible scheduler for simulated_annealing, based on the aima example.
'''
return k * math.exp(-lam * iteration)
def _create_simulated_annealing_expander(schedule):
'''
Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time.
'''
def _expander(fringe, iteration, viewer):
T = schedule(iteration)
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [neighbors])
if neighbors:
succ = random.choice(neighbors)
delta_e = succ.value - current.value
if delta_e > 0 or random.random() < math.exp(delta_e / T):
fringe.pop()
fringe.append(succ)
if viewer:
viewer.event('chosen_node', succ)
return _expander
def simulated_annealing(problem, schedule=_exp_schedule, iterations_limit=0, viewer=None):
'''
Simulated annealing.
schedule is the scheduling function that decides the chance to choose worst
nodes depending on the time.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_create_simulated_annealing_expander(schedule),
iterations_limit=iterations_limit,
fringe_size=1,
stop_when_no_better=iterations_limit==0,
viewer=viewer)
def _create_genetic_expander(problem, mutation_chance):
'''
Creates an expander that expands the bests nodes of the population,
crossing over them.
'''
def _expander(fringe, iteration, viewer):
fitness = [x.value for x in fringe]
sampler = InverseTransformSampler(fitness, fringe)
new_generation = []
expanded_nodes = []
expanded_neighbors = []
for _ in fringe:
node1 = sampler.sample()
node2 = sampler.sample()
child = problem.crossover(node1.state, node2.state)
action = 'crossover'
if random.random() < mutation_chance:
# Noooouuu! she is... he is... *IT* is a mutant!
child = problem.mutate(child)
action += '+mutation'
child_node = SearchNodeValueOrdered(state=child, problem=problem, action=action)
new_generation.append(child_node)
expanded_nodes.append(node1)
expanded_neighbors.append([child_node])
expanded_nodes.append(node2)
expanded_neighbors.append([child_node])
if viewer:
viewer.event('expanded', expanded_nodes, expanded_neighbors)
fringe.clear()
for node in new_generation:
fringe.append(node)
return _expander
def genetic(problem, population_size=100, mutation_chance=0.1,
iterations_limit=0, viewer=None):
'''
Genetic search.
population_size specifies the size of the population (ORLY).
mutation_chance specifies the probability of a mutation on a child,
varying from 0 to 1.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.generate_random_state, SearchProblem.crossover,
SearchProblem.mutate and SearchProblem.value.
'''
return _local_search(problem,
_create_genetic_expander(problem, mutation_chance),
iterations_limit=iterations_limit,
fringe_size=population_size,
random_initial_states=True,
stop_when_no_better=iterations_limit==0,
viewer=viewer)
def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1,
random_initial_states=False, stop_when_no_better=True,
viewer=None):
'''
Basic algorithm for all local search algorithms.
'''
if viewer:
viewer.event('started')
fringe = BoundedPriorityQueue(fringe_size)
if random_initial_states:
for _ in range(fringe_size):
s = problem.generate_random_state()
fringe.append(SearchNodeValueOrdered(state=s, problem=problem))
else:
fringe.append(SearchNodeValueOrdered(state=problem.initial_state,
problem=problem))
finish_reason = ''
iteration = 0
run = True
best = None
while run:
if viewer:
viewer.event('new_iteration', list(fringe))
old_best = fringe[0]
fringe_expander(fringe, iteration, viewer)
best = fringe[0]
iteration += 1
if iterations_limit and iteration >= iterations_limit:
run = False
finish_reason = 'reaching iteration limit'
elif old_best.value >= best.value and stop_when_no_better:
run = False
finish_reason = 'not being able to improve solution'
if viewer:
viewer.event('finished', fringe, best, 'returned after %s' % finish_reason)
return best