-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReproductionHandler.py
53 lines (45 loc) · 1.87 KB
/
ReproductionHandler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from Tree import *
#from gp import MUTATIONPERCENT, CROSSOVERPERCENT
import random
from GeneticOperators import mutation, crossover
import copy
import multiprocessing as mp
import itertools
MUTATIONPERCENT = 0.05 # probabilidade de mutacao
CROSSOVERPERCENT = 0.95 # probabilidade de crossover
def Generate_Offsprings(parents, popsize):
#start_time = time.time()
pool = mp.Pool(processes=5)
pop_per_process = int(popsize/5)
offsprings = pool.starmap(apply_operators, ((parents, pop_per_process, []), (parents, pop_per_process, []),
(parents,pop_per_process, []), (parents,pop_per_process, []), (parents,pop_per_process, [])))
pool.close ()
pool.join()
offsprings = list(itertools.chain.from_iterable(offsprings))
#print("--- %s seconds1 ---" % (time.time() - start_time))
offsprings = sorted(offsprings, key=lambda x: x[1])
return offsprings
def apply_operators(parents, popsize, offspring):
appendof = offspring.append
while len(offspring) < popsize:
if len(parents) >= 2:
if random.random() <= MUTATIONPERCENT:
p = parents[random.randint(0, len(parents) - 1)]
parent = copy.deepcopy(p)
mutation(parent)
appendof(p)
else:
p1 = parents[random.randint(0, len(parents) - 1)]
parent1 = copy.deepcopy(p1)
p2 = parents[random.randint(0, len(parents) - 1)]
parent2 = copy.deepcopy(p2)
crossover(parent1, parent2)
appendof(parent1)
appendof(parent2)
else:
p = parents[random.randint(0, len(parents) - 1)]
parent = copy.deepcopy(p)
mutation(parent)
appendof(p)
offspring = sorted(offspring, key=lambda x: x.fit)
return offspring