Simple Genetic Algorithm Library in Go
Go
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.gitignore
README.md
banner.png
comparison_func.go
crossover.go
crossover_test.go
evaluation_func.go
ga.go
ga_test.go
genome.go
genome_test.go
logbook.go
mutation.go
mutation_test.go
selection_func.go

README.md

alt text GoDoc

Installation

To install geneticgo run the following:

$ go get -u github.com/jinyeom/geneticgo

Usage

As GeneticGo provides most of its functionality via interface, everything is modular and user-definable. However, it also provides basic implementations of its functionalities. Below is an example use of GeneticGo.

package main

import (

	// Import GeneticGo package after installing the package through
	// the instruction provided above.
	gg "github.com/jinyeom/geneticgo"

)

func main() {
	
	// First, define an evaluation function. An evaluation function takes
	// a genome, decodes and evaluates it, and returns its fitness score.
	// Following example evaluation function evaluates a genome by how many
	// zeroes are in its chromosome. It only accepts BinaryGenome.
	zeromax := func(g Genome) float64 {

		// initialize score with 0.0
		score := 0.0

		// check for correct type of Genome
		switch g.(type) {
		case gg.*BinaryGenome:

			// count zeros in the chromosome
			for _, gene := range g.Chromosome().(string) {
				if gene == '0' {
					score += 1.0
				}
			}

		default:
			panic("Invalid Genome type")
		}

		return score
	}

	// Now, set the rest of the configuration for GA.
	config := &GAConfig{
		GenomeSize:     20, // size of each genome 
		PopulationSize: 50, // number of genome in the population
		NumGeneration:  50, // number of generations during optimization
		
		// since we want as much zeros in the genome as possible, higher score
		// means more fit; we should use DirectComparison() for comparing genomes.
		Compare: gg.DirectComparison(),

		// specify selection method; we'll use tournament selection with the
		// tournament size of 10.
		Select: gg.TournamentSelection(10),
	
		// then choose crossover method. We'll use one-point crossover.
		Crossover: gg.Crossover1P(),

		// now for mutation, we'll use standard iterative mutation, with mutation
		// rate of 0.2.	
		Mutate: gg.MutationIter(0.2),

		// lastly, specify evaluation method with the evalation function we
		// created above.
		Evaluate: zeromax,
	}		

	// Everything is set; all we have to do now is create a new GA struct by
	// specifying it with the configuration we just created and method of genome
	// initialization. Since we want binary genomes, we'll use NewBinaryGenome
	// for initializer.
	ga := New(config, gg.NewBinaryGenome)

	// Now, start optimization.
	best := ga.Run()

	// Confirm the best solution.
	fmt.Println(best.String())
}

License

This package is under GNU General Public License.