cgp

package module
v0.0.0-...-72f9989 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2017 License: MIT Imports: 7 Imported by: 0

README

Status: This project is abandoned. I'm keeping it online because it may still prove to be useful for someone, but I will not address Issues or merge Pull requests.

CGP for Go

This is a library implementing Cartesian Genetic Programming in the Go programming language.

Installation

go get github.com/DataWraith/cgp

Usage

Here's an example of using CGP for symbolic regression. We are trying to approximate the function f(x) = x³ - 2x + 10.

import "fmt"
import "github.com/DataWraith/cgp"
import "math"
import "math/rand"

// First, we set up our parameters:
options := cgp.CGPOptions{
        PopSize:      100,  // The population size. One parent, 99 children
        NumGenes:     30,   // The maximum number of functions in the genome
        MutationRate: 0.05, // The mutation rate
        NumInputs:    1,    // The number of input values
        NumOutputs:   1,    // The number of output values
        MaxArity:     2,    // The maximum arity of the functions in the FunctionList
}

// The function list specifies the functions that are used in the genetic
// program. The first input is always the constant evolved for the function.
options.FunctionList = []cgp.CGPFunction{
        func(input []float64) float64 { return input[0] },            // Constant
        func(input []float64) float64 { return input[1] },            // Pass through A
        func(input []float64) float64 { return input[2] },            // Pass through B
        func(input []float64) float64 { return input[1] + input[2] }, // Addition
        func(input []float64) float64 { return input[1] - input[2] }, // Subtraction
        func(input []float64) float64 { return input[1] * input[2] }, // Multiplication

        // Division
        func(input []float64) float64 {
                if input[2] == 0 {
                        return 0
                }
                return input[1] / input[2]
        },
}

// This function is used to generate constants for use by the functions in
// the FunctionList. In this case we are using the provided instance of
// rand.Rand to generate a random constant between 0 and 100.
options.RandConst = func(rand *rand.Rand) float64 {
        return float64(rand.Intn(101))
}

// Prepare the testcases.
var testCases = []struct {
        in  float64
        out float64
}{
        {0, 10},
        {0.5, 9.125},
        {1, 9},
        {10, 990},
        {-5, -105},
        {17, 4889},
        {3.14, 34.679144},
}

// The evaluator uses the test cases to grade an individual by setting the
// fitness to the sum of squared errors. The lower the fitness the better the
// individual. Note that the input to the individual is a slice of float64.
options.Evaluator = func(ind cgp.Individual) float64 {
       fitness := 0.0
       for _, tc := range testCases {
                input := []float64{tc.in}
                output := ind.Run(input)
                fitness += math.Pow(tc.out-output[0], 2)
        }
        return fitness
}

// Initialize CGP
gp := cgp.New(options)

// Population[0] is the parent, which is the most fit individual. We
// loop until we've found a perfect solution (fitness 0)
for gp.Population[0].Fitness > 0 {
        gp.RunGeneration()
        fmt.Println(gp.Population[0].Fitness)
}

Documentation

Overview

Package cgp implements Cartesian Genetic Programming in Go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CGP

type CGP struct {
	Options        CGPOptions
	Population     []Individual
	NumEvaluations int // The number of evaluations so far
}

func New

func New(options CGPOptions) *CGP

New takes CGPOptions and returns a new CGP object. It panics when a necessary precondition is violated, e.g. when the number of genes is negative.

func (*CGP) RunGeneration

func (cgp *CGP) RunGeneration()

RunGeneration creates offspring from the current parent via mutation, evaluates the offspring using the CGP object's Evaluator and selects the new parent for the following generation.

type CGPFunction

type CGPFunction func([]float64) float64

A CGPFunction is a function that is usable in a Genetic Program. It takes zero or more parameters and outputs a single result. For example a CGPFunction could implement binary AND or floating point multiplication.

type CGPOptions

type CGPOptions struct {
	PopSize      int              // Population Size
	NumGenes     int              // Number of Genes
	MutationRate float64          // Mutation Rate
	NumInputs    int              // The number of Inputs
	NumOutputs   int              // The number of Outputs
	MaxArity     int              // The maximum Arity of the CGPFunctions in FunctionList
	FunctionList []CGPFunction    // The functions used in evolution
	RandConst    RndConstFunction // The function supplying constants
	Evaluator    EvalFunction     // The evaluator that assigns a fitness to an individual
	Rand         *rand.Rand       // An instance of rand.Rand that is used throughout cgp to make runs repeatable
}

CGPOptions is a struct describing the options of a CGP run.

type EvalFunction

type EvalFunction func(Individual) float64

The EvalFunction takes one Individual and returns its fitness value.

type Individual

type Individual struct {
	Genes   []gene      // The function genes
	Outputs []int       // The output genes
	Options *CGPOptions // A pointer to the CGPOptions. Necessary to retrieve e.g. the mutation rate.
	Fitness float64     // The fitness of the individual
	// contains filtered or unexported fields
}

An Individual represents the genetic code of an evolved program. It contains function genes and output genes and can hold the fitness of the evolved program.

func NewIndividual

func NewIndividual(options *CGPOptions) (ind Individual)

NewIndividual creates a random valid program with the options as specified.

func (*Individual) CacheID

func (ind *Individual) CacheID() string

CacheID returns the functional ID of ind. Two individuals that have the same CacheID are guaranteed to compute the same function. Note that individuals that differ in their inactive genes but are identical in their active genes will have the same CacheID.

func (Individual) Mutate

func (ind Individual) Mutate() (mutant Individual)

Mutate returns a mutated copy of the Individual.

func (Individual) Run

func (ind Individual) Run(input []float64) []float64

Run executes the evolved program with the given input.

type RndConstFunction

type RndConstFunction func(rand *rand.Rand) float64

RndConstFunction takes a PRNG as input and outputs a random number that is used as a constant in the evolved program. This allows you to set the range and type (integers vs. floating point) of constants used during evolution. For example, if you are evolving programs that create RGB images you might constrain the RndConstFunction to return integer values between 0 and 255.

Jump to

Keyboard shortcuts

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