neat

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package neat implements the NeuroEvolution of Augmenting Topologies (NEAT) method, which can be used to evolve specific Artificial Neural Networks from scratch using genetic algorithms.

Index

Constants

View Source
const NumTraitParams = 8

NumTraitParams The number of parameters used in neurons that learn through habituation, sensitization or Hebbian-type processes

Variables

View Source
var (
	// LogLevel The current log level of the context
	LogLevel LoggerLevel

	// DebugLog The logger to output all messages
	DebugLog = func(message string) {
		if acceptLogLevel(LogLevel, LogLevelDebug) {
			_ = loggerDebug.Output(2, message)
		}
	}
	// InfoLog The logger to output messages with Info and up level
	InfoLog = func(message string) {
		if acceptLogLevel(LogLevel, LogLevelInfo) {
			_ = loggerInfo.Output(2, message)
		}
	}
	// WarnLog The logger to output messages with Warn and up level
	WarnLog = func(message string) {
		if acceptLogLevel(LogLevel, LogLevelWarning) {
			_ = loggerWarn.Output(2, message)
		}
	}
	// ErrorLog The logger to output messages with Error and up level
	ErrorLog = func(message string) {
		if acceptLogLevel(LogLevel, LogLevelError) {
			_ = loggerError.Output(2, message)
		}
	}
)
View Source
var (
	ErrNoActivatorsRegistered                = errors.New("no node activators registered with NEAT options, please assign at least one to NodeActivators")
	ErrActivatorsProbabilitiesNumberMismatch = errors.New("number of node activator probabilities doesn't match number of activators")
)
View Source
var ErrNEATOptionsNotFound = errors.New("NEAT options not found in the context")
View Source
var (
	ErrTraitsParametersCountMismatch = errors.New("traits parameters number mismatch")
)

Functions

func InitLogger

func InitLogger(level string) error

InitLogger is to initialize logger

func NewContext

func NewContext(ctx context.Context, opts *Options) context.Context

NewContext returns a new Context that carries value of NEAT options.

Types

type GenomeCompatibilityMethod

type GenomeCompatibilityMethod string

GenomeCompatibilityMethod defines the method to calculate genomes compatibility

const (
	GenomeCompatibilityMethodLinear GenomeCompatibilityMethod = "linear"
	GenomeCompatibilityMethodFast   GenomeCompatibilityMethod = "fast"
)

func (GenomeCompatibilityMethod) Validate

func (g GenomeCompatibilityMethod) Validate() error

Validate checks if this genome compatibility method is supported.

type LoggerLevel

type LoggerLevel string

LoggerLevel type to specify logger output level

const (
	// LogLevelDebug The Debug log level
	LogLevelDebug LoggerLevel = "debug"
	// LogLevelInfo The Info log level
	LogLevelInfo LoggerLevel = "info"
	// LogLevelWarning The Warning log level
	LogLevelWarning LoggerLevel = "warn"
	// LogLevelError The Error log level
	LogLevelError LoggerLevel = "error"
)

type Options

type Options struct {
	// Probability of mutating a single trait param
	TraitParamMutProb float64 `yaml:"trait_param_mut_prob"`
	// Power of mutation on a single trait param
	TraitMutationPower float64 `yaml:"trait_mutation_power"`
	// The power of a link weight mutation
	WeightMutPower float64 `yaml:"weight_mut_power"`

	// Genome compatibility coefficients.
	// Compatibility = disjoint_coeff * pdg + excess_coeff * peg + mutdiff_coeff * mdmg
	DisjointCoeff float64 `yaml:"disjoint_coeff"`
	ExcessCoeff   float64 `yaml:"excess_coeff"`
	MutdiffCoeff  float64 `yaml:"mutdiff_coeff"`

	// CompatThreshold is the compatibility distance below which two genomes are considered the same species.
	CompatThreshold float64 `yaml:"compat_threshold"`

	// Probabilities of a non-mating reproduction
	MutateOnlyProb         float64 `yaml:"mutate_only_prob"`
	MutateRandomTraitProb  float64 `yaml:"mutate_random_trait_prob"`
	MutateLinkTraitProb    float64 `yaml:"mutate_link_trait_prob"`
	MutateNodeTraitProb    float64 `yaml:"mutate_node_trait_prob"`
	MutateLinkWeightsProb  float64 `yaml:"mutate_link_weights_prob"`
	MutateToggleEnableProb float64 `yaml:"mutate_toggle_enable_prob"`
	MutateGeneReenableProb float64 `yaml:"mutate_gene_reenable_prob"`
	MutateAddNodeProb      float64 `yaml:"mutate_add_node_prob"`
	MutateAddLinkProb      float64 `yaml:"mutate_add_link_prob"`
	// Probability of mutation involving disconnected input connections
	MutateConnectSensors float64 `yaml:"mutate_connect_sensors"`

	// Probabilities for cross-species mating and crossover type selection
	InterspeciesMateRate  float64 `yaml:"interspecies_mate_rate"`
	MateMultipointProb    float64 `yaml:"mate_multipoint_prob"`
	MateMultipointAvgProb float64 `yaml:"mate_multipoint_avg_prob"`
	MateSinglepointProb   float64 `yaml:"mate_singlepoint_prob"`

	// MateOnlyProb is the probability of mating without subsequent mutation
	MateOnlyProb float64 `yaml:"mate_only_prob"`
	// RecurOnlyProb forces selection of only recurrent links when adding a link
	RecurOnlyProb float64 `yaml:"recur_only_prob"`

	// PopSize is the initial population size (population is variable-size in ALife mode)
	PopSize int `yaml:"pop_size"`
	// NewLinkTries is the number of attempts mutateAddLink makes to find an unconnected pair
	NewLinkTries int `yaml:"newlink_tries"`

	// GenCompatMethod selects the genome compatibility calculation (linear or fast)
	GenCompatMethod GenomeCompatibilityMethod `yaml:"genome_compat_method"`

	// NodeActivators is the list of activation functions to choose from for new nodes
	NodeActivators []math.NodeActivationType `yaml:"-"`
	// NodeActivatorsProb are the probabilities of each activator in NodeActivators
	NodeActivatorsProb []float64 `yaml:"-"`

	// NodeActivatorsWithProbs is the YAML representation of NodeActivators+Probs
	NodeActivatorsWithProbs []string `yaml:"node_activators"`

	// LogLevel controls log output verbosity
	LogLevel string `yaml:"log_level"`
}

Options holds the NEAT algorithm parameters.

func FromContext

func FromContext(ctx context.Context) (*Options, bool)

FromContext returns the NEAT Options value stored in ctx, if any.

func LoadNeatOptions

func LoadNeatOptions(r io.Reader) (*Options, error)

LoadNeatOptions Loads NEAT options configuration from provided reader encode in plain text format (.neat)

func LoadYAMLOptions

func LoadYAMLOptions(r io.Reader) (*Options, error)

LoadYAMLOptions is to load NEAT options encoded as YAML file

func ReadNeatOptionsFromFile

func ReadNeatOptionsFromFile(configFilePath string) (*Options, error)

ReadNeatOptionsFromFile reads NEAT options from specified configFilePath automatically resolving config file encoding.

func (*Options) NeatContext

func (c *Options) NeatContext() context.Context

NeatContext returns a context carrying these options.

func (*Options) RandomNodeActivationType

func (c *Options) RandomNodeActivationType() (math.NodeActivationType, error)

RandomNodeActivationType returns a random activation type from the registered set.

func (*Options) Validate

func (c *Options) Validate() error

Validate checks that the options are internally consistent.

type Trait

type Trait struct {
	// The trait ID
	Id int `yaml:"id"`
	// The learned trait parameters
	Params []float64 `yaml:"params"`
}

Trait is a group of parameters that can be expressed as a group more than one time. Traits save a genetic algorithm from having to search vast parameter landscapes on every node. Instead, each node can simply point to a trait and those traits can evolve on their own.

func NewTrait

func NewTrait() *Trait

NewTrait is to create empty trait with default parameters number (see: NumTraitParams above)

func NewTraitAvrg

func NewTraitAvrg(t1, t2 *Trait) (*Trait, error)

NewTraitAvrg Special Constructor creates a new Trait which is the average of two existing traits passed in

func NewTraitCopy

func NewTraitCopy(t *Trait) *Trait

NewTraitCopy The copy constructor

func (*Trait) Mutate

func (t *Trait) Mutate(traitMutationPower, traitParamMutProb float64)

Mutate perturb the trait parameters slightly

func (*Trait) String

func (t *Trait) String() string

Directories

Path Synopsis
Package genetics holds data holders and helper utilities used to implement genetic evolution algorithm
Package genetics holds data holders and helper utilities used to implement genetic evolution algorithm
Package math defines standard mathematical primitives used by the NEAT algorithm as well as utility functions
Package math defines standard mathematical primitives used by the NEAT algorithm as well as utility functions
Package network provides data structures and utilities to describe Artificial Neural Network and network solvers.
Package network provides data structures and utilities to describe Artificial Neural Network and network solvers.
formats
Package formats defines the serialization formats which can be used for network graph persistence
Package formats defines the serialization formats which can be used for network graph persistence

Jump to

Keyboard shortcuts

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