Commits

remusao committed f82aec5

adapt code to use with pypy

  • Participants
  • Parent commits c4e4d05

Comments (0)

Files changed (5)

 from simulated_annealing import SimulatedAnnealing
 from optimisation_composants import *
 
+import numpy as np
 
 def main():
     sa = SimulatedAnnealing()
-    sa.t_init = 1000
+    sa.t_init = 15
     solution = sa.run(init_fun, cost_fun, mod_fun, stop_fun)
     print(solution)
 
 #! /usr/bin/python
 
-from __future__ import print_function, absolute_import, division
+from __future__ import print_function, absolute_import
 from genetic_algorithm import GeneticAlgorithm
-from optimisation_composants import cost_fun, stop_fun
+
+from optimisation_composants import cost_fun
 
 def main():
 
         # Set options
         ga.begin_range = 0
         ga.end_range = 25
-        ga.mutation_rate = 0.3
-        ga.selection_amount = 5
+        ga.mutation_rate = 0.0
+        ga.selection_amount = 15
+        ga.pop_size = 1000
 
         # Find solution
-        epoc, score, best = ga.run(cost_fun, stop_fun)
+        epoc, score, best = ga.run(cost_fun, lambda e: e == 200)
 
         # Print solution
         print(epoc)

File src/genetic_algorithm.py

 
 from operator import itemgetter
 from itertools import chain
-import numpy as np
-import numpy.random as rnd
+import random
 
+def argsort(seq):
+    return sorted(xrange(len(seq)), key=seq.__getitem__)
 
 # DNA = tuple(code, score)
 
 
 
 def newRandom(dna_size, end):
-    return rnd.permutation(end)
+    new = range(end)
+    random.shuffle(new)
+    return new
 
 
 def newCrossover(parents):
-    shape = parents[0].shape
-    new = np.zeros(shape)
-    indices = map(np.argsort, parents)
-    for i in range(0, shape[0]):
-        index = rnd.randint(0, len(parents))
+    size = len(parents[0])
+    new = [0] * size
+    indices = map(argsort, parents)
+    for i in range(0, size):
+        index = random.randint(0, len(parents) - 1)
         new[i] = parents[index][indices[index][i]]
     return new, 0
 
 
 def mutate(dna, rate, end):
     dna, score = dna
-    for i in range(0, dna.shape[0]):
-        if rnd.random() <= rate:
-            a, b = rnd.choice(end, 2)
+    for i in range(0, len(dna)):
+        if random.random() <= rate:
+            a, b = random.sample(xrange(end), 2)
             dna[a], dna[b] = dna[b], dna[a]
     return dna, score
 
         # Init defaults options
         self.pop_size = 1000
         self.selection_amount = 100
-        self.max_epoc = 10000
+        self.max_epoc = 100000
         self.mutation_rate = 0.5
         self.begin_range = -5
         self.end_range = 5
 
         # Create new generation
         elite = [dna for dna, score in self.population[:self.selection_amount]]
-        elite = list(chain(elite, [newRandom(self.dna_size, self.end_range) for i in range(0, self.selection_amount)]))
+        #elite = list(chain(elite, [newRandom(self.dna_size, self.end_range) for i in range(0, self.selection_amount)]))
         self.population = [mutate(newCrossover(elite), self.mutation_rate, self.end_range) for i in range(0, self.pop_size)]
 
         return best, best_score

File src/optimisation_composants.py

 
-from __future__ import print_function, absolute_import, division
-import numpy as np
-import numpy.random as rnd
+from __future__ import print_function
+import random
+import numpypy as np
 
-from numba import autojit
 
 def init_fun():
-    return rnd.permutation(25)
+    new = np.arange(25)
+    random.shuffle(new)
+    return new
 
 
 def manhattan(x1, y1, x2, y2):
 
 def mod_fun(cases):
     # We want to swap 2 elements (positions) of the list "cases".
-    a, b = rnd.choice(25, 2)
+    a, b = random.sample(xrange(25), 2)
 
     new = cases.copy()
     new[a], new[b] = cases[b], cases[a]

File src/simulated_annealing.py

 from math import exp
-import numpy.random as rnd
-import numpy as np
+import random
+import numpypy as np
 
 
 class SimulatedAnnealing(object):
 
         # Init default options
         self.t_init = None
-        self.t_step = 0.99
+        self.t_step = 0.999
         self.t_stop = 10e-5
-        self.max_epoc = 100000
+        self.max_epoc = 1000000
 
 
     def findOptimalTemperature(self, mod_fun, cost_fun, init_fun):
             for i in range(0, nb_step):
                 cases_mod = mod_fun(cases.copy())
                 mod_e = cost_fun(cases_mod) - cost_fun(cases)
-                if rnd.random() < exp(-mod_e / t):
+                if random.random() < exp(-mod_e / t):
                     energie_eq += 1
                 else:
                     energie_eq -= 1
         cases = init_fun()
         cases_score = cost_fun(cases)
         changed = np.zeros(cases.shape, np.bool)
-        unchanged = 0
 
         epoc = 0
-        while unchanged < 10000 and (not stop_fun(cases_score)) and epoc < self.max_epoc and t > self.t_stop:
+        while (not stop_fun(cases_score)) and epoc < self.max_epoc and t > self.t_stop:
             # Choose neighbor
             cases_mod = mod_fun(cases)
 
             # Compute energy delta
             mod_e = score_mod - cases_score
 
-            unchanged += 1
-
             # Keep the candidate or not
-            if mod_e <= 0 or rnd.random() < exp(-mod_e / t):
-                if mod_e != 0:
-                    unchanged = 0
+            if mod_e <= 0 or random.random() < exp(-mod_e / t):
                 cases = cases_mod
                 cases_score = score_mod