-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSelection.py
54 lines (43 loc) · 1.83 KB
/
Selection.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
import Tree
#from gp import D
import random
import multiprocessing as mp
import itertools
def elitism(parents, offspring, popsize):
newgen = sorted(parents + offspring, key=lambda x: x.fit)
return newgen[:popsize]
def select(parents, tournament_type, popsize, tournament_size ):
pool = mp.Pool(processes=5)
pop_per_process = int(popsize/5)
chosen = pool.starmap(tournament, ((parents, pop_per_process, tournament_size), (parents, pop_per_process, tournament_size),
(parents, pop_per_process, tournament_size), (parents, pop_per_process, tournament_size),
(parents, pop_per_process, tournament_size)))
chosen = list(itertools.chain.from_iterable(chosen))
if tournament_type is "doubletournament":
chosen = pool.starmap(double_tournament, ((chosen, pop_per_process), (chosen, pop_per_process),
(chosen,pop_per_process), (chosen,pop_per_process), (chosen,pop_per_process)))
chosen = list(itertools.chain.from_iterable(chosen))
pool.close()
pool.join()
#print("--- %s seconds1 ---" % (time.time() - start_time))
chosen = sorted(chosen, key=lambda x: x[1])
return chosen
def tournament(parents, popsize, tsize):
chosen = []
append = chosen.append
while len(chosen) < popsize:
r = [random.randint(0,popsize-1) for x in range(0,tsize)]
append(parents[min(r)])
return chosen
def double_tournament(parents, popsize):
chosen = []
append = chosen.append
parents = sorted(parents, key=lambda x: x.size)
while len(chosen) < popsize:
r = [random.randint(0, popsize - 1) for x in range(0, 2)]
if random.random() < 0.7:
append(parents[min(r)])
else:
append(parents[max(r)])
chosen = sorted(chosen, key=lambda x: x.fit)
return chosen