/
population.go
90 lines (70 loc) 路 1.82 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
package ga
import (
"errors"
"math/rand"
"github.com/patrickmn/go-cache"
"github.com/salvacorts/eaopt"
)
type semaphore chan int
func (sem semaphore) Acquire(n int) {
for i := 0; i < n; i++ {
<-sem
}
}
func (sem semaphore) Release(n int) {
for i := 0; i < n; i++ {
sem <- 1
}
}
// Population stores individuals
type Population struct {
cache *cache.Cache
}
// MakePopulation returns an empty population
func MakePopulation() *Population {
return &Population{
cache: cache.New(cache.NoExpiration, cache.NoExpiration),
}
}
// Add an individual
func (pop *Population) Add(indiv eaopt.Individual) {
pop.cache.Set(indiv.ID, indiv, cache.NoExpiration)
}
// Remove an individual
func (pop *Population) Remove(indiv eaopt.Individual) {
pop.cache.Delete(indiv.ID)
}
// Length returns the size of the population
func (pop *Population) Length() int {
return pop.cache.ItemCount()
}
// Fold applies function f to each individual in the population
// until the end is reached or f returns false
func (pop *Population) Fold(f func(eaopt.Individual) bool) {
items := pop.cache.Items()
for _, item := range items {
cont := f(item.Object.(eaopt.Individual))
if !cont {
break
}
}
}
// Snapshot returns the state of the population
// at the moment it was called.
// TODO: Wrap the cache.Item type to eaopt.Individual
func (pop *Population) Snapshot() map[string]cache.Item {
return pop.cache.Items()
}
// RandIndividual takes an snapshot of the population and returns a random entry from it
func (pop *Population) RandIndividual(rnd *rand.Rand) (eaopt.Individual, error) {
items := pop.cache.Items()
target := rnd.Intn(len(items))
idx := 0
for _, item := range items {
if idx == target {
return item.Object.(eaopt.Individual), nil
}
idx++
}
return eaopt.Individual{}, errors.New("Could not get random individual")
}