-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathga.go
103 lines (91 loc) · 2.1 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
package eago
import (
"fmt"
"log"
"time"
"math/rand"
)
type GA struct {
GAConfig
Population
Selector Selector
BestIndividual Individual
PrintCallBack func()
}
type GAConfig struct {
PopulationSize uint
NGenerations uint
CrossoverRate float64
MutationRate float64
ParallelEval bool
}
type Population struct {
Individuals Individuals
Generations uint
}
func NewGA(gaConfig GAConfig) *GA {
return &GA{
GAConfig: gaConfig,
Selector: Tournament{
NContestants: 2,
},
}
}
func (ga *GA) initPopulation(g Genome) {
indis := make(Individuals, ga.PopulationSize)
for i := range indis {
indis[i].Chromosome = g.Initialization()
}
indis.Evaluate(ga.ParallelEval)
ga.Population.Generations = 0
ga.Population.Individuals = indis
ga.Population.Individuals.SortByFitness()
ga.BestIndividual = ga.Population.Individuals[0]
}
func (ga *GA) evolve() error {
ga.Generations++
rand.Seed(time.Now().UnixNano())
offSprings := make(Individuals, ga.PopulationSize)
selected, err:= ga.Selector.Select(ga.Population.Individuals)
if err != nil {
log.Fatal(err)
}
for i := range offSprings {
if i == len(selected)-1 {
offSprings[i] = selected[i].Clone()
} else {
if rand.Float64() < ga.CrossoverRate {
offSprings[i].Chromosome = selected[i].Chromosome.Crossover(selected[i+1].Chromosome)
} else {
offSprings[i] = selected[i].Clone()
}
}
if rand.Float64() < ga.MutationRate {
offSprings[i].Chromosome.Mutation()
}
}
offSprings.Evaluate(ga.ParallelEval)
offSprings.SortByFitness()
ga.updateBest(offSprings[0])
ga.Population.Individuals = offSprings.Clone()
return nil
}
func (ga *GA) updateBest(indi Individual) {
if ga.BestIndividual.Fitness > indi.Fitness {
ga.BestIndividual = indi.Clone()
}
}
func (ga *GA) Minimize(g Genome) error {
ga.initPopulation(g)
for i := uint(1); i <= ga.NGenerations; i++ {
if err := ga.evolve(); err != nil {
return err
}
if ga.PrintCallBack != nil {
ga.PrintCallBack()
} else {
fmt.Printf("Generation %3d: Fitness=%.3f Solution=%.3f\n", i, ga.BestIndividual.Fitness, ga.BestIndividual.Chromosome)
}
}
return nil
}