-
Notifications
You must be signed in to change notification settings - Fork 0
/
population.go
101 lines (86 loc) · 2.04 KB
/
population.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
package main
import (
"fmt"
"math"
"math/rand"
"sort"
)
type Population struct {
population []Individual
generation uint32
populationSize uint32
}
func genPopulation(populationSize uint32, configEntries map[string]*ConfigEntry) Population {
var pop Population
var i uint32
for i = 0; i < populationSize; i++ {
pop.population = append(pop.population, genIndividual(configEntries))
}
pop.generation = 0
pop.populationSize = populationSize
//fmt.Println(pop)
return pop
}
func (pop Population) String() string {
var s string
for idx, p := range pop.population {
s += fmt.Sprintf("#%d: %s %d\n", idx, p.String(), p.score)
}
return s
}
func (pop Population) mix(mutationRate uint32, configEntries map[string]*ConfigEntry) {
var i uint32
for i = 0; i < pop.populationSize/2; i++ {
var motherID int
fatherID := rand.Intn(int(pop.populationSize / 2))
for {
motherID := rand.Intn(int(pop.populationSize / 2))
if fatherID != motherID {
break
}
}
baby := pop.population[motherID].mix(&pop.population[fatherID], mutationRate, configEntries)
baby.score = scoreUnitialized
pop.population[i+pop.populationSize/2] = baby
}
}
func (pop *Population) getStdDev(topN int) float64 {
var avg float64
var stdDev float64
var count float64
for idx, p := range pop.population {
if idx > topN {
break
}
//Ignore erroneous scores
if p.score != scoreUnitialized {
avg += float64(p.score)
count += 1.0
}
}
avg /= count
stdDev = 0.0
for idx, p := range pop.population {
if idx > topN {
break
}
//Ignore erroneous scores
if p.score != scoreUnitialized {
dev := math.Abs(float64(p.score) - avg)
stdDev += dev * dev
}
}
return math.Sqrt(stdDev / count)
}
func (pop *Population) sort() {
sort.Sort(pop)
}
func (pop Population) Swap(i, j int) {
pop.population[i], pop.population[j] = pop.population[j], pop.population[i]
}
func (pop Population) Less(i, j int) bool {
return pop.population[i].score < pop.population[j].score
}
func (pop Population) Len() int {
return int(pop.populationSize)
}