-
Notifications
You must be signed in to change notification settings - Fork 40
/
ga_parallel.go
89 lines (78 loc) · 1.85 KB
/
ga_parallel.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Copyright 2010 Thomas Jager <mail@jager.no> All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
Crude Parallel Genetic Algorithm
*/
package ga
import (
"fmt"
)
type GAParallel struct {
ga []*GA
Parameter GAParameter
numproc int
}
func NewGAParallel(parameter GAParameter, numproc int) *GAParallel {
gap := new(GAParallel)
gap.Parameter = parameter
gap.ga = make([]*GA, numproc)
gap.numproc = numproc
for i := 0; i < numproc; i++ {
gap.ga[i] = NewGA(parameter)
}
return gap
}
func (ga *GAParallel) String() string {
return fmt.Sprintf("Initializer = %s, Selector = %s, Mutator = %s Breeder = %s",
ga.Parameter.Initializer,
ga.Parameter.Selector,
ga.Parameter.Mutator,
ga.Parameter.Breeder)
}
func (ga *GAParallel) Init(popsize int, init GAGenome) {
for i := 0; i < ga.numproc; i++ {
ga.ga[i].Init(popsize, init)
}
}
func optimize_worker(ga *GA, gen int, c chan int) {
ga.Optimize(gen)
c <- 1
}
func (ga *GAParallel) Optimize(gen int) {
c := make(chan int, ga.numproc)
for i := 0; i < ga.numproc; i++ {
go optimize_worker(ga.ga[i], gen, c)
}
for i := 0; i < ga.numproc; i++ {
<-c
}
nselect := gen * 2
children := make([]GAGenomes, ga.numproc)
for i := 0; i < ga.numproc; i++ {
children[i] = make(GAGenomes, nselect)
for j := 0; j < nselect; j++ {
children[i][j] = ga.ga[i].Parameter.Selector.SelectOne(ga.ga[i].pop)
}
}
j := ga.numproc - 1
for i := 0; i < ga.numproc; i++ {
ga.ga[i].pop = AppendGenomes(ga.ga[i].pop, children[j])
j--
}
}
func (ga *GAParallel) OptimizeUntil(stop func(best GAGenome) bool) {
for !stop(ga.Best()) {
ga.Optimize(1)
}
}
func (ga *GAParallel) Best() GAGenome {
best := ga.ga[0].Best()
for i := 1; i < ga.numproc; i++ {
nbest := ga.ga[i].Best()
if nbest.Score() < best.Score() {
best = nbest
}
}
return best
}