From 991b7f4175f0e0908d1c04cbbe0491b7a44d46d1 Mon Sep 17 00:00:00 2001 From: Maximilian Schlosser Date: Tue, 11 Jul 2017 22:25:56 +0200 Subject: [PATCH] simulated annealing --- src/Generator/generator.py | 15 +++++++---- src/SchedulingAlgorithms/simanneal.py | 36 +++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/Generator/generator.py b/src/Generator/generator.py index 9642bdd..6920d4b 100644 --- a/src/Generator/generator.py +++ b/src/Generator/generator.py @@ -159,16 +159,21 @@ def generate(old_solution, steps, percent=1): Generate a new solution from an existing solution with a specified number of max steps. """ + import sys + print("Max steps: " + str(steps)) + sys.stdout.write("Start generation... ") solution = old_solution[:] - percent = 1 option = pull_fwd #do at least one pull - while(steps > 0): + for i in range(0, steps): solution = option(solution) if(option == accept): break - steps -= 1 - select = random.randrange(0,100) - option = pull_fwd if (select - percent) > 0 else accept + select = random.randrange(0,1000) + option = pull_fwd #if (select - percent) > 0 else accept + if ((i * 100) % steps == 0): + sys.stdout.write(str(i*100/steps) + "%... ") + sys.stdout.flush() + sys.stdout.write("\n") accept(solution) return solution diff --git a/src/SchedulingAlgorithms/simanneal.py b/src/SchedulingAlgorithms/simanneal.py index e69de29..082b64f 100644 --- a/src/SchedulingAlgorithms/simanneal.py +++ b/src/SchedulingAlgorithms/simanneal.py @@ -0,0 +1,36 @@ +from Generator.generator import generate +from Generator.generator import init as gen_init +from SchedulingAlgorithms.enumerate import enumerate as enum +from math import e +from random import random + +def anneal(max_temp = 1000, max_steps = 1000): + global problem + gen_init(problem) + temp = max_temp + initial = enum(problem) + current = generate(initial, problem.machines * problem.jobs * 10) + del initial + for step in range(0, max_steps): + new = generate(current, problem.machines * problem.jobs) + new_end = rate(new) + curr_end = rate(current) + p = 1 / ( 1 + (e ** ((curr_end - new_end)/temp))) + if (new_end < curr_end) or (p < random()): + current = new + print("Old: " + str(curr_end) + " New: " + str(new_end)) + temp = ((max_temp-1)/(max_steps**2))*(step-max_steps)**2+1 + print("Iteration: "+ str(step) + " Temperature: " + str(temp)) + return current + +def rate(solution): + global problem + last_tasks = [] + for i in range(0,problem.jobs): + last_tasks += [next(( x for x in solution[::-1] if x[1][0] == i), [])] + end_times = [ problem[x[1]][0] + x[0] for x in last_tasks] + return max(end_times) + +def init(in_problem): + global problem + problem = in_problem