-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconstrainedint.go
91 lines (80 loc) · 2.55 KB
/
constrainedint.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
package genes
import (
"fmt"
"math/rand"
"github.com/soypat/mu8"
)
// NewConstrainedInt returns a mu8.Gene implementation for a number
// that should be kept within bounds [min,max] during mutation.
func NewConstrainedInt(start, min, max int) *ConstrainedInt {
if min >= max {
panic(errBadConstraints)
}
if start > max || start < min {
panic(errStartOutOfBounds)
}
return &ConstrainedInt{
gene: start,
min: min,
rangeMinus1: max - min - 1,
}
}
// ConstrainedInt implements Gene interface.
// Is automatically initialized to the domain [0,1]
type ConstrainedInt struct {
// functional unit of heredity.
gene int
min int
// rangeMinus1 is the max value constraint can reach, minus 1+min.
// This allows initialization without a call to NewConstrainedInt.
rangeMinus1 int
}
// Value returns actual value of constrained float.
func (c *ConstrainedInt) Value() int { return c.gene }
// SetValue sets the gene's actual value. This method may be useful
// for setting best gene value for a single individual in the
// population by hand between runs.
func (c *ConstrainedInt) SetValue(f int) {
if f < c.min || f > c.rangeMinus1+1 {
panic("value not within constraints")
}
c.gene = f
}
// Mutate changes the gene's value by a random amount within constraints.
// Mutate implements the [mu8.Gene] interface.
func (c *ConstrainedInt) Mutate(rng *rand.Rand) {
// Uniform mutation distribution.
c.gene = c.min + rng.Intn(c.rangeMinus1+1)
}
// CloneFrom copies the argument gene into the receiver. CloneFrom implements
// the [mu8.Gene] interface. If g is not of type *ConstrainedInt, CloneFrom panics.
func (c *ConstrainedInt) CloneFrom(g mu8.Gene) {
co := castGene[*ConstrainedInt](g)
c.gene = co.gene
}
// Copy returns a copy of the gene.
func (c *ConstrainedInt) Copy() *ConstrainedInt {
clone := *c
return &clone
}
// Splice performs a crossover between the argument and the receiver genes
// and stores the result in the receiver. It implements the [mu8.Gene] interface.
// If g is not of type *ConstrainedInt, Splice panics.
func (c *ConstrainedInt) Splice(rng *rand.Rand, g mu8.Gene) {
co := castGene[*ConstrainedInt](g)
diff := c.gene - co.gene
if diff <= 0 {
if diff == 0 {
return // no work to do if genes are equal, also avoids a panic.
}
diff = -diff
}
random := rng.Intn(diff)
minGene := min(c.gene, co.gene)
// Pick a random uniformly distributed gene between two values.
c.gene = minGene + random
}
// String returns a string representation of the gene.
func (c *ConstrainedInt) String() string {
return fmt.Sprintf("%d", c.gene)
}