-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselection_test.go
83 lines (72 loc) · 2.58 KB
/
selection_test.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
package ga
import (
"math/rand"
"testing"
)
func TestSetSelectionFunc(t *testing.T) {
t.Parallel()
var genA = NewGeneticAlgorithm()
genA.SetSeed(3)
genA.SetOutputFunc(func(a ...interface{}) { t.Log(a...) })
genA.SetSelectionFunc(func(Fitness FitnessFunction, genomes Population, random *rand.Rand) Population {
offspring := make(Population, 0)
for range genomes {
offspring = append(offspring, genomes[0].Copy())
}
return offspring
})
genA.Candidates = Population{
{Bitstring{"1", "1", "1", "1"}},
{Bitstring{"0", "1", "1", "1"}},
{Bitstring{"0", "0", "1", "1"}},
{Bitstring{"0", "0", "0", "1"}},
}
genA.Candidates = genA.Selection(genA.Fitness, genA.Candidates, genA.RandomEngine)
expectedFitness := 4
gotFitness := genA.AverageFitness(genA.Candidates)
if expectedFitness != gotFitness {
t.Error("Set selection function did not work.", "Expected:", expectedFitness, "Got:", gotFitness)
} else {
t.Log("Set selection function worked.", "Expected:", expectedFitness, "Got:", gotFitness)
}
}
func TestTournament(t *testing.T) {
t.Parallel()
var genA = NewGeneticAlgorithm()
genA.SetSeed(3)
genA.SetOutputFunc(func(a ...interface{}) { t.Log(a...) })
genA.Candidates = Population{
{Bitstring{"1", "1", "1", "1"}},
{Bitstring{"0", "1", "1", "1"}},
{Bitstring{"0", "0", "1", "1"}},
{Bitstring{"0", "0", "0", "1"}},
}
avgFitnessBefore := genA.AverageFitness(genA.Candidates)
genA.Candidates = genA.Selection(genA.Fitness, genA.Candidates, genA.RandomEngine)
avgFitnessAfter := genA.AverageFitness(genA.Candidates)
if avgFitnessAfter < avgFitnessBefore {
t.Error("Average Fitness decreased after tournament.", "Was:", avgFitnessBefore, "Now:", avgFitnessAfter)
} else {
t.Log("Average Fitness no worse after tournament.", "Was:", avgFitnessBefore, "Now:", avgFitnessAfter)
}
}
func TestRoulette(t *testing.T) {
t.Parallel()
var genA = NewGeneticAlgorithm()
genA.SetSeed(3)
genA.SetOutputFunc(func(a ...interface{}) { t.Log(a...) })
genA.Candidates = Population{
{Bitstring{"1", "1", "1", "1"}},
{Bitstring{"0", "1", "1", "1"}},
{Bitstring{"0", "0", "1", "1"}},
{Bitstring{"0", "0", "0", "1"}},
}
avgFitnessBefore := genA.AverageFitness(genA.Candidates)
genA.Candidates = genA.Selection(genA.Fitness, genA.Candidates, genA.RandomEngine)
avgFitnessAfter := genA.AverageFitness(genA.Candidates)
if avgFitnessAfter < avgFitnessBefore {
t.Error("Average Fitness decreased after tournament.", "Was:", avgFitnessBefore, "Now:", avgFitnessAfter)
} else {
t.Log("Average Fitness no worse after tournament.", "Was:", avgFitnessBefore, "Now:", avgFitnessAfter)
}
}