-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathga.go
112 lines (96 loc) · 2.45 KB
/
ga.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
Copyright 2010 Thomas Jager <[email protected]> All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
Genetic Algorithm
*/
package ga
import (
"fmt"
"math/rand"
"sort"
)
type GAParameter struct {
//Chance of breeding
PBreed float64
//Chance of mutation
PMutate float64
// Initializer, Selector, Mutator, Breeder Objects this GA will use
Initializer GAInitializer
Selector GASelector
Mutator GAMutator
Breeder GABreeder
}
type GA struct {
pop GAGenomes
popsize int
Parameter GAParameter
}
func NewGA(parameter GAParameter) *GA {
ga := new(GA)
ga.Parameter = parameter
return ga
}
func (ga *GA) 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 *GA) Init(popsize int, i GAGenome) {
ga.pop = ga.Parameter.Initializer.InitPop(i, popsize)
ga.popsize = popsize
}
func (ga *GA) Optimize(gen int) {
for i := 0; i < gen; i++ {
l := len(ga.pop) // Do not try to breed/mutate new in this gen
for p := 0; p < l; p++ {
//Breed two inviduals selected with selector.
if ga.Parameter.PBreed > rand.Float64() {
children := make(GAGenomes, 2)
children[0], children[1] = ga.Parameter.Breeder.Breed(
ga.Parameter.Selector.SelectOne(ga.pop),
ga.Parameter.Selector.SelectOne(ga.pop))
ga.pop = AppendGenomes(ga.pop, children)
}
//Mutate
if ga.Parameter.PMutate > rand.Float64() {
children := make(GAGenomes, 1)
children[0] = ga.Parameter.Mutator.Mutate(ga.pop[p])
ga.pop = AppendGenomes(ga.pop, children)
}
}
//cleanup remove some from pop
// this should probably use a type of selector
sort.Sort(ga.pop)
ga.pop = ga.pop[0:ga.popsize]
}
}
func (ga *GA) OptimizeUntil(stop func(best GAGenome) bool) {
for !stop(ga.Best()) {
ga.Optimize(1)
}
}
func (ga *GA) Best() GAGenome {
sort.Sort(ga.pop)
return ga.pop[0]
}
func (ga *GA) PrintTop(n int) {
sort.Sort(ga.pop)
if len(ga.pop) < n {
for i := 0; i < len(ga.pop); i++ {
fmt.Printf("%2d: %s Score = %f\n", i, ga.pop[i], ga.pop[i].Score())
}
return
}
for i := 0; i < n; i++ {
fmt.Printf("%2d: %s Score = %f\n", i, ga.pop[i], ga.pop[i].Score())
}
}
func (ga *GA) PrintPop() {
fmt.Printf("Current Population:\n")
for i := 0; i < len(ga.pop); i++ {
fmt.Printf("%2d: %s Score = %f\n", i, ga.pop[i], ga.pop[i].Score())
}
}