Commit a65632cf authored by Julien Lin's avatar Julien Lin
Browse files

add simulated annealing

parent b88a83ad
########################################################################
# Algorithms
########################################################################
import numpy as np
def random(func, init, again):
"""Iterative random search template."""
......@@ -37,5 +36,24 @@ def greedy(func, init, neighb, again):
# TODO add a simulated-annealing template.
def simulated_annealing(func, init, neigh, temp, proba, rand, again):
"""Recuit simulé."""
best_sol = init()
best_val = func(best_sol)
cur_val, cur_sol = best_val,best_sol
k = 1
while again(k, best_val, best_sol):
sol = neigh(best_sol)
val = func(sol)
if val > cur_val or rand() <= proba(val - cur_val, temp(k)):
cur_sol = sol
cur_val = val
if val > best_val:
best_sol = cur_sol
best_val = cur_val
k += 1
return best_val, best_sol
# TODO add a population-based stochastic heuristic template.
......@@ -106,18 +106,50 @@ if __name__=="__main__":
sensors = num.to_sensors(sol)
elif the.solver == "bit_greedy":
val,sol = algo.greedy(
make.func(bit.cover_sum,
domain_width = the.domain_width,
sensor_range = the.sensor_range,
dim = d * the.nb_sensors),
make.init(bit.rand,
domain_width = the.domain_width,
nb_sensors = the.nb_sensors),
make.neig(bit.neighb_square,
scale = the.variation_scale,
domain_width = the.domain_width),
iters
elif the.solver == "num_sim_anneal":
def temp_generator(lamda):
def f(T):
return lamda * T
return f
def proba():
def f(delta_energy, temp):
return np.exp(-delta_energy / temp)
return f
def rand():
def f():
return np.random.rand()
return f
val, sol = algo.simulated_annealing(
make.func(
num.cover_sum,
domain_width=the.domain_width,
sensor_range=the.sensor_range,
dim=d * the.nb_sensors,
),
make.init(
num.rand,
dim=d * the.nb_sensors,
scale=the.domain_width,
),
make.neig(
num.neighb_square,
scale=the.variation_scale,
domain_width=the.domain_width,
),
temp_generator(0.99),
proba(),
rand(),
iters,
)
sensors = num.to_sensors(sol)
)
sensors = bit.to_sensors(sol)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment