Commit 3f34c18d authored by Grégoire GRZECZKOWICZ's avatar Grégoire GRZECZKOWICZ
Browse files

Simulated annealing with constant temperature

Accept solution with probability np.exp(-(best_val-val)/T)
parent 5b54bcd7
......@@ -35,7 +35,26 @@ def greedy(func, init, neighb, again):
i += 1
return best_val, best_sol
# TODO add a simulated-annealing template.
def simulated_annealing(func, init, neighb, again):
"""Iterative randomized simulated-annealing template."""
best_sol = init()
best_val = func(best_sol)
val,sol = best_val,best_sol
i = 1
T = 1
while again(i, best_val, best_sol):
sol = neighb(best_sol)
val = func(sol)
# Use >= and not >, so as to avoid random walk on plateus.
if val >= best_val:
best_val = val
best_sol = sol
elif np.random.random() < np.exp(-(best_val-val)/T):
best_val = val
best_sol = sol
i += 1
return best_val, best_sol
# TODO add a population-based stochastic heuristic template.
......@@ -32,7 +32,7 @@ if __name__=="__main__":
can.add_argument("-s", "--seed", metavar="VAL", default=None, type=int,
help="Random pseudo-generator seed (none for current epoch)")
solvers = ["num_greedy","bit_greedy"]
solvers = ["num_greedy","bit_greedy","num_simulated_annealing","bit_simulated_annealing"]
can.add_argument("-m", "--solver", metavar="NAME", choices=solvers, default="num_greedy",
help="Solver to use, among: "+", ".join(solvers))
......@@ -121,6 +121,38 @@ if __name__=="__main__":
)
sensors = bit.to_sensors(sol)
elif the.solver == "num_simulated_annealing":
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),
iters
)
sensors = num.to_sensors(sol)
elif the.solver == "bit_simulated_annealing":
val,sol = algo.simulated_annealing(
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
)
sensors = bit.to_sensors(sol)
# Fancy output.
print("\n{} : {}".format(val,sensors))
......
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