def take_steps(bounds, current, step_size, big_stepsize, instance): step, big_step = {}, {} step["vector"] = take_step(bounds, current["vector"], step_size) step["cost"], step["penalty"], step["penalty_tuple"] = main_checker(instance, step["vector"], ) big_step["vector"] = take_step(bounds, current["vector"], big_stepsize) big_step["cost"], big_step["penalty"], big_step["penalty_tuple"] = main_checker(instance, big_step["vector"]) return step, big_step
def sa_main(instance, time_limit, penalty_koef): start_time = time.time() Interventions = instance[INTERVENTIONS_STR] dim = len(Interventions) Deltas = [] intervention_names = list(Interventions.keys()) for i in range(dim): Deltas.append(max(Interventions[intervention_names[i]]['Delta'])) initialTemperature = 1000000 endTemperature = 0.0000001 # iterMax = 15000 state = [ random.randint(1, int(Interventions[intervention_names[i]][TMAX_STR])) for i in range(dim) ] penalties = [] currentEnergy, penal, penal_tup = main_checker(instance, state, penalty_koef) currentTemp = initialTemperature energy = [currentEnergy] best_energy = currentEnergy best_state = state best_penalty = penal iter = 0 while (time.time() - start_time) <= time_limit: stateCandidate = GenerateStateCandidate( state) # получаем состояние - кандидат candidateEnergy, penal, penal_tup = main_checker( instance, stateCandidate, penalty_koef) penalties.append(penal) if candidateEnergy < currentEnergy: currentEnergy = candidateEnergy state = stateCandidate if (candidateEnergy < best_energy) & (penal <= best_penalty): best_energy = candidateEnergy best_state = stateCandidate best_penalty = penal else: probability = GetTransitionProbability( candidateEnergy - currentEnergy, currentTemp) if MakeTransit(probability): currentEnergy = candidateEnergy state = stateCandidate if not (iter % 100): energy.append(best_energy) currentTemp = DecreaseTemperature(initialTemperature, iter) if currentTemp <= endTemperature: break iter += 1 print('Done SA. Best solution:', best_energy, 'penalty:', best_penalty) time_values = list(range(len(energy))) return best_state, best_energy, best_penalty, energy, time_values
def search(max_iter, bounds, init_factor, s_factor, l_factor, iter_mult, max_no_impr, intervention_names, dim, instance, initial): Interventions = instance[INTERVENTIONS_STR] step_size = (bounds[0][1] - bounds[0][0]) * init_factor current, count = {}, 0 current["vector"] = initial current["cost"], current["penalty"], current["penalty_tuple"] = main_checker(instance, current["vector"]) time = [1] values = [current["cost"]] for i in range(max_iter): big_stepsize = large_step_size(i, step_size, s_factor, l_factor, iter_mult) step, big_step = take_steps(bounds, current, step_size, big_stepsize, instance) if not (i % 20): time.append(time[-1]+1) values.append(current["cost"]) if (step["cost"] <= current["cost"] or big_step["cost"] <= current["cost"]) & \ (step["penalty"] <= current["penalty"] or big_step["penalty"] <= current["penalty"]): if big_step["cost"] <= step["cost"]: step_size, current = big_stepsize, big_step else: current = step count = 0 else: count += 1 if count >= max_no_impr: count, stepSize = 0, (step_size / s_factor) return current, time, values
def search(neighborhoods, max_no_improv, max_no_improv_ls, instance, ini_vector, time_limit, start_time, penalty_koef): best = {} best["vector"] = ini_vector best["cost"], best["penalty"], best["penalty_tuple"] = main_checker( instance, best["vector"], penalty_koef) iter_, count = 0, 0 info = {} info["function"] = [] info["penalty"] = [] info["time"] = [] while (time.time() - start_time) < time_limit: for neigh in neighborhoods: if (time.time() - start_time) >= time_limit: break candidate = {} candidate["vector"] = [v for v in best["vector"]] for _ in range(neigh): stochastic_two_opt(candidate["vector"]) candidate["cost"], candidate["penalty"], candidate["penalty_tuple"] = \ main_checker(instance, candidate["vector"], penalty_koef) candidate = local_search(candidate, max_no_improv_ls, neigh, instance, penalty_koef) iter_ += 1 if (candidate["cost"] < best["cost"]) & (candidate["penalty"] <= best["penalty"]): best, count = candidate, 0 break else: count += 1 info["function"].append(best["cost"]) info["penalty"].append(best["penalty"]) info["time"].append(iter_) return best, info
def local_search(best, max_no_improv, neighborhood_size, instance, penalty_koef): count = 0 while count < max_no_improv: candidate = {} candidate["vector"] = [v for v in best["vector"]] for _ in range(neighborhood_size): stochastic_two_opt(candidate["vector"]) candidate["cost"], candidate["penalty"], candidate["penalty_tuple"] = \ main_checker(instance, candidate["vector"], penalty_koef) if (candidate["cost"] < best["cost"]) & (candidate["penalty"] <= best["penalty"]): count, best = 0, candidate else: count += 1 return best
def main_bipop(instance, ini_val, ini_pen, initial, time_limit, penalty_koef): start_time = time.time() Interventions = instance[INTERVENTIONS_STR] dim = len(Interventions) Deltas = [] intervention_names = list(Interventions.keys()) for i in range(dim): Deltas.append(max(Interventions[intervention_names[i]][DELTA_STR])) seed = 0 rng = np.random.RandomState(0) bounds = np.array( [[1, int(Interventions[intervention_names[i]][TMAX_STR])] for i in range(dim)]) lower_bounds, upper_bounds = bounds[:, 0], bounds[:, 1] # mean = np.array(initial, dtype='float64') mean = (lower_bounds + rng.rand(1, dim) * (upper_bounds - lower_bounds))[0] # sigma = dim * 2 / 5 # 1/5 of the domain width sigma = (max(upper_bounds) - min(lower_bounds)) / 2 * 2 / 5 optimizer = CMA(mean=mean, sigma=sigma, bounds=bounds, seed=0) n_restarts = 0 # A small restart doesn't count in the n_restarts small_n_eval, large_n_eval = 0, 0 popsize0 = optimizer.population_size inc_popsize = 3 # best_value = np.inf best_value = ini_val best_solution = initial # best_penalty = 0 best_penalty = ini_pen current_value = [] current_penalty = [] iteration = 0 solutions = [] max_n_restart = 25 #poptype = "small" poptype = "large" while n_restarts < max_n_restart: solutions = [] for _ in range(optimizer.population_size): x = optimizer.ask() x = np.around(list(x)) value, penalty, penalty_tuple = main_checker( instance, list(x), penalty_koef) solutions.append((x, value)) iteration += 1 if value < best_value: best_value = value best_solution = x best_penalty = penalty if not (iteration % 150): current_value.append(best_value) current_penalty.append(best_penalty) optimizer.tell(solutions) if time.time() - start_time >= time_limit: n_restarts = max_n_restart break if optimizer.should_stop(): seed += 1 n_eval = optimizer.population_size * optimizer.generation * 2 if poptype == "small": small_n_eval += n_eval else: # poptype == "large" large_n_eval += n_eval if small_n_eval < large_n_eval: poptype = "small" popsize_multiplier = inc_popsize**n_restarts popsize = math.floor(popsize0 * popsize_multiplier**(rng.uniform()**2)) else: poptype = "large" n_restarts += 1 popsize = popsize0 * (inc_popsize**n_restarts) mean = (lower_bounds + rng.rand(1, dim) * (upper_bounds - lower_bounds))[0] optimizer = CMA( mean=mean, sigma=sigma, bounds=bounds, seed=seed, population_size=popsize, ) print('Done CMA-ES, Best_value:', best_value, 'Best_penalty:', best_penalty) ar_time = [i for i in range(1, len(current_value) + 1)] print(time.time() - start_time, 'seconds for CMA') return current_value, current_penalty, ar_time, best_value, best_penalty, best_solution, solutions
from function_checker import main_checker from json_reader import read_json penalty_koef = 300 instance_name = 'A_15' f = open('current_best/' + instance_name + ".txt", 'r') lines = [] solution = [] for line in f: lines.append(line.split()) solution.append(int(lines[-1][1])) instance = read_json(instance_name + '.json') value_best, value_penalty, value_pen_tup = main_checker( instance, solution, penalty_koef) print(value_best, value_penalty)
TMAX_STR = 'tmax' INTERVENTIONS_STR = 'Interventions' EXCLUSIONS_STR = 'Exclusions' T_STR = 'T' Exclusions = instance[EXCLUSIONS_STR] Time = instance[T_STR] Interventions = instance[INTERVENTIONS_STR] intervention_names = list(Interventions.keys()) dim = len(Interventions) initial = [ random.randint(1, int(Interventions[intervention_names[i]][TMAX_STR])) for i in range(dim) ] value, penalty, _ = main_checker(instance, initial) print('value1:', value, 'penalty1:', penalty) # ---------------------------------------------------------------------# L = [1 for _ in range(dim)] U = [ round(int(Interventions[intervention_names[i]][TMAX_STR])) for i in range(dim) ] gamma = round(Time // 5) I = [round((U[i] - L[i]) / gamma) for i in range(dim)] S = np.zeros((gamma, dim))