ga

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 26, 2021 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package ga implements the genetic algorithm.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Entity

type Entity interface {
	// Fitness represents the fitness of this entity.
	Fitness() float64
	// Mutate is the mutation operation.
	Mutate() Entity
	// Cross is the crossover operation.
	Cross(float64, Entity) Entity
}

Entity represents an entity of GA model.

type GA

type GA struct {
	// contains filtered or unexported fields
}

GA represents the GA model.

Example
package main

import (
	"fmt"
	"math/rand"

	"gitee.com/ofunc/ga"
)

// V is an entity of GA model.
type V struct {
	X, Y float64
}

// Fitness is the fitness of this entity.
// The problem to be solved is:
//
//	max = 2x + 3y
//	4x + 3y <= 10
//	3x + 5y <= 12
//	x, y >= 0
func (v V) Fitness() float64 {
	s, f := 0.0, 2*v.X+3*v.Y
	if d := (4*v.X+3*v.Y)/10 - 1; d > 0 {
		s += d
	}
	if d := (3*v.X+5*v.Y)/12 - 1; d > 0 {
		s += d
	}
	if s > 0 {
		return -s
	} else {
		return f
	}
}

// Mutate is the mutation operation.
func (v V) Mutate() ga.Entity {
	return V{10 * rand.Float64(), 10 * rand.Float64()}
}

// Crossover is the crossover operation.
func (v V) Cross(w float64, e ga.Entity) ga.Entity {
	a := e.(V)
	return V{w*v.X + (1-w)*a.X, w*v.Y + (1-w)*a.Y}
}

func main() {
	m := ga.New(1000, V{}.Mutate)
	e, f, ok := m.Evolve(30, 10000)
	fmt.Println("fitness: ", f)
	fmt.Println("elite:", e)
	fmt.Println("isok:", ok)
}
Output:

func New

func New(n int, gen func() Entity) *GA

New creates a GA model.

func (*GA) Elite

func (a *GA) Elite() Entity

Elite returns the current elite.

func (*GA) Evolve

func (a *GA) Evolve(n int, max int) (Entity, float64, bool)

Evolve runs the GA model until the elite n generations have not changed, or the max of iterations has been reached.

func (*GA) Fitness

func (a *GA) Fitness() float64

Fitness returns the fitness of current elite.

func (*GA) Next

func (a *GA) Next() (Entity, float64)

Next gets the next generation of GA model, and returns the current elite and fitness.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL