To use a Genetic Algorithm in eaopt, you must implement the eaopt.Genome interface for your data type. This involves defining Evaluate, Mutate, Crossover, and Clone methods. You then use a GenomeFactory function to generate initial individuals.
Steps to run an optimization:
- Define a type that implements
eaopt.Genome. - Create a factory function that returns a new instance of your type (the
GenomeFactory). - Instantiate a GA using
eaopt.NewDefaultGAConfig().NewGA(). - Configure the GA (e.g.,
NGenerations, Callback). - Call
ga.Minimize(factory) to start the optimization process.
package main
import (
"fmt"
m "math"
"math/rand"
"github.com/MaxHalford/eaopt"
)
// A Vector contains float64s.
type Vector []float64
// Evaluate a Vector with the Drop-Wave function.
func (X Vector) Evaluate() (float64, error) {
var (
numerator = 1 + m.Cos(12*m.Sqrt(m.Pow(X[0], 2)+m.Pow(X[1], 2)))
denominator = 0.5*(m.Pow(X[0], 2)+m.Pow(X[1], 2)) + 2
)
return -numerator / denominator, nil
}
// Mutate a Vector by resampling each element from a normal distribution.
func (X Vector) Mutate(rng *rand.Rand) {
eaopt.MutNormalFloat64(X, 0.8, rng)
}
// Crossover a Vector with another Vector using uniform crossover.
func (X Vector) Crossover(Y eaopt.Genome, rng *rand.Rand) {
eaopt.CrossUniformFloat64(X, Y.(Vector), rng)
}
// Clone a Vector to produce a new one.
func (X Vector) Clone() eaopt.Genome {
var Y = make(Vector, len(X))
copy(Y, X)
return Y
}
// VectorFactory returns a random vector.
func VectorFactory(rng *rand.Rand) eaopt.Genome {
return Vector(eaopt.InitUnifFloat64(2, -10, 10, rng))
}
func main() {
// Instantiate a GA with a GAConfig
var ga, err = eaopt.NewDefaultGAConfig().NewGA()
if err != nil {
fmt.Println(err)
return
}
// Set the number of generations to run
ga.NGenerations = 10
// Add a custom print function to track progress
ga.Callback = func(ga *eaopt.GA) {
fmt.Printf("Best fitness at generation %d: %f\n", ga.Generations, ga.HallOfFame[0].Fitness)
}
// Find the minimum
err = ga.Minimize(VectorFactory)
if err != nil {
fmt.Println(err)
return
}
}