Skip to content

Commit

Permalink
approaching deepcopy heavywatal#22
Browse files Browse the repository at this point in the history
  • Loading branch information
hamazaki1990 committed May 26, 2017
1 parent a334d5c commit 98965aa
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
15 changes: 10 additions & 5 deletions hamazaki1990/individual.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import random
import copy


class Individual:
mutationrate = 0.001
mutationrate = 1

def __init__(self, n, f=1.0):
self._id = n
Expand All @@ -20,10 +21,12 @@ def get_genotype(self):

def acquire_mutation(self):
r = random.random()
next_genotype = self._genotype
next_ind = copy.deepcopy(self)
next_genotype = next_ind._genotype
if r < Individual.mutationrate:
next_genotype.append(random.random())
self._genotype = next_genotype
next_ind._genotype = next_genotype
return next_ind

def __repr__(self):
return str(self._id)
Expand All @@ -34,11 +37,13 @@ def main():
print(ind.get_id())
print(ind.get_fitness())

ind2 = Individual(30, 0.8)
ind2 = Individual(30)
print(ind2.get_id())
print(ind2.get_fitness())
ind2.acquire_mutation()
print(ind2.get_genotype())
ind2_1 = ind2.acquire_mutation()
print(ind2.get_genotype())
print(ind2_1.get_genotype())
ind2.acquire_mutation()
print(ind2.get_genotype())
print(ind2.get_id())
Expand Down
11 changes: 4 additions & 7 deletions hamazaki1990/population.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import random
import copy
from individual import Individual


Expand Down Expand Up @@ -34,19 +33,17 @@ def next_genwf(self):
cumsum_fitness = [sum(fitness[:i]) for i in range(1, size + 1)]
next_generation = []
for x in range(size):
current_inds = copy.deepcopy(self._inds)
next_inds = roulettechoice(current_inds, cumsum_fitness)
next_inds.acquire_mutation()
parent_inds = roulettechoice(self._inds, cumsum_fitness)
next_inds = parent_inds.acquire_mutation()
next_generation.append(next_inds)
self._inds = next_generation
return next_generation

def next_genmo(self):
fitness = [x.get_fitness() for x in self._inds]
size = len(self._inds)
cumsum_fitness = [sum(fitness[:i]) for i in range(1, size + 1)]
i_dying = random.randrange(size)
current_inds = copy.deepcopy(self._inds)
next_inds = roulettechoice(current_inds, cumsum_fitness)
next_inds = roulettechoice(self._inds, cumsum_fitness)
next_inds.acquire_mutation()
self._inds[i_dying] = next_inds

Expand Down

0 comments on commit 98965aa

Please sign in to comment.