This repository has been archived by the owner on Aug 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
population.go
70 lines (63 loc) · 1.67 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
package gago
import (
"log"
"math/rand"
"time"
"golang.org/x/sync/errgroup"
)
// A Population contains individuals. Individuals mate within a population.
// Individuals can migrate from one population to another. Each population has a
// random number generator to bypass the global rand mutex.
type Population struct {
Individuals Individuals `json:"indis"`
Age time.Duration `json:"age"`
Generations int `json:"generations"`
ID string `json:"id"`
RNG *rand.Rand
}
// Generate a new population.
func newPopulation(size int, newGenome NewGenome, RNG *rand.Rand) Population {
var (
popRNG = rand.New(rand.NewSource(RNG.Int63()))
pop = Population{
Individuals: newIndividuals(size, newGenome, popRNG),
ID: randString(3, popRNG),
RNG: popRNG,
}
)
return pop
}
// Log a Population's current statistics with a provided log.Logger.
func (pop Population) Log(logger *log.Logger) {
logger.Printf(
"pop_id=%s min=%f max=%f avg=%f std=%f",
pop.ID,
pop.Individuals.FitMin(),
pop.Individuals.FitMax(),
pop.Individuals.FitAvg(),
pop.Individuals.FitStd(),
)
}
// Populations type is necessary for migration and speciation purposes.
type Populations []Population
// Apply a function to a slice of Populations.
func (pops Populations) Apply(f func(pop *Population) error, parallel bool) error {
if parallel {
var g errgroup.Group
for i := range pops {
i := i // https://golang.org/doc/faq#closures_and_goroutines
g.Go(func() error {
return f(&pops[i])
})
}
return g.Wait()
}
var err error
for i := range pops {
err = f(&pops[i])
if err != nil {
return err
}
}
return err
}