-
Notifications
You must be signed in to change notification settings - Fork 96
/
models.go
384 lines (360 loc) · 9.93 KB
/
models.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package eaopt
import (
"errors"
"math/rand"
)
var (
errNilSelector = errors.New("selector cannot be nil")
errInvalidMutRate = errors.New("mutRate should be between 0 and 1")
errInvalidCrossRate = errors.New("crossRate should be between 0 and 1")
)
// Two parents are selected from a pool of individuals, crossover is then
// applied to generate two offsprings. The selection and crossover process is
// repeated until n offsprings have been generated. If n is uneven then the
// second offspring of the last crossover is discarded.
func generateOffsprings(n uint, indis Individuals, sel Selector, crossRate float64,
rng *rand.Rand) (Individuals, error) {
var (
offsprings = make(Individuals, n)
i = 0
)
for i < len(offsprings) {
// Select 2 parents
var selected, _, err = sel.Apply(2, indis, rng)
if err != nil {
return nil, err
}
// Generate 2 offsprings from the parents
if rng.Float64() < crossRate {
selected[0].Crossover(selected[1], rng)
}
if i < len(offsprings) {
offsprings[i] = selected[0]
i++
}
if i < len(offsprings) {
offsprings[i] = selected[1]
i++
}
}
return offsprings, nil
}
// A Model specifies a protocol for applying genetic operators to a
// population at generation i in order for it obtain better individuals at
// generation i+1.
type Model interface {
Apply(pop *Population) error
Validate() error
}
// ModGenerational implements the generational model.
type ModGenerational struct {
Selector Selector
MutRate float64
CrossRate float64
}
// Apply ModGenerational.
func (mod ModGenerational) Apply(pop *Population) error {
// Generate as many offsprings as there are of individuals in the current population
var offsprings, err = generateOffsprings(
uint(len(pop.Individuals)),
pop.Individuals,
mod.Selector,
mod.CrossRate,
pop.RNG,
)
if err != nil {
return err
}
// Apply mutation to the offsprings
if mod.MutRate > 0 {
offsprings.Mutate(mod.MutRate, pop.RNG)
}
// Replace the old population with the new one
copy(pop.Individuals, offsprings)
return nil
}
// Validate ModGenerational fields.
func (mod ModGenerational) Validate() error {
// Check the selection method presence
if mod.Selector == nil {
return errNilSelector
}
// Check the selection method parameters
var errSelector = mod.Selector.Validate()
if errSelector != nil {
return errSelector
}
// Check the mutation rate
if mod.MutRate < 0 || mod.MutRate > 1 {
return errInvalidMutRate
}
// Check the crossover rate
if mod.CrossRate < 0 || mod.CrossRate > 1 {
return errInvalidCrossRate
}
return nil
}
// ModSteadyState implements the steady state model.
type ModSteadyState struct {
Selector Selector
KeepBest bool
MutRate float64
CrossRate float64
}
// Apply ModSteadyState.
func (mod ModSteadyState) Apply(pop *Population) error {
var selected, indexes, err = mod.Selector.Apply(2, pop.Individuals, pop.RNG)
if err != nil {
return err
}
var offsprings = selected.Clone(pop.RNG)
if pop.RNG.Float64() < mod.CrossRate {
offsprings[0].Crossover(offsprings[1], pop.RNG)
}
// Apply mutation to the offsprings
if mod.MutRate > 0 {
if pop.RNG.Float64() < mod.MutRate {
offsprings[0].Mutate(pop.RNG)
}
if pop.RNG.Float64() < mod.MutRate {
offsprings[1].Mutate(pop.RNG)
}
}
if mod.KeepBest {
// Replace the chosen individuals with the best individuals
err = offsprings[0].Evaluate()
if err != nil {
return err
}
err = offsprings[1].Evaluate()
if err != nil {
return err
}
var indis = Individuals{selected[0], selected[1], offsprings[0], offsprings[1]}
indis.SortByFitness()
pop.Individuals[indexes[0]] = indis[0]
pop.Individuals[indexes[1]] = indis[1]
} else {
// Replace the chosen parents with the offsprings
pop.Individuals[indexes[0]] = offsprings[0]
pop.Individuals[indexes[1]] = offsprings[1]
}
return nil
}
// Validate ModSteadyState fields.
func (mod ModSteadyState) Validate() error {
// Check the selection method presence
if mod.Selector == nil {
return errNilSelector
}
// Check the selection method parameters
var errSelector = mod.Selector.Validate()
if errSelector != nil {
return errSelector
}
// Check the mutation rate in the presence of a mutator
if mod.MutRate < 0 || mod.MutRate > 1 {
return errInvalidMutRate
}
// Check the crossover rate
if mod.CrossRate < 0 || mod.CrossRate > 1 {
return errInvalidCrossRate
}
return nil
}
// ModDownToSize implements the select down to size model.
type ModDownToSize struct {
NOffsprings uint
SelectorA Selector
SelectorB Selector
MutRate float64
CrossRate float64
}
// Apply ModDownToSize.
func (mod ModDownToSize) Apply(pop *Population) error {
var offsprings, err = generateOffsprings(
mod.NOffsprings,
pop.Individuals,
mod.SelectorA,
mod.CrossRate,
pop.RNG,
)
if err != nil {
return err
}
// Apply mutation to the offsprings
if mod.MutRate > 0 {
offsprings.Mutate(mod.MutRate, pop.RNG)
}
err = offsprings.Evaluate(false)
if err != nil {
return err
}
// Merge the current population with the offsprings
offsprings = append(offsprings, pop.Individuals...)
// Select down to size
var selected, _, _ = mod.SelectorB.Apply(uint(len(pop.Individuals)), offsprings, pop.RNG)
// Replace the current population of individuals
copy(pop.Individuals, selected)
return nil
}
// Validate ModDownToSize fields.
func (mod ModDownToSize) Validate() error {
// Check the number of offsprings value
if mod.NOffsprings <= 0 {
return errors.New("NOffsprings has to higher than 0")
}
// Check the first selection method presence
if mod.SelectorA == nil {
return errNilSelector
}
// Check the first selection method parameters
var errSelectorA = mod.SelectorA.Validate()
if errSelectorA != nil {
return errSelectorA
}
// Check the second selection method presence
if mod.SelectorB == nil {
return errNilSelector
}
// Check the second selection method parameters
var errSelectorB = mod.SelectorB.Validate()
if errSelectorB != nil {
return errSelectorB
}
// Check the mutation rate in the presence of a mutator
if mod.MutRate < 0 || mod.MutRate > 1 {
return errInvalidMutRate
}
return nil
}
// ModRing implements the island ring model.
type ModRing struct {
Selector Selector
MutRate float64
}
// Apply ModRing.
func (mod ModRing) Apply(pop *Population) error {
for i := range pop.Individuals {
var (
indi = pop.Individuals[i].Clone(pop.RNG)
neighbour = pop.Individuals[(i+1)%len(pop.Individuals)]
)
indi.Crossover(neighbour, pop.RNG)
// Apply mutation to the offsprings
if mod.MutRate > 0 {
if pop.RNG.Float64() < mod.MutRate {
indi.Mutate(pop.RNG)
}
if pop.RNG.Float64() < mod.MutRate {
neighbour.Mutate(pop.RNG)
}
}
err := indi.Evaluate()
if err != nil {
return err
}
err = neighbour.Evaluate()
if err != nil {
return err
}
// Select an individual out of the original individual and the
// offsprings
indis := Individuals{pop.Individuals[i], indi, neighbour}
selected, _, err := mod.Selector.Apply(1, indis, pop.RNG)
if err != nil {
return err
}
pop.Individuals[i] = selected[0]
}
return nil
}
// Validate ModRing fields.
func (mod ModRing) Validate() error {
// Check the selection method presence
if mod.Selector == nil {
return errNilSelector
}
// Check the selection method parameters
var errSelector = mod.Selector.Validate()
if errSelector != nil {
return errSelector
}
// Check the mutation rate in the presence of a mutator
if mod.MutRate < 0 || mod.MutRate > 1 {
return errInvalidMutRate
}
return nil
}
// ModMutationOnly implements the mutation only model. Each generation, all the
// Individuals are mutated. If Strict is true then the individuals are only
// replaced if the mutation is favorable.
type ModMutationOnly struct {
Strict bool
}
// Apply ModMutationOnly.
func (mod ModMutationOnly) Apply(pop *Population) error {
for i, indi := range pop.Individuals {
var mutant = indi.Clone(pop.RNG)
mutant.Mutate(pop.RNG)
err := mutant.Evaluate()
if err != nil {
return err
}
if !mod.Strict || (mod.Strict && mutant.Fitness < indi.Fitness) {
pop.Individuals[i] = mutant
}
}
return nil
}
// Validate ModMutationOnly fields.
func (mod ModMutationOnly) Validate() error {
return nil
}
// An SAAcceptance function, used by ModSimulatedAnnealing, returns the
// probability of accepting an energy (badness) increase from e0 to e1 on
// generation gen of nGen.
type SAAcceptance func(gen, nGen uint, e0, e1 float64) float64
// ModSimulatedAnnealing is a mutation-only model used to implement simulated
// annealing. All individuals are mutated but only conditionally replace their
// parent. If the mutation is favorable it always replaces its parent. If the
// mutation is unfavorable, it is more likely to replace its parent earlier
// than later in the evolution.
type ModSimulatedAnnealing struct {
GA *GA // Pointer to the encompassing GA, set by NewGA and needed to gauge progress toward completion
Accept SAAcceptance // Badness acceptance function
}
// Apply ModSimulatedAnnealing.
func (mod ModSimulatedAnnealing) Apply(pop *Population) error {
for i, indi := range pop.Individuals {
// Mutate the individual.
var mutant = indi.Clone(pop.RNG)
mutant.Mutate(pop.RNG)
err := mutant.Evaluate()
if err != nil {
return err
}
// Decide whether to keep the original or its mutation
prob := 1.0
if mutant.Fitness > indi.Fitness && mod.GA != nil {
prob = mod.Accept(mod.GA.Generations,
mod.GA.GAConfig.NGenerations,
indi.Fitness,
mutant.Fitness)
}
if prob > pop.RNG.Float64() {
pop.Individuals[i] = mutant
}
}
return nil
}
// Validate ModSimulatedAnnealing fields.
func (mod ModSimulatedAnnealing) Validate() error {
// Ideally, we would check that GA is not nil. Unfortunately, Validate
// may be called before NewGA has a chance to initialize that field so
// all we can check is the Accept field.
if mod.Accept == nil {
return errors.New("an Accept function must be provided to ModSimulatedAnnealing")
}
return nil
}