-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathparticle_swarm_test.go
104 lines (96 loc) · 2.49 KB
/
particle_swarm_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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package hego
import (
"math/rand"
"testing"
)
func TestVerifyPSOSettings(t *testing.T) {
settings := PSOSettings{}
settings.PopulationSize = 10
settings.LearningRate = 0.1
settings.Omega = 0.1
settings.GlobalWeight = 0.1
settings.ParticleWeight = 0.1
err := settings.Verify()
if err != nil {
t.Error("expected verification to pass with these valid settings")
}
settings.PopulationSize = 0
err = settings.Verify()
if err == nil {
t.Error("expected verification to fail with populationsize 0")
}
err = nil
settings.PopulationSize = 10
settings.LearningRate = 0.0
err = settings.Verify()
if err == nil {
t.Error("expected verification to fail with learningrate 0")
}
err = nil
settings.LearningRate = 1.0
settings.Omega = -1.0
err = settings.Verify()
if err == nil {
t.Error("expected verification to fail with negative omega")
}
err = nil
settings.Omega = 1.0
settings.GlobalWeight = -1.0
err = settings.Verify()
if err == nil {
t.Error("expected verification to fail with negative globalweight")
}
err = nil
settings.GlobalWeight = 1.0
settings.ParticleWeight = -1.0
err = settings.Verify()
if err == nil {
t.Error("expected verification to fail with negative ParticleWeight")
}
err = nil
settings.ParticleWeight = 0.0
settings.GlobalWeight = 0.0
err = settings.Verify()
if err == nil {
t.Error("expected verification to fail with both zero particle weight and global weight")
}
}
func TestPSO(t *testing.T) {
f := func(x []float64) float64 {
return x[0] * x[0]
}
init := func() ([]float64, []float64) {
return []float64{-10 + rand.Float64()*20}, []float64{rand.Float64() * 20.0}
}
settings := PSOSettings{}
_, err := PSO(f, init, settings)
if err == nil {
t.Error("PSO should fail with invalid settings")
}
settings.MaxIterations = 100
settings.Verbose = 10
settings.LearningRate = 1.0
settings.GlobalWeight = 0.1
settings.Omega = 0.9
settings.ParticleWeight = 0.1
settings.PopulationSize = 10
res, err := PSO(f, init, settings)
if err != nil {
t.Error("PSO should not fail")
}
best := res.BestParticle
if best[0] > 0.5 || best[0] < -0.5 {
t.Errorf("PSO algorithm produced unexpected result. Wanted ~0.0, got %v", best[0])
}
if len(res.BestParticles) != 0 {
t.Error("expected BestParticles to be empty with KeepHistory=false")
}
settings.KeepHistory = true
res, err = PSO(f, init, settings)
if err != nil {
t.Error("PSO should not fail")
}
if len(res.BestParticles) == 0 {
t.Error("expected BestParticles to contain values, got 0")
}
}