Commit 4e12907f authored by Julien Lin's avatar Julien Lin
Browse files

refactor

parent b212255e
......@@ -38,14 +38,16 @@ def greedy(func, init, neighb, again):
def simulated_annealing(func, init, neigh, temp, proba, rand, again):
"""Recuit simulé."""
best_sol = init()
best_sol, t = init()
best_val = func(best_sol)
cur_val, cur_sol = best_val,best_sol
k = 1
# t = 2000
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)):
t = temp(t)
if val > cur_val or rand() <= proba(abs(val - cur_val), t):
cur_sol = sol
cur_val = val
if val > best_val:
......
"""Wrappers that captures parameters of a function
and returns an operator with a given interface."""
import numpy as np
def func(cover, **kwargs):
"""Make an objective function from the given function.
An objective function takes a solution and returns a scalar."""
......@@ -33,3 +36,21 @@ def iter(iters, **kwargs):
return iters(i, val, sol, **kwargs)
return f
def temp(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
\ No newline at end of file
......@@ -44,6 +44,9 @@ def rand(dim, scale):
return np.random.random(dim) * scale
def init_with_t(t,**kwargs):
return rand(**kwargs), t
########################################################################
# Neighborhood
########################################################################
......
......@@ -189,24 +189,32 @@ if __name__ == "__main__":
)
sensors = bit.to_sensors(sol)
elif the.solver == "num_sim_anneal":
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.init_with_t,
t=2000,
dim=d * the.nb_sensors,
scale=the.domain_width,
),
make.neig(
num.neighb_square,
scale=the.variation_scale,
domain_width=the.domain_width,
),
make.temp(0.99),
make.proba(),
make.rand(),
iters,
)
sensors = num.to_sensors(sol)
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
elif the.solver == "bit_sim_anneal":
val, sol = algo.simulated_annealing(
make.func(
......@@ -225,9 +233,9 @@ if __name__ == "__main__":
scale=the.variation_scale,
domain_width=the.domain_width,
),
temp_generator(0.99),
proba(),
rand(),
make.temp(0.99),
make.proba(),
make.rand(),
iters,
)
sensors = num.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