From 58d588ce5cf7787825c47ae287c736765bfb67da Mon Sep 17 00:00:00 2001 From: lampv Date: Tue, 16 Apr 2019 11:29:58 +0700 Subject: [PATCH] ver2 --- genetic.py | 195 +++++++++++++++++++++++++++++++++++------- genetic.pyc | Bin 5964 -> 6016 bytes resourceAllocation.py | 61 ++++++++----- selections.py | 36 +++----- selections.pyc | Bin 996 -> 1589 bytes 5 files changed, 213 insertions(+), 79 deletions(-) diff --git a/genetic.py b/genetic.py index 8496c76..c90af6a 100644 --- a/genetic.py +++ b/genetic.py @@ -2,6 +2,8 @@ import statistics import sys import time +import numpy +import operator from bisect import bisect_left from enum import Enum from math import exp @@ -17,13 +19,13 @@ def _generate_parent(get_fitness, length, geneSet,generate_genes): def _mutate(parent, geneSet, get_fitness): return 0 -def _mutate_custom(parent, custom_mutate, get_fitness, bestParent): +def _mutate_custom(parent, custom_mutate, get_fitness): childGenes = parent.Genes - custom_mutate(childGenes, bestParent) - fitness = get_fitness(childGenes) - return Chromosome(childGenes, fitness, Strategies.Mutate) + child = custom_mutate(childGenes) + fitness = get_fitness(child) + return Chromosome(child, fitness, Strategies.Mutate) -def _crossover(parent, parentDonor, parents,get_fitness, crossover): +def _crossover(parent, parentDonor, parents, get_fitness, crossover): childGenes = crossover(parent.Genes, parentDonor.Genes) fitness = get_fitness(childGenes) return Chromosome(childGenes, fitness, Strategies.Crossover) @@ -33,32 +35,124 @@ def get_best(generate_genes, get_fitness, length, optimalFitness, geneSet, displ custom_mutate=None, custom_create=None, maxAge=None, poolSize=1, crossover=None): - def fnMutate(parent, bestParent): - return _mutate_custom(parent, custom_mutate, get_fitness, bestParent) - def fnGenerateParent(): return _generate_parent(get_fitness, length, geneSet, generate_genes) - strategyLookup = { - Strategies.Create: lambda p, o, i: fnGenerateParent(), - Strategies.Mutate: lambda p, o, i: fnMutate(p, i), - Strategies.Crossover: lambda p, o, i : _crossover(p, o, i, get_fitness, crossover) - } - usedStrategies = [strategyLookup[Strategies.Mutate]] - usedStrategies.append(strategyLookup[Strategies.Crossover]) - - def fnNewChild(parents, bestParent): - parent = selections.roulette_selection(parents) - parentDonor = selections.roulette_selection(parents) - while parent == parentDonor: - parentDonor = selections.roulette_selection(parents) - return random.choice(usedStrategies)(parent, parentDonor, bestParent) #bad - - for improvement in _get_improvement(fnNewChild, fnGenerateParent, - maxAge, poolSize): - display(improvement) - if improvement.Fitness == 1: - return improvement + def fnMutate(parent): + return _mutate_custom(parent, custom_mutate, get_fitness) + + # def fn(): + # pass + + # usedStrategies = [strategyLookup[Strategies.Mutate]] + # if crossover is not None: + # usedStrategies.append(strategyLookup[Strategies.Crossover]) + + bestParent = fnGenerateParent() + display(bestParent) + # yield bestParent + parents = [bestParent] + + for _ in range(poolSize - 1): + parent = fnGenerateParent() + parents.append(parent) + if parent.Fitness > bestParent.Fitness: + display(parent) + bestParent = parent + + lastParentIndex = poolSize - 1 + pindex = 1 + selectedParents = [] + while True: + # select parents + + parents = sorted(parents, key=operator.attrgetter('Fitness')) + parentIndex = 49 + for _ in range(50): + tempParent = parents[parentIndex] + selectedParents.append(tempParent) + parentIndex += 1 + + # crossover with Pc + + # for _ in range(50): + # parent = selections.roulette_selection(selectedParents) + # # import pdb; pdb.set_trace() + # parentDonor = selections.roulette_selection(selectedParents) + # while parent == parentDonor: + # parentDonor = selections.roulette_selection(selectedParents) + # child = _crossover(parent, parentDonor, parents, get_fitness, crossover) + # display(child) + # # child = fnMutate(child) + # selectedParents.append(child) + # if child.Fitness > bestParent.Fitness: + # bestParent = child + # display(bestParent) + + # mutate with Pm + + for _ in range(50): + # import pdb; pdb.set_trace() + k = random.choice('01') + if k == '0': + parent = selections.roulette_selection(selectedParents) + child = fnMutate(parent) + # display(child) + if child.Fitness > bestParent.Fitness: + bestParent = child + display(bestParent) + selectedParents.append(child) + if child.Fitness == 1: + import pdb; pdb.set_trace() + break + else: + parent = selections.roulette_selection(selectedParents) + # import pdb; pdb.set_trace() + parentDonor = selections.roulette_selection(selectedParents) + while parent == parentDonor: + parentDonor = selections.roulette_selection(selectedParents) + child = _crossover(parent, parentDonor, parents, get_fitness, crossover) + # display(child) + # child = fnMutate(child) + selectedParents.append(child) + if child.Fitness > bestParent.Fitness: + bestParent = child + display(bestParent) + + + # if child.Fitness > 0.7: + # import pdb; pdb.set_trace() + # display(child) + + parents = selectedParents + selectedParents = [] + + + + + + + + # strategyLookup = { + # Strategies.Create: lambda p, o, i: fnGenerateParent(), + # Strategies.Mutate: lambda p, o, i: fnMutate(p, i), + # Strategies.Crossover: lambda p, o, i : _crossover(p, o, i, get_fitness, crossover) + # } + # usedStrategies = [strategyLookup[Strategies.Mutate]] + # usedStrategies.append(strategyLookup[Strategies.Crossover]) + + # def fnNewChild(parents, parent1): + # parent = selections.roulette_selection(parents) + # parentDonor = selections.random_selection(parents) + # while parent == parentDonor: + # parentDonor = selections.random_selection(parents) + # return random.choice(usedStrategies)(parent, parentDonor, parent1) #bad + + # for improvement in _get_improvement(fnNewChild, fnGenerateParent, + # maxAge, poolSize): + # display(improvement) + # if improvement.Fitness == 1: + # return improvement def _get_improvement(new_child, generate_parent, maxAge, poolSize): bestParent = generate_parent() @@ -75,12 +169,51 @@ def _get_improvement(new_child, generate_parent, maxAge, poolSize): lastParentIndex = poolSize - 1 pindex = 1 while True: - - child = new_child(parents, bestParent) - + # select parents + parentIndex = 100 + for _ in range(100): + tempParent = parents[parentindex] + selectedParents.append(tempParent) + parentIndex += 1 + + # crossover with Pc + + for _ in range(100): + parent = selections.roulette_selection(parents) + parentDonor = selections.random_selection(parents) + while parent == parentDonor: + parentDonor = selections.random_selection(parents) + + + + + + # pindex = pindex - 1 if pindex > 0 else lastParentIndex + # parent = parents[pindex] + # import pdb; pdb.set_trace() + child = new_child(parents, parent) + # if parent.Fitness < child.Fitness: + # ind = parents.index(min(parents, key=operator.attrgetter('Fitness'))) + # parents[ind] = child + # parents[pindex] = child + # if maxAge is None: + # continue + # parent.Age += 1 + # if maxAge > parent.Age: + # continue + # parents[pindex] = child + # print("1") + # parents.append(child) + # ind = parents.index(max(parents, key=operator.attrgetter('Fitness'))) + # parents[ind] = child + # if bestParent.Fitness > 0.8: + # import pdb; pdb.set_trace() if child.Fitness > bestParent.Fitness: bestParent = child yield bestParent + # print('1') + # ind = parents.index(min(parents, key=operator.attrgetter('Fitness'))) + # parents[ind] = child parents.append(bestParent) diff --git a/genetic.pyc b/genetic.pyc index 2157467f6ee3bebc71cbf9b13610aa8fdb36b32d..af375b76df2b271cc97686c979ed5effadc1034d 100644 GIT binary patch delta 2367 zcmZWqOLG)e6h61RXC^)GS2B4~5{e1~g%Xg5mgR#YAc#h6&@m$s!*nOiWZrXQg`&r? zh-KJP*DYmfxwjNqs0;r98AolDo^#LX@7(jq?H4}ZH(@@E zh40VbI$xr}FNnWyV09+1PaNq9s#;XE$R%>Y2dEg(yg}6<)k0JZkzk!k)gh|cRJ8kh zi>hI&MW`6*?_nFIVwBtfeL+-=ksH)ZoZOIR666kPCdnTfy!Q2v9IKOD|*#0Ch7k_pPU zU|}7@>Kp{|i7G^0lYBwGN$Y~T7O5*{BU`#uuDWk}b+01>IHYi~@g_0X0r*XGtOon^QHqE_yV(aFn`Gdh7>11OJm((@-rIKa32$rZPF3gv>s4l?SOc~Zl^#f zGDMXjE+bCP2>HmiO)Cbqe-+ZEN|@cT3b96egGjqM@^eqedR0L3)Fsw&aeXAYJ`!yK zFzo!e;fA>-suAjrl0Qn7C?N~tOzXJOn)?5jH-Yptk}+C)j)C}N+SQ|{PmfXSo+wD9 zQ=h;^UPJkXX+1y;`&mSf^ELHM41j{S04o&3GNn09ty@$8^0RrayE#<~{c>`et8UN- zT#~%F4|IPd!Eg}~UBin+ny}>)bDBC?uzfD3{tDK5yRjcQ)Afy-AX@P*BT+;r$`UQp zDenhgJ^&*5vorf8JDe&1i(fv@Vs5JTVtv_@+%AjFrdM~JZLDEn=h~}%MW@l0o-4W6 z8cnagC>zsl8D0U&70NIllWP7pXIb+!6 z$JO0PWz6BebS6Nw(~Ic#GmCAnF4aPOW;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iWGm%oZ=x`YBvR?q|hvd=O2K%4|O;35BW^#x2%mr$!ogC*))!X=pk%IdSR zT4IFB7cJFe(VuP}{gveX>i@(YUs46_X{(#>*d-V zRX%@=b$kYDo5odR8X>W1j=yPPX#VFw4zPwC1bU58XuY4U-}K}m793}I*)}G|*e);; z)&^r~p*+aKZ975ivX7BT20V0!o_7TSgh7I8})l$4J(g}i;oTVwOtAKrd4guaYbR;h~UGpqI_d5k2I*uWw|W zO9%{4(P7r|F;e7Y?Oxj!IsWxo8PRQ}JCY(J;+(j7x@iGG?IK8Zn@H1C#a55EDXbIYDQ!jwct0m}M8W6LWg z^r_AxotS5dQ8R7S>BMLZx6He#pBJVR@+h+x82sTU>A_Um%8H0^g+#1+zw3lvOHYfE z{yF`%xUCm5r^Pw_Mdm{>qxUnl$az+h7qsfCi$(oMS0LWe*Ro3k9?T(F65%R@dQg6s zZ_m3InN-h?=ROtPryvDyA`hxHPDcOQJr%o(1MH|S=8NJz{a5~${yZNQRsB`|&4ISX zAjv9zP!6hTC1vlsX16dY6FaQ7m diff --git a/resourceAllocation.py b/resourceAllocation.py index c204e4e..0ee7526 100644 --- a/resourceAllocation.py +++ b/resourceAllocation.py @@ -2,6 +2,7 @@ import math import random import unittest +import copy from itertools import chain import genetic @@ -25,7 +26,7 @@ def generate_time_sched(genes, index, arrayOfDependencies, arrayOfDuration): for i in range(len(arrayOfDependencies)): if arrayOfDependencies[i][1] == index: timeTemp = genes[arrayOfDependencies[i][0]][0] # time schedule of task j - res = random.randrange(timeTemp, 90) + res = random.randrange(timeTemp, 75) return res return timeSched @@ -74,39 +75,53 @@ def display(candidate, startTime): candidate.Strategy.name, timeDiff)) +def mutate(genes, fnGetFitness, arrayOfDependencies, arrayOfDuration): + # genes[index][0] = generate_time_sched(genes, index, arrayOfDependencies, arrayOfDuration) + # index = random.randrange(1, len(genes)+1) + # tempGenes[index][0] = random.randrange(0,71) -def get_distance(locationA, locationB): - return 0 - + # return tempGenes -def mutate(genes, fnGetFitness, arrayOfDependencies, arrayOfDuration, bestParent): - initialFitness = fnGetFitness(genes) - a = 0 + # return genes + tempGenes = copy.deepcopy(genes) index = random.randrange(1, len(genes)+1) - for _ in range(0,20): - # import pdb; pdb.set_trace() - a = genes[index][0] - genes[index][0] = generate_time_sched(genes, index, arrayOfDependencies, arrayOfDuration) - - fitness = fnGetFitness(genes) + initialFitness = fnGetFitness(genes) + for _ in range(70): + tempGenes[index][0] = generate_time_sched(genes, index, arrayOfDependencies, arrayOfDuration) + fitness = fnGetFitness(tempGenes) if fitness > initialFitness: - return - genes[index][0] = a - return + return tempGenes + return tempGenes def crossover(genes, donorGenes, fnGetFitness): + tempGenes = copy.deepcopy(genes) + tempDonor = copy.deepcopy(donorGenes) initialFitness = fnGetFitness(genes) if (fnGetFitness(genes) > fnGetFitness(donorGenes)) else fnGetFitness(donorGenes) - + # import pdb; pdb.set_trace() for i in range(1,11): - genes[i][0], donorGenes[i][0] = donorGenes[i][0], genes[i][0] - childGenes = genes if (fnGetFitness(genes) > fnGetFitness(donorGenes)) else donorGenes + # i = random.randrange(1, 11) + tempGenes[i][0], tempDonor[i][0] = tempDonor[i][0], tempGenes[i][0] + childGenes = tempGenes if (fnGetFitness(tempGenes) > fnGetFitness(tempDonor)) else tempDonor if fnGetFitness(childGenes) > initialFitness: return childGenes - donorGenes[i][0], genes[i][0] = genes[i][0], donorGenes[i][0] - return genes + # donorGenes[i][0], genes[i][0] = genes[i][0], donorGenes[i][0] + + return childGenes + + # initialFitness = fnGetFitness(genes) if (fnGetFitness(genes) > fnGetFitness(donorGenes)) else fnGetFitness(donorGenes) + + # for i in range(1,11): + + # genes[i][0], donorGenes[i][0] = donorGenes[i][0], genes[i][0] + # childGenes = genes if (fnGetFitness(genes) > fnGetFitness(donorGenes)) else donorGenes + + # if fnGetFitness(childGenes) > initialFitness: + # return childGenes + # donorGenes[i][0], genes[i][0] = genes[i][0], donorGenes[i][0] + # return genes class ResourceAllocationTest(unittest.TestCase): geneSet = "01" @@ -130,8 +145,8 @@ def fnGetFitness(genes): return get_fitness_of_duration(genes,numberOfTask, arrayOfDependencies, arrayOfDuration) - def fnMutate(genes, bestParent): - mutate(genes, fnGetFitness, arrayOfDependencies, arrayOfDuration, bestParent) + def fnMutate(genes): + return mutate(genes, fnGetFitness, arrayOfDependencies, arrayOfDuration) def fnCrossover(genes, donor): return crossover(genes, donor, fnGetFitness) diff --git a/selections.py b/selections.py index 49e5a41..e2b7b6e 100644 --- a/selections.py +++ b/selections.py @@ -1,22 +1,17 @@ import random import operator +import numpy -def random_selection(parents, index): - donorIndex = random.randrange(0, len(parents)) - if donorIndex == index: - donorIndex = (donorIndex + 1) % len(parents) +def random_selection(parents): + index = random.randrange(0, len(parents)) - # import pdb; pdb.set_trace() - return parents[donorIndex] + return parents[index] def roulette_selection(parents): ''' Selects individuals to be parents based on their fitness proportion ''' - # sorted_pop = sorted(parents, key=operator.attrgetter('Fitness')) - # parents_pop's first is the best distance - sum_fits = 0 # import pdb; pdb.set_trace() for ind in parents: @@ -29,21 +24,12 @@ def roulette_selection(parents): if current > pick: return ind - # sum_fits = sum(operator.attrgetter('Fitness')) +def tournament_selection(parents, pressure): - # max_fitness = max(population, key=operator.attrgetter(fitness_name)) - # if minimization: - # sum_fits = sum(max_fitness - operator.attrgetter(fitness_name)(ind) for ind in population) - # else: - # sum_fits = sum(operator.attrgetter(fitness_name)(ind) for ind in population) - - # pick = random_state.uniform(0, sum_fits) - # current = 0 - # for ind in sorted_pop: - # if minimization: - # current += (max_fitness - ind.fitness) - # else: - # current += ind.fitness + tournament_pool_size = int(len(parents)*pressure) + tournamet_pool = numpy.random.choice(parents, size=tournament_pool_size, replace=False) + # import pdb; pdb.set_trace() + return max(tournamet_pool, key=operator.attrgetter('Fitness')) - # if current > pick: - # return ind +def best_selection(parents): + return parents[len(parents)-1] diff --git a/selections.pyc b/selections.pyc index e6c0e3def14d0118daefb781f3e503a2c4a6a274..92a9df80e86b0b8cf467257651425dca4d7e6cbc 100644 GIT binary patch delta 742 zcmZ8fL5|Zv5bPc&&SvGH&9bZ(f)L_@pMgMdf*hO!QiK#4X9V^-w&m$ayC_i(;m9S* z3pnrs#GS|R10Dcf6IdZ^O;1g`XR5l!KYHJyQSftce0%r#O-6qnqw^CT?&WTDe?v59 zDh*8y%?*7dng%ovJm}E8<3X3^T@OMOPvTH_=fCtBXRHthc62<`;T~!bqJmK>hE_yd zrmdkh1Fx9wPGamB=Nf4D{qZ?g($mnSt*yjKS8=|NxE=sGoK1XTzJB5_yg5ed6sc}# z20S#U9P&Wlh_k;+AkeFMr9jn)=T;p`f2PygKw1${(Saycy7KKS^OnszAPH&ZeNbJ+ z5qv-s%#(NnNn?Q~mw&KccWaw6&8!5PytLN|=;OWypUEppe2dswEf>voq5u>`+50-z zjrj5+E#2XWMS3MinyDMxrc$?pmQ#`TofUa*+Zf~t$b4DTTIZInl`~}OWm}~SwQ<(e zbvg4IZ~gP(kl&y1>&yS@oh@x9d0maP+(8|gbADhl+%X0iy{m9vZBt_px2yhL+}tWE zV+7yy0R{Uym_CJ!x7Nw*hUt-J9K0cp@dJ2ck~=^{1o)Cf2=@?1`yyygu#WV$Bh&Bp HhyC7flAwY= delta 299 zcmdnW^MqZR`7B&&&x0J%u7kFn7o%Y ze6k;-h#<)NVh)gEMhQk9MseoN`HV{$EqOq~LLgxdHYQ$1K_($aHb!0`jl3x_W2IK_sPTtB|zy)IRF!C^QasU9Y)iOf>