pyrimidine package

pyrimidine is a competitive framework for genetic algorithms

pyrimidine.base module

The base classes are defined here, mainly for implementation of GAs.

This is the core module of pyrimidine.

Main classes:

BaseGene: the gene of chromosome BaseChromosome: sequence of genes, represents part of a solution BaseIndividual: sequence of chromosomes, represents a solution of a problem BasePopulation: set of individuals, represents a set of a problem

also the state of a stachostic process

BaseMultiPopulation/BaseCommunity: set of populations for more complicated optimalization BaseEnviorenment:

Remark:

  1. Subclass the classes and override some main method esp. _fitness.

  2. BaseGene is not important, as a wrapper of np.int32 and np.float64

  3. The base classes have been crafted specifically for GA-style algorithms.

If your novel algorithm differs from GAs, it is advisable to derive from the mixin classes.

Example

select ti, ni from arraies t, n sum of ni ~ 10 (for example), while ti are exptected to be not repeated

The opt. problem is min sum of {ni} and maximum of frequences in {ti} where i are selected indexes.

``` t = np.random.randint(1, 5, 100) n = np.random.randint(1, 4, 100)

import collections def max_repeat(x):

# maximum of numbers of repeats c = collections.Counter(x) bm=np.argmax([b for a, b in c.items()]) return list(c.keys())[bm]

class MyIndividual(MonoIndividual):

element_class = BinaryChromosome

def _fitness(self):

x = self.evaluate() return - x[0] - x[1]

def evaluate(self):

return np.dot(n, self.chromosomes[0]), max_repeat(ti for ti, c in zip(t, self.chromosomes[0]) if c==1)

class MyPopulation(StandardPopulation):

element_class = MyIndividual

pop = MyPopulation.random(n_individuals=50, size=100) pop.evolve() print(pop.best_individual) ```

class pyrimidine.base.BaseChromosome(*args, **kwargs)

Bases: SolutionMixin

Base class of chromosomes

Chromosome is an array of genes. It is the unit of the GA.

default_size

the default number of genes in the chromosome

Type:

int

element_class

the type of gene

Type:

TYPE

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
property class_name
cross(other)

crossover operation

Parameters:

other (BaseChromosome) – another choromosome

Raises:

NotImplementedError

default_size = 8
element_class

alias of BaseGene

equal_to(other)

Judge that self == other

Parameters:

other (BaseChromosome) – another choromosome

Returns:

bool

mutate(*args, **kwargs)
params = {'max_iter': 100}
classmethod random(*args, **kwargs)
replicate()
transition(*args, **kwargs)

The core method of the object.

This method transitions one state of the object to another state based on certain rules, such as crossing and mutating for individuals in GA, or the moving method in Simulated Annealing.

x(other)
class pyrimidine.base.BaseCommunity(*args, **kwargs)

Bases: BaseMultiPopulation

alias = {'get_best_population': 'get_best_element', 'get_best_populations': 'get_best_elements', 'get_best_populationspopulation': 'best_element', 'n_populations': 'n_elements', 'populations': 'elements', 'worst_population': 'worst_element'}
apply(f, *args, **kwargs)
property elements
flatten(type_)
isa(cls)
property n_elements
params = {'max_iter': 100, 'migrate_prob': 0.75}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.base.BaseEnvironment(*args, **kwargs)

Bases: CollectiveMixin

Base Class of environments

The main method is evaluate, computing the fitness of an individual or a population

alias = {}
apply(f, *args, **kwargs)
element_class = None
property elements
evaluate(*args, **kwargs)
isa(cls)
property n_elements
params = {'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
select(pop, n_sel)
class pyrimidine.base.BaseGene

Bases: object

Base class of genes

values

the values that a gene takes

Type:

tuple of numbers

classmethod random(*args, **kwargs)
values = (0, 1)
class pyrimidine.base.BaseIndividual(*args, **kwargs)

Bases: SolutionMixin

Base class of individuals

It is essentially a sequence of chromosomes that may vary in sizes.

You should implement the methods: cross, mute …

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
cross(other)

Cross operation of two individuals

Parameters:

other (BaseIndividual) – another individual

Returns:

BaseIndividual

cross2(other)
decode()

Decode an individual to a real solution

For example, transform a 0-1 sequence to a real number.

Returns:

a list of decoding results of its chromosomes

Return type:

list

default_size = 2
element_class

alias of BaseChromosome

property elements
get_neighbour()

to get a neighbour of an individual

e.g. mutate only one gene

isa(cls)
mutate(*args, **kwargs)
property n_elements
params = {'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
replicate()
transition(*args, **kwargs)

The core method of the object.

This method transitions one state of the object to another state based on certain rules, such as crossing and mutating for individuals in GA, or the moving method in Simulated Annealing.

class pyrimidine.base.BaseMultiPopulation(*args, **kwargs)

Bases: MultiPopulationMixin

Base class of BaseMultiPopulation

default_size

the number of populations

Type:

int

element_class

the type of the populations

Type:

BasePopulation

alias = {'get_best_population': 'get_best_element', 'get_best_populations': 'get_best_elements', 'get_best_populationspopulation': 'best_element', 'n_populations': 'n_elements', 'populations': 'elements', 'worst_population': 'worst_element'}
apply(f, *args, **kwargs)
default_size = 2
element_class

alias of BasePopulation

property elements
flatten(type_)
get_best_individual(copy=True)

To get the individual with the max. fitness

Parameters:

copy (bool, optional) – if it is true, then return a copy

Returns:

An individual representing the solution

Return type:

BaseIndividual

property individuals
isa(cls)
mate()
migrate(migrate_prob=None, copy=True)
mutate(*args, **kwargs)
property n_elements
params = {'max_iter': 100, 'migrate_prob': 0.75}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
select(*args, **kwargs)
transition(*args, **kwargs)

The core method of the object.

This method transitions one state of the object to another state based on certain rules, such as crossing and mutating for individuals in GA, or the moving method in Simulated Annealing.

class pyrimidine.base.BasePopulation(*args, **kwargs)

Bases: PopulationMixin

The base class of population in GA

Represents a state of a stachostic process (Markov process)

Extends:

PopulationMixin

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
cross(other)

Cross two populations as two individuals

Parameters:

other (BasePopulation) – another population

Returns:

the result population

Return type:

BasePopulation

default_size = 20
element_class

alias of BaseIndividual

property elements
get_rank(individual)

Get rank of one individual

Use rank if you call it frequently.

Parameters:

individual (BaseIndividual, optional) – an individual in the population

Returns:

the rank of the individual

Return type:

float

isa(cls)
mate(mate_prob=None)

To mate the entire population.

Just call the method mate of each individual (customizing anthor individual)

Keyword Arguments:

(default (mate_prob {float} -- the proba. of mating of two individuals) – {None})

mate_with(other, mate_prob=None)

To mate with another population.

Just call the method mate of each individual (customizing anthor individual)

Keyword Arguments:
  • population (other {BasePopulation} -- another)

  • (default (mate_prob {float} -- the proba. of mating of two individuals) – {None})

Returns:

the offspring

Return type:

BasePopulation

merge(other, n_sel=None)

Merge two populations.

Applied in the case when merging the offspring to the original population.

other should be a population or a list/tuple of individuals

Parameters:
  • other (BasePopulation) – another population

  • n_sel (int|float) – the number of individuals in the result population

Returns:

the result population

Return type:

BasePopulation

migrate(other)

Migrate between two populations

Parameters:

other (BasePopulation) – another population

mutate(*args, **kwargs)
property n_elements
params = {'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'tourn_size': 5}
rank(tied=False)

To rank all individuals by the fitness increasingly

Parameters:

tied (bool, optional) – for tied ranking

regester(name, key, force=True)
regester_map(name, key=None, force=True)
select(n_sel=None, tourn_size=None)

The standard method of selecting operation in GA

Select the best individual among tourn_size randomly chosen individuals, n_sel times.

Parameters:
  • n_sel (int|float) – the number of individuals that will be selected

  • tourn_size (int) – the size of the tournament

transition(*args, **kwargs)

Transition of the states of population. The core method of the class

It is considered to be the standard flow of the Genetic Algorithm

pyrimidine.base.random() x in the interval [0, 1).

pyrimidine.chromosome module

Chromosome classes, subclass of BaseChromosome

A chromosome is an array of genes, or it can be customized by the user. It could be a part of an individual or encodes a solution directly.

  • NumpyArrayChromosome: Chromosome implemented by the array of numpy

  • MatrixChromosome: matrix type of chromosome

  • BinaryChromosome: 0-1 chromosome, such as 001101001

  • DigitChromosome: chromosome with digits, such as 2312514

  • ProbabilityChromosome: chromosome representing the probability

  • QuantumChromosome: for Quantum GA

  • ListChromosome: like NumpyArrayChromosome, but implemented by the list

class pyrimidine.chromosome.ArrayChromosome(*args, **kwargs)

Bases: BaseChromosome, array

Chromosome class implemented by array.array

element_class

the type of gene

Type:

str

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
copy(type_=None)

copy the object

Parameters:
  • type – the type of new object

  • element_class (None, optional) – the new element_class

Returns:

a new object copy the data but with new type

cross(other)

crossover operation

Parameters:

other (BaseChromosome) – another choromosome

Raises:

NotImplementedError

element_class = 'd'
mutate(*args, **kwargs)
params = {'max_iter': 100}
class pyrimidine.chromosome.BinaryChromosome(*args, **kwargs)

Bases: NaturalChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
dual()
element_class

alias of BinaryGene

mutate(*args, **kwargs)
classmethod one()
params = {'max_iter': 100}
classmethod zero()
class pyrimidine.chromosome.CircleChromosome(*args, **kwargs)

Bases: FloatChromosome

Used in Quantum-Chromosome

Extends:

FloatChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
element_class

alias of CircleGene

mutate(*args, **kwargs)
normalize()
params = {'max_iter': 100}
class pyrimidine.chromosome.DigitChromosome(*args, **kwargs)

Bases: NaturalChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
element_class

alias of DigitGene

params = {'max_iter': 100}
class pyrimidine.chromosome.FloatChromosome(*args, **kwargs)

Bases: NumpyArrayChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
element_class

alias of FloatGene

mutate(*args, **kwargs)
params = {'max_iter': 100}
random_neighbour(mu=0, sigma=None)
sigma = 0.1
class pyrimidine.chromosome.FloatMatrixChromosome(*args, **kwargs)

Bases: MatrixChromosome, FloatChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
params = {'max_iter': 100}
class pyrimidine.chromosome.ListChromosome(*args, **kwargs)

Bases: BaseChromosome, list

Chromosome class implemented by list

element_class

the type of gene

Type:

str

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
copy(type_=None)

copy the object

Parameters:
  • type – the type of new object

  • element_class (None, optional) – the new element_class

Returns:

a new object copy the data but with new type

cross(other)

crossover operation

Parameters:

other (BaseChromosome) – another choromosome

Raises:

NotImplementedError

element_class = None
mutate(*args, **kwargs)
params = {'max_iter': 100}
class pyrimidine.chromosome.MatrixChromosome(*args, **kwargs)

Bases: NumpyArrayChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
cross(other)

Crossover operation for a single chromosome

Note that when len(self) == 2 ==> k==1

Parameters:

other (BaseChromosome) – another chromosome

Returns:

new chromosome, as the child of the two chromosomes

Return type:

BaseChromosome

mutate(*args, **kwargs)
params = {'max_iter': 100}
class pyrimidine.chromosome.NaturalChromosome(*args, **kwargs)

Bases: VectorChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
dual()
element_class

alias of NaturalGene

mutate(*args, **kwargs)
params = {'max_iter': 100}
class pyrimidine.chromosome.NumpyArrayChromosome(*args, **kwargs)

Bases: BaseChromosome, ndarray

Chromosome implemented by np.array

element_class

the type of gene

Type:

TYPE

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
clone()

Alias of copy, but regarded as a genetic operation

Returns:

BaseChromosome

copy(type_=None, *args, **kwargs)

copy the object

Parameters:
  • type – the type of new object

  • element_class (None, optional) – the new element_class

Returns:

a new object copy the data but with new type

cross(other)

Crossover operation for a single chromosome

Note that when len(self) == 2 ==> k==1

Parameters:

other (BaseChromosome) – another chromosome

Returns:

new chromosome, as the child of the two chromosomes

Return type:

BaseChromosome

cross2(other)
element_class

alias of BaseGene

property elements
mutate(*args, **kwargs)
params = {'max_iter': 100}
classmethod random(*args, **kwargs)
class pyrimidine.chromosome.PermutationChromosome(*args, **kwargs)

Bases: NaturalChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
cross(other)

Crossover operation for a single chromosome

Note that when len(self) == 2 ==> k==1

Parameters:

other (BaseChromosome) – another chromosome

Returns:

new chromosome, as the child of the two chromosomes

Return type:

BaseChromosome

default_size = 10
dual()
element_class

alias of NaturalGene

classmethod identity()
move_toward(other)
mutate(*args, **kwargs)
params = {'max_iter': 100}
classmethod random(size=None)
class pyrimidine.chromosome.PositiveChromosome(*args, **kwargs)

Bases: FloatChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
normalize()
params = {'max_iter': 100}
class pyrimidine.chromosome.ProbabilityChromosome(*args, **kwargs)

Bases: PositiveChromosome

The genes represent a distribution, such as [0.1,0.2,0.3,0.4].

Extends:

PositiveChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
check()
cross(other)

Crossover operation for a single chromosome

Note that when len(self) == 2 ==> k==1

Parameters:

other (BaseChromosome) – another chromosome

Returns:

new chromosome, as the child of the two chromosomes

Return type:

BaseChromosome

element_class

alias of UnitFloatGene

mutate(*args, **kwargs)
normalize()
params = {'max_iter': 100}
classmethod random(size=None)
random_neighbour()
class pyrimidine.chromosome.QuantumChromosome(*args, **kwargs)

Bases: CircleChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
decode()

Decoding of the solution/individual

Translate the solution/individual to (part of) solution, maybe a number.

measure()
property measure_result
params = {'max_iter': 100}
class pyrimidine.chromosome.StochasticMatrixChromosome(*args, **kwargs)

Bases: MatrixChromosome, PositiveChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
normalize()
params = {'max_iter': 100}
class pyrimidine.chromosome.UnitFloatChromosome(*args, **kwargs)

Bases: PositiveChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
dual()
element_class

alias of UnitFloatGene

mutate(*args, **kwargs)
normalize()
params = {'max_iter': 100}
tobinary()
class pyrimidine.chromosome.VectorChromosome(*args, **kwargs)

Bases: NumpyArrayChromosome

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
params = {'max_iter': 100}
pyrimidine.chromosome.random() x in the interval [0, 1).

pyrimidine.de module

Differential Evolution Algorithm

Ref Price, Kenneth V., Rainer M. Storn, and Jouni A. Lampinen. The differential evolution algorithm. Differential evolution: a practical approach to global optimization (2005): 37-134.

class pyrimidine.de.DifferentialEvolution(*args, **kwargs)

Bases: PopulationMixin

alias = {}
apply(f, *args, **kwargs)
default_size = 4
element_class

alias of BaseIndividual

property elements
init()
isa(cls)
move()
property n_elements
params = {'cross_prob': 0.75, 'factor': 0.05, 'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
transition(*args, **kwargs)

The core method of the object.

This method transitions one state of the object to another state based on certain rules, such as crossing and mutating for individuals in GA, or the moving method in Simulated Annealing.

class pyrimidine.de.DifferentialEvolution1(*args, **kwargs)

Bases: DifferentialEvolution

alias = {}
apply(f, *args, **kwargs)
property elements
init()
isa(cls)
move()
property n_elements
params = {'cross_prob': 0.75, 'factor': 0.5, 'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
pyrimidine.de.random() x in the interval [0, 1).

pyrimidine.deco module

Decorators

Two main kinds of decorators: 1. cache decorator: store the information of previous computing, to seep up the algorithm. Should clear it to suppress the side effect. It is used with @side-effect decorator. Methods with @side-effect will clear the cache after executing. 2. memory decorator: As cache, it record some information, but it will chage the behavior of the algorithms.

class pyrimidine.deco.Regester(key=None)

Bases: object

class pyrimidine.deco.add_cache(attrs, methods=(), scope=None, cmd={})

Bases: object

Handle with cache for class

attrs

a tuple of attributes what will be cached

Type:

tuple[str]

methods

a tuple of method names that will be cached

Type:

tuple[str]

cmd

a dict of commands to handle with the cache

Type:

dict[str]

class pyrimidine.deco.add_memory(memory={})

Bases: object

add the _memory dict to the cls/obj

The memory dict stores the best solution, unlike the _cache dict which only records the last computing result. it will affect the behaviour of the algo. And it is not affected by any genetic operation.

_memory {dict[str]} – the memory for an object;

In general, the keys are the attributes of the object.

pyrimidine.deco.basic_memory(cls)

special case of add_memory it adds _memory = {‘fitness’:None, ‘solution’: None} to an object

pyrimidine.deco.clear_cache(func)
pyrimidine.deco.clear_fitness(func)

To clear fitness of the object after some changes have occurred such as executing the method in the list USUAL_SIDE_EFFECT

pyrimidine.deco.method_cache(func, a)

make cache for the method

If the attribute a is in the cache, then access it from the cache directly, else compute it again, and store it in the cache

Please pre-define _cache as an attribute of the obj.

Parameters:
  • func (TYPE) – the original method

  • a (TYPE) – an attribute (or any value) computed by the method

Returns:

new method

Return type:

function

class pyrimidine.deco.regester_map(mappings, map_=<class 'map'>)

Bases: object

To regester the map method for the class requiring map method

Example

@regester_map(mappsings=(‘f’, ‘g’)) class C(metaclass=MetaContainor):

element_class = D default_size = 8

class D:

def random(self):

pass

def f(self):

pass

def g(self):

pass

c = C.random() list(c.f()) == [d.f() for d in c] list(c.g()) == [d.g() for d in c]

class pyrimidine.deco.set_fitness(f=None)

Bases: object

pyrimidine.deco.side_effect(func)

Decorator for methods with side effect

Apply the decorator to methods with side effects. If all the methods called by a particular method have the decorator applied, it is not advisable to include the decorator in that method.

Parameters:

func (TYPE) – a method

Returns:

Decorated method

pyrimidine.ep module

Evolution Programming

Invented by L. Fogel[1966] for designing FSM initially.

General form of the algorithm:

  1. initialize a population with N individuals

  2. loop:

    calculate f(x) for each x in population mutate x for each x get new population (mixed with the original population) select best N individuals from the 2N mixed population

where the mutation defined as,

x’ <- x + r*sqrt(v) v’ <- v + c*r*sqrt(v) (make sure that v>epsilon)

Remark:

No cross operation in EP

class pyrimidine.ep.BaseEPIndividual(*args, **kwargs)

Bases: MixedIndividual

Base class of EP Individual Class; A single solution in EP

consisted of a solution and a variance

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
decode()

Decode an individual to a real solution

For example, transform a 0-1 sequence to a real number.

Returns:

a list of decoding results of its chromosomes

Return type:

list

element_class = (<class 'pyrimidine.base.BaseChromosome'>, <class 'pyrimidine.chromosome.FloatChromosome'>)
property elements
isa(cls)
mutate(*args, **kwargs)
property n_elements
params = {'c': 0.1, 'epsilon': 0.0001, 'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
property variance
class pyrimidine.ep.EvolutionProgramming(*args, **kwargs)

Bases: BasePopulation

Evolution Programming

Extends:

BasePopulation

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
element_class

alias of BaseEPIndividual

property elements
isa(cls)
property n_elements
params = {'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
transition(*args, **kwargs)

Transition of the states of population. The core method of the class

It is considered to be the standard flow of the Genetic Algorithm

pyrimidine.es module

(mu + lambda) - Evolution Strategy

References Rechenberg, I. 1973. Evolutions strategie – Optimierung technischer Systeme nach Prinzipien der biologischen Evolution, Frommann-Holzboog.

class pyrimidine.es.EvolutionStrategy(*args, **kwargs)

Bases: BasePopulation

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
property elements
init()
isa(cls)
mate(lambda_=None)

To mate the entire population.

Just call the method mate of each individual (customizing anthor individual)

Keyword Arguments:

(default (mate_prob {float} -- the proba. of mating of two individuals) – {None})

property n_elements
params = {'lambda_': 20, 'mate_prob': 0.75, 'max_iter': 100, 'mu': 10, 'mutate_prob': 0.2, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
select_best_individuals(mu=None)
transition(*args, **kwargs)

Transition of the states of population. The core method of the class

It is considered to be the standard flow of the Genetic Algorithm

pyrimidine.errors module

Custom exception classes to handle specific error scenarios, during the object generation and attribute access processes.

exception pyrimidine.errors.RegesterError(cls, attr_name)

Bases: AttributeError

exception pyrimidine.errors.UnavalibleAttributeError(cls, attr_name)

Bases: AttributeError

exception pyrimidine.errors.UnknownSizeError(cls)

Bases: Exception

pyrimidine.gene module

Gene classes: as the elements in the chromosome.

The wrapper of data type of numpy.

class pyrimidine.gene.BinaryGene

Bases: int64, BaseGene

classmethod random(*args, **kwargs)
class pyrimidine.gene.CircleGene(x=0, /)

Bases: PeriodicGene

lb = 0
period = 6.283185307179586
ub = 6.283185307179586
class pyrimidine.gene.DigitGene

Bases: NaturalGene

class pyrimidine.gene.FloatGene(x=0, /)

Bases: float64, BaseGene

lb = 0
classmethod random(*args, **kwargs)
ub = 1
class pyrimidine.gene.IntegerGene

Bases: int64, BaseGene

lb = -10
classmethod random(*args, **kwargs)
ub = 10
class pyrimidine.gene.NaturalGene

Bases: int64, BaseGene

lb = 0
classmethod random(*args, **kwargs)
ub = 10
class pyrimidine.gene.PeriodicGene(x=0, /)

Bases: FloatGene

property period
class pyrimidine.gene.SemiCircleGene(x=0, /)

Bases: CircleGene

lb = 0
ub = 3.141592653589793
class pyrimidine.gene.UnitFloatGene(x=0, /)

Bases: FloatGene

lb = 0
ub = 1

pyrimidine.individual module

Individual classes

An individual represents a solution of a optimization problem. It is defined as a container of chromosomes.

class pyrimidine.individual.AgeIndividual(*args, **kwargs)

Bases: BaseIndividual

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
property elements
isa(cls)
property n_elements
params = {'age': 0, 'life_span': 100, 'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.individual.GenderIndividual(*args, **kwargs)

Bases: MixedIndividual

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
property elements
property gender
isa(cls)
property n_elements
params = {'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.individual.MixedIndividual(*args, **kwargs)

Bases: BaseIndividual

base class of individual

You should implement the enetic operations: cross, mutate

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
property default_size

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

element_class = (<class 'pyrimidine.base.BaseChromosome'>, <class 'pyrimidine.base.BaseChromosome'>)
property elements
isa(cls)
property n_elements
params = {'max_iter': 100}
classmethod random(size=None, n_chromosomes=None, *args, **kwargs)

Generate a container randomly

Parameters:

n_elements (**kwargs -- set size of the container if use the alias of)

Keyword Arguments:

(default (n_elements {number} -- the number of elements) – {None})

Returns:

The container class

regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.individual.MonoIndividual(*args, **kwargs)

Bases: BaseIndividual

Base class of individual with only one chromosome; It is equavalent to a chromosome.

You should implement the genetic operations: cross, mutate.

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
property chromosome
decode()

Decode an individual to a real solution

For example, transform a 0-1 sequence to a real number.

Returns:

a list of decoding results of its chromosomes

Return type:

list

property elements
isa(cls)
property n_elements
params = {'max_iter': 100}
classmethod random(*args, **kwargs)

Generate a container randomly

Parameters:

n_elements (**kwargs -- set size of the container if use the alias of)

Keyword Arguments:

(default (n_elements {number} -- the number of elements) – {None})

Returns:

The container class

regester(name, key, force=True)
regester_map(name, key=None, force=True)
classmethod set_size(sz)
class pyrimidine.individual.MultiIndividual(*args, **kwargs)

Bases: BaseIndividual

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
property elements
isa(cls)
property n_elements
params = {'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.individual.PhantomIndividual(*args, **kwargs)

Bases: BaseIndividual

after_setter()
alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
backup()
property cache
clear_cache(k=None)
cleared(k=None)
copy(cache=True, *args, **kwargs)

copy the object

Parameters:
  • type – the type of new object

  • element_class (None, optional) – the new element_class

Returns:

a new object copy the data but with new type

property elements
property fitness

get the attribute from cache, otherwise re-compute it by the default/parent method

init()
isa(cls)
property n_elements
params = {'max_iter': 100}
phantom = None
regester(name, key, force=True)
regester_map(name, key=None, force=True)
set_cache(**d)
pyrimidine.individual.PolyIndividual

alias of MultiIndividual

pyrimidine.individual.binaryIndividual(size=8)

simple binary individual encoded as a sequence such as 01001101

Equiv. to makeIndividual(size=size)

pyrimidine.individual.makeBinaryIndividual(size=8, cls=None)

To make a binary individual

Examples

makeBinaryIndividual(size=8) # an individual containting one binary choromosome with 8 genes

pyrimidine.individual.makeIndividual(element_class=<class 'pyrimidine.chromosome.BinaryChromosome'>, n_chromosomes=None, size=8, cls=None)

helper to make an individual

Example

# make an indiviudal with 2 binary chromosomes, each chromosome has 8 genes, makeIndividual(element_class=BinaryChromosome, n_chromosomes=2, size=8) # make mixed indiviudal with 2 type of chromosomes, one has 8 genes and the other has 2, makeIndividual(element_class=(BinaryChromosome, FloatChromosome), size=(8,2))

Parameters:
  • element_class (BaseChromosome, tuple, optional) – class of chromosomes

  • n_chromosomes (int, optional) – the number of chromosomes

  • size (int, tuple, optional) – the sizes of chromosomes

  • cls – the class of the return individual

Returns:

cls or other individual classes

pyrimidine.meta module

Metaclasses

class pyrimidine.meta.MetaArray(name, bases, attrs)

Bases: ParamType

Metaclass for chromosomes

Chromosomes could be seen as a container of genes. But we implement them by the arrays for convenience.

class pyrimidine.meta.MetaContainer(name, bases, attrs)

Bases: ParamType

Meta class of containers

A container is a algebric system with elements of some type and operators acting on the elements

Example:

```python from collections import UserString class C(metaclass=MetaContainer):

# container of strings element_class = UserString alias = {‘strings’: ‘elements’}

c = C(strings=[UserString(‘I’), UserString(‘love’), UserString(‘you’)], lasting=’for ever’) print(c.element_class) print(c.strings) print(c.lasting) print(c.n_strings) print(c[1]) for a in c:

print(a)

c.regester(‘upper’) print(c.upper()) ```

Output: ` <class 'collections.UserString'> <property object at 0x1065715e0> ['I', 'love', 'you'] for ever 3 love I love you ['I', 'LOVE', 'YOU'] `

random(n_elements=None, *args, **kwargs)

Generate a container randomly

Parameters:

n_elements (**kwargs -- set size of the container if use the alias of)

Keyword Arguments:

(default (n_elements {number} -- the number of elements) – {None})

Returns:

The container class

class pyrimidine.meta.MetaHighContainer(name, bases, attrs)

Bases: MetaContainer

class pyrimidine.meta.MetaList(name, bases, attrs)

Bases: MetaContainer

class pyrimidine.meta.MetaSingle(name, bases, attrs)

Bases: MetaContainer

class pyrimidine.meta.MetaTuple(name, bases, attrs)

Bases: MetaContainer

class pyrimidine.meta.ParamType(name, bases=(), attrs={})

Bases: type

Just a wrapper of type

The key-value pairs in params could be inherited from super classes, like attributes. It make users set and manage parameters of classes or instances more conveniently.

Example

class C(metaclass=ParamType):

alias = {“a”: “A”} params = {“A”: 1}

c = C() assert c.a == c.A == 1

class D(C):

pass

d = D() assert d.a == d.A == 1

mixin(bases)

mixin other base classes

Parameters:

bases (tuple) – the base classes

set(*args, **kwargs)
set_params(**kwargs)
class pyrimidine.meta.System(name, bases, attrs)

Bases: MetaContainer

Metaclass of systems, considered in future!

A system is a type of container, that defines operators on them.

pyrimidine.meta.inherit(attrs, attr, bases)

Inherit attribute the attributes attr from the base classes bases

Parameters:
  • attrs (dict) – The attribution dictionary of an object

  • attr (string) – An attribution whose value is a dict

  • bases (tuple) – The base classes

Returns:

The updated dictionary of attributions

Return type:

dict

pyrimidine.multipopulation module

classes for MultiPopulation GA

class pyrimidine.multipopulation.DoublePopulation(*args, **kwargs)

Bases: MultiPopulation

Multi-population composed by two populations: the male and female population.

alias = {'get_best_population': 'get_best_element', 'get_best_populations': 'get_best_elements', 'get_best_populationspopulation': 'best_element', 'n_populations': 'n_elements', 'populations': 'elements', 'worst_population': 'worst_element'}
apply(f, *args, **kwargs)
default_size = 2
property elements
property female_fitness
property female_population
property females
flatten(type_)
isa(cls)
property male_fitness
property male_population
property males
match(male, female)
mate()

Crossing operations between the same population are prohibited.

merge(other)
mutate()
property n_elements
params = {'mate_prob': 0.75, 'max_iter': 100, 'migrate_prob': 0.75, 'n_elders': 0.5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
select()
transition(*args, **kwargs)

The core method of the object.

This method transitions one state of the object to another state based on certain rules, such as crossing and mutating for individuals in GA, or the moving method in Simulated Annealing.

class pyrimidine.multipopulation.HybridPopulation(*args, **kwargs)

Bases: MultiPopulation

alias = {'get_best_population': 'get_best_element', 'get_best_populations': 'get_best_elements', 'get_best_populationspopulation': 'best_element', 'n_populations': 'n_elements', 'populations': 'elements', 'worst_population': 'worst_element'}
apply(f, *args, **kwargs)
property elements
flatten(type_)
isa(cls)
migrate(migrate_prob=None, copy=True)
property n_elements
params = {'max_iter': 100, 'migrate_prob': 0.75}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.multipopulation.MultiPopulation(*args, **kwargs)

Bases: BaseMultiPopulation

alias = {'get_best_population': 'get_best_element', 'get_best_populations': 'get_best_elements', 'get_best_populationspopulation': 'best_element', 'n_populations': 'n_elements', 'populations': 'elements', 'worst_population': 'worst_element'}
apply(f, *args, **kwargs)
classmethod create(individual_cls, default_size=None, population_cls=None, n_individuals=10)
property elements
flatten(type_)
isa(cls)
mate()
property n_elements
params = {'max_iter': 100, 'migrate_prob': 0.75}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
pyrimidine.multipopulation.random() x in the interval [0, 1).

pyrimidine.optimize module

Helpers for the optimization based on GA.

Users can use the following example to optimize a multivariate function by GA directly without encoding the solutions to chromosomes or individuals.

Example

` # min x1^2+x2, x1,x2 in (-1,1) ga_minimize(lambda x:x[0]**2+x[1], (-1,1), (-1,1)) `

class pyrimidine.optimize.Optimizer(Population=None, min_max='min')

Bases: object

Optimizer class for optimization problem

min_max

‘min’ or ‘max’

Type:

str

Population

GA population or other evolutionary algorithms

pyrimidine.optimize.add_init_ind(cls, init_ind=None)
pyrimidine.optimize.de_minimize(func, *xlim, decode=<function _decode>, population_size=20, size=8, init_x=None, **kwargs)

DE for minimizing the function func defined on xlim

Parameters:
  • {function} (func) – objective function defined on R^n

  • xlim – the intervals of xi

  • decode – transform a binary sequence to a real number (‘0-1’ sequence, lower_bound, upper_bound) mapsto xi

  • population_size – size of the population

  • size – the length of the encoding of xi

Example

de_minimize(lambda x:x[0]**2+x[1], (-1,1), (-1,1))

pyrimidine.optimize.ga_minimize(func, *xlim, decode=<function _decode>, population_size=20, size=8, init_x=None, **kwargs)

GA(with hall of fame) for minimizing the function func defined on xlim

Parameters:
  • {function} (func) – objective function defined on R^n

  • pairs} (xlim {tuple of number) – the intervals of xi

  • {mapping} (decode) – transform a binary sequence to a real number (‘0-1’ sequence, lower_bound, upper_bound) mapsto xi

  • {int} (population_size) – size of the population

  • int} (size {int or tuple of) – the length of the encoding of xi

  • init_x – the initial solution

Example

ga_minimize(lambda x:x[0]**2+x[1], (-1,1), (-1,1))

pyrimidine.optimize.ga_minimize_1d(func, xlim, decode=<function _decode>, population_size=20, size=8, init_x=None, *args, **kwargs)

GA(with hall of fame) for minimizing 1D function func defined on the interval xlim

Parameters:
  • func – objective function defined on R

  • numbers} (xlim {pair of) – the interval of x

  • decode – transform a binary sequence to a real number (‘0-1’ sequence, lower_bound, upper_bound) mapsto xi

  • {int} (size) – size of the population

  • {int} – the length of the encoding of x

Example

ga_minimize_1d(lambda x:x**2, (-1,1))

pyrimidine.population module

Variants of Population classes

A population is defined as a container of individuals.

  • StandardPopulation: Standard Genetic Algorithm

  • HOFPopulation: Standard Genetic Algorithm with hall of fame

  • DualPopulation: population with two dual method

  • LocalSearchPopulation: GA with local searching

  • AgePopulation: remove the old individuals in GA

class pyrimidine.population.AgePopulation(*args, **kwargs)

Bases: EliminationPopulation

Population with age

Extends:

EliminationPopulation

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
property elements
eliminate()
isa(cls)
property n_elements
params = {'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
transition(*args, **kwargs)

Transition of the states of population. The core method of the class

It is considered to be the standard flow of the Genetic Algorithm

class pyrimidine.population.DualPopulation(*args, **kwargs)

Bases: StandardPopulation

Dual Genetic Algo.

Extends:

StandardPopulation

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
dual()
property elements
isa(cls)
property n_elements
params = {'dual_prob': 0.2, 'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'n_elders': 0.3, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
transition(*args, **kwargs)

Transitation in Standard GA

class pyrimidine.population.EliminationPopulation(*args, **kwargs)

Bases: BasePopulation

Population with elimination rule

Extends:

EliminationPopulation

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
property elements
eliminate()
isa(cls)
property n_elements
params = {'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
transition(*args, **kwargs)

Transition of the states of population. The core method of the class

It is considered to be the standard flow of the Genetic Algorithm

class pyrimidine.population.GamogenesisPopulation(*args, **kwargs)

Bases: HOFPopulation

Gamogenesis Genetic Algo.

Extends:

HOFPopulation

alias = {'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'hof': 'hall_of_fame', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
property elements
get_homosex(x=0)
isa(cls)
mate(mate_prob=None)

Mate the male sub-population and female sub-population.

Keyword Arguments:

(default (mate_prob {number} -- the proba. of mating of two individuals) – {None})

property n_elements
params = {'hof_size': 2, 'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.population.HOFPopulation(*args, **kwargs)

Bases: BasePopulation

GA with hall of fame

Extends:

StandardPopulation

hall_of_fame

the copy of the best individuals

Type:

list

alias = {'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'hof': 'hall_of_fame', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
property best_individual
property elements
init()
isa(cls)
property max_fitness
property n_elements
params = {'hof_size': 2, 'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
transition(*args, **kwargs)

Update the hall_of_fame after each step of evolution

update_hall_of_fame()

Update the hall of fame

insert the best individuals of the population into the hall of fame; meanwhile, remove the worst ones in the hall of fame

class pyrimidine.population.LocalSearchPopulation(*args, **kwargs)

Bases: StandardPopulation

Population with local_search method

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
property elements
isa(cls)
property n_elements
params = {'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'n_elders': 0.5, 'n_local_iter': 2, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
transition(*args, **kwargs)

Transitation of the states of population

Calling local_search method

class pyrimidine.population.ModifiedPopulation(*args, **kwargs)

Bases: StandardPopulation

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
property elements
isa(cls)
mutate()

Mutate the whole population where the mutate_prob is computed recoording to the fitness

property n_elements
params = {'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'mutate_prob_lb': 0.1, 'mutate_prob_ub': 0.5, 'n_elders': 0.5, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.population.StandardPopulation(*args, **kwargs)

Bases: BasePopulation

Standard GA

Extends:

BasePopulation

Params:

n_elders: the number (or rate) of the last generation

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
classmethod create(individual_cls, default_size=None)
property elements
isa(cls)
property n_elements
params = {'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'n_elders': 0.5, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
transition(*args, **kwargs)

Transitation in Standard GA

pyrimidine.population.makeBinaryPopulation(n_individuals=20, size=8, as_chromosome=True, cls=None)

Helper to make a binary population

Parameters:
  • n_individuals (int, optional) – the number of the individuals in the population

  • size (int, optional) – the size of an individual or a chromosome

  • as_chromosome (bool, optional) – take chromosomes as the individuals of the population

  • cls (None, optional) – the type of the population (HOFPopulation by default)

Returns:

subclass of BasePopulation

pyrimidine.population.random() x in the interval [0, 1).

pyrimidine.pso module

Particle Swarm Optimization

Developed by J. Kennedy and R. Eberhart[Kennedy and Eberhart 2001]

Each individual consists of the position and the velocity. It also has the memory of the best solution

Ref. J. Kennedy, R. Eberhart Particle swarm optimization Proc. IEEE Int. Conf. Neural Netw., 4 (1995), pp. 1942-1948

class pyrimidine.pso.BaseParticle(*args, **kwargs)

Bases: BaseIndividual

A particle in PSO

An individual represented by 2 chromosomes: position and velocity

Variables:

default_size {number} – 2 by default memory {Particle} – the best state of the particle moving in the solution space.

Caution

Have to implement the properties in subclasses: position, velocity

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
backup(check=True)

Backup the fitness and other information

Parameters:

check (bool, optional) – check whether the fitness increases.

property best_position
copy(*args, **kwargs)

copy the object

Parameters:
  • type – the type of new object

  • element_class (None, optional) – the new element_class

Returns:

a new object copy the data but with new type

decode()

Decode an individual to a real solution

For example, transform a 0-1 sequence to a real number.

Returns:

a list of decoding results of its chromosomes

Return type:

list

default_size = 2
element_class

alias of FloatChromosome

property elements
property fitness
init()
isa(cls)
property memory
move(velocity=None)
property n_elements
params = {'max_iter': 100}
property position
regester(name, key, force=True)
regester_map(name, key=None, force=True)
set_memory(**d)
property solution

get the attribute from memory, where the best solution is stored

update_vilocity(fame=None, *args, **kwargs)
property velocity
class pyrimidine.pso.DiscreteParticleSwarm(*args, **kwargs)

Bases: ParticleSwarm

alias = {'best_particle': 'best_element', 'get_best_particle': 'get_best_element', 'get_best_particles': 'get_best_elements', 'n_particles': 'n_elements', 'particles': 'elements'}
apply(f, *args, **kwargs)
property elements
isa(cls)
move()

Move the discrete particles

property n_elements
params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_iter': 100, 'max_velocity': None}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.pso.Particle(*args, **kwargs)

Bases: BaseParticle

Standard Particle

chromosomes = (position, velocity)

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
default_size = 2
property direction
element_class

alias of FloatChromosome

property elements
isa(cls)
property n_elements
params = {'acceleration_coefficient': 3, 'inertia': 0.5, 'learning_factor': 2, 'max_iter': 100}
property position
regester(name, key, force=True)
regester_map(name, key=None, force=True)
update_vilocity(scale, inertia, learning_factor)
update_vilocity_by_fame(fame, scale, scale_fame, inertia, learning_factor, acceleration_coefficient)
property velocity
class pyrimidine.pso.ParticleSwarm(*args, **kwargs)

Bases: PopulationMixin

Standard PSO

Extends:

PopulationMixin

alias = {'best_particle': 'best_element', 'get_best_particle': 'get_best_element', 'get_best_particles': 'get_best_elements', 'n_particles': 'n_elements', 'particles': 'elements'}
apply(f, *args, **kwargs)
backup()
property best_fitness
default_size = 20
element_class

alias of Particle

property elements
init()
isa(cls)
move()

Move the particles

Define the moving rule of particles, according to the hall of fame and the best record

property n_elements
params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_iter': 100, 'max_velocity': None}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
transition(*args, **kwargs)

Transitation of the states of particles

update_hall_of_fame()
pyrimidine.pso.random() x in the interval [0, 1).

pyrimidine.qga module

Quantum GA

class pyrimidine.qga.QuantumPopulation(*args, **kwargs)

Bases: HOFPopulation

Population for quantum QA

alias = {'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'hof': 'hall_of_fame', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
backup()
default_size = 20
element_class

alias of _Individual

property elements
isa(cls)
property n_elements
params = {'hof_size': 2, 'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
update_hall_of_fame(*args, **kwargs)

Update the hall_of_fame after each step of evolution

pyrimidine.saga module

Self Adaptive GA

class pyrimidine.saga.BaseSelfAdaptiveIndividual(*args, **kwargs)

Bases: MixedIndividual

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
property desire
property elements
isa(cls)
property mate_prob
property mutate_prob
property n_elements
params = {'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.saga.RankingIndividual(*args, **kwargs)

Bases: SelfAdaptiveIndividual

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
property elements
isa(cls)
property n_elements
params = {'max_iter': 100}
ranking = None
regester(name, key, force=True)
regester_map(name, key=None, force=True)
class pyrimidine.saga.SSAPopulation(*args, **kwargs)

Bases: StandardPopulation

alias = {'best_individual': 'best_element', 'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
doom()
property elements
is_crowd()
isa(cls)
classmethod match(individual, other)
mate()

To mate the entire population.

Just call the method mate of each individual (customizing anthor individual)

Keyword Arguments:

(default (mate_prob {float} -- the proba. of mating of two individuals) – {None})

property n_elements
params = {'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'n_elders': 0.5, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
select(p=0.5)

The standard method of selecting operation in GA

Select the best individual among tourn_size randomly chosen individuals, n_sel times.

Parameters:
  • n_sel (int|float) – the number of individuals that will be selected

  • tourn_size (int) – the size of the tournament

transition(*args, **kwargs)

Transitation in Standard GA

class pyrimidine.saga.SelfAdaptiveIndividual(*args, **kwargs)

Bases: BaseSelfAdaptiveIndividual

Individual for Self-adaptive GA

Provide at least 2 chromosomes, one of them is coded by float numbers representing the prob of mutation and mating.

Extends:

BaseSelfAdaptiveIndividual

alias = {'chromosomes': 'elements', 'n_chromosomes': 'n_elements'}
apply(f, *args, **kwargs)
property desire
element_class = (<class 'pyrimidine.chromosome.BinaryChromosome'>, <class 'pyrimidine.chromosome.FloatChromosome'>)
property elements
isa(cls)
mate(other, mate_prob=None)
property mate_prob
mutate()
property mutate_prob
property n_elements
params = {'max_iter': 100}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
property trait
pyrimidine.saga.lim(r, e)
pyrimidine.saga.random() x in the interval [0, 1).

pyrimidine.studga module

The Stud GA

References: Khatib, Wael and Peter John Fleming. “The Stud GA: A Mini Revolution?” Parallel Problem Solving from Nature (1998).

class pyrimidine.studga.StudPopulation(*args, **kwargs)

Bases: HOFPopulation

alias = {'best_individuals': 'best_elements', 'get_best_individual': 'get_best_element', 'get_best_individuals': 'get_best_elements', 'hof': 'hall_of_fame', 'individuals': 'elements', 'n_individuals': 'n_elements', 'worst_individual': 'worst_element'}
apply(f, *args, **kwargs)
property elements
isa(cls)
mate(mate_prob=None)

Mating in studGA

individuals only mate with individuals in the hall of fame

property n_elements
params = {'fame_size': 2, 'hof_size': 2, 'mate_prob': 0.75, 'max_iter': 100, 'mutate_prob': 0.2, 'tourn_size': 5}
regester(name, key, force=True)
regester_map(name, key=None, force=True)
pyrimidine.studga.random() x in the interval [0, 1).

pyrimidine.utils module

Helper functions

pyrimidine.utils.boltzmann_select(xs, fs, T=1)
pyrimidine.utils.choice(xs, *args, **kwargs)

Choose xi from xs with a certain probability

Parameters:

xs (List) – a list of objects

Returns:

the sampling result

Return type:

List

pyrimidine.utils.choice_uniform(xs, *args, **kwargs)

Choose xi from xs with the unifrom probability

Parameters:

xs (List) – a list of objects

Returns:

the sampling result

Return type:

List

pyrimidine.utils.choice_with_fitness(xs, fs=None, n=1, T=1)
pyrimidine.utils.copy(obj, *args, **kwargs)
pyrimidine.utils.hl(x)
pyrimidine.utils.max0(x)
pyrimidine.utils.metropolis_rule(D, T, epsilon=1e-06)

Metropolis rule

Parameters:
  • D (float) – number representing the change of the value

  • T (float) – A number representing temperature

  • epsilon (float, optional) – The l.b. of T

Returns:

change the state or not

Return type:

bool

pyrimidine.utils.pattern(chromosomes)

Get the pattern of the chromosomes

Parameters:

chromosomes (TYPE) – A set of binary chromosomes

Returns:

the pattern of the chromosomes

Return type:

str

Example

>> pattern([[0,1,0], [1,0,0]]) >> # Output “**0”

pyrimidine.utils.prufer_decode(x, nodes=None)

Prufer code to tree

Parameters:
  • x (TYPE) – Prufer code

  • nodes (None, optional) – all nodes of the tree

Returns:

list of pair, representing a tree

Example

>> x = [2,5,6,8,2,5] >> print(prufer_decode(x)) [(1, 2), (3, 5), (4, 6), (6, 8), (7, 2), (2, 5), (5, 8)]

pyrimidine.utils.randint2(lb=0, ub=9, ordered=False)

Select two different numbers in [lb, ub] randomly

Formally i != j ~ U(lb, ub) Applied in GA operations.

Keyword Arguments:
  • (default (ub {number} -- upper bound of interval) – {0})

  • (default – {9})

Returns:

two numbers

pyrimidine.utils.random() x in the interval [0, 1).
pyrimidine.utils.rotate(x, rotations)

Permutate x by the list of rotations rotation

Parameters:
  • x (array-like) – a permutation

  • rotation (list of tuples) – a list of rotations

Return type:

array-like

pyrimidine.utils.rotations(x, y)

The rotations transforming x to y

Parameters:
  • x (array-like) – a permutation of objects

  • y (array-like) – a permutation of objects

Returns:

each tuple represent a rotation (based on indexes)

Return type:

list of tuple

Example

>> rotation([5,2,3,1,4], [2,5,3,4,1]) >> [(0, 1), (3, 4)]