Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

metaheuristic-designer

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

metaheuristic-designer

A python package to desing metaheuristic optimization algorithms from components.

  • 0.1.5
  • PyPI
  • Socket score

Maintainers
1

Metaheuristic-designer

Documentation Status

This is an object-oriented framework for the development, testing and analysis of metaheuristic optimization algorithms.

It defines the components of a general evolutionary algorithm and offers some implementations of algorithms along with components that can be used directly. Those components will be explained below.

It was inspired by the article Metaheuristics “in the large” that discusses some of the issues in the research on metaheuristic optimization, sugesting the development of libraries for the standarization of metaheuristic algorithms.

Most of the design decisions are based on the book Introduction to evolutionary computing by Eiben, Agoston E., and James E. Smith which is very well expained and is highly recomended to anyone willing to learn about the topic.

This framework doesn't claim to have a high performance, specially since the chosen language is Python and the code has not been designed for speed. This shouldn't really be an issue since the highest amount of time spent in these kind of algorithms tends to be in the evaluation of the objective function. If you want to compare an algorithm made with this tool with another one that is available by other means, it is recomended to use the number of evaluations of the objective function as a metric instead of execution time.

Instalation

The package is available in the PyPi repository (https://pypi.org/project/metaheuristic-designer/).

To install it, use the pip command as follows:

pip install metaheuristic-designer

Examples

  • There are 2 scripts to test this repository:
    • "examples/exec_basic.py": Optimize a simple function, in this case, the "sphere" function that calculates the squared norm of a vector, we want a vector that minmizes this function. There are two possible flags that can be added:
      • "-a [Alg]" use one of the available algorithms, the choices are:
        • HillClimb: simple hill climbing algorithm.
        • LocalSearch: take the best of 20 randomly chosen neighbours.
        • ES: (100+150)-ES, basic evolutionary strategy.
        • HS: Harmony search algorithm.
        • GA: genetic algorithm.
        • SA: simulated annealing algorithm.
        • DE: DE/best/1, differential evolution algorithm.
        • PSO: simple particle swarm algorithm.
        • NoSearch: no search is done.
      • "-m" use a memetic search like structure, do local search after mutation.
    • "examples/exec_basic.py": Evolve an image so that it matches the one given as an input.
      • The same parameters as the previous script.
      • "-i [Image path]" read the image and evolve a random image into this one.

It is recomended that you create a virtual environment to test the examples.

This is done with the following commands:

python -m venv venv
source venv/bin/activate
pip install .[examples]

Once you have activate the virtual environment, you can execute one of the examples like this:

python examples/example_basic.py

or

python examples/image_evolution.py

To run the tests you need to install nox, to execute the tests use the command

nox test

Implemented components

This package comes with some already made components that can be used in any algorithm in this framework

Search strategies

The algorithms implemented are:

Class nameStrategyParamsOther info
NoSearchDo nothingFor debugging purposes
RandomSearchRandom Search
HillClimbHill climb
LocalSearchLocal seachiters (number of neighbors to test each time)
SASimulated annealingiter (iterations per temperature change), temp_init (initial temperature), alpha (exponent of the temperature change)
GAGenetic algorithmpmut (probability of mutation), pcross (probability of crossover)
ESEvolution strategyoffspringSize (number of indiviuals to generate each generation)
HSHarmony searchHSM, HMCR, BW, PAR
PSOParticle Swarm optimizationw,c1,c2
DEDifferential evolution
CROCoral Reef Optimizationrho,Fb,Fd,Pd,attempts
CRO_SLCoral Reef Optimization with substrate layersrho,Fb,Fd,Pd,attempts
PCRO_SLprobabilistic Coral Reef Optimization with substrate layersrho,Fb,Fd,Pd,attempts
DPCRO_SLDynamic probabilistic Coral Reef Optimization with substrate layersrho,Fb,Fd,Pd,attempts,group_subs,dyn_method,dyn_steps,prob_amp
VNDVariable neighborhood descent
RVNSRestricted variable neighborhood searchIn progress
VNSVariable neighborhood searchIn progress
CMA_ESCovariance matrix adaptation - Evolution strategyNot implemented yet

Survivor selection methods

These are methods of selecting the individuals to use in future generations.

The methods implemented are:

Method nameAlgorithmParamsOther info
"Elitism"Elitismamount
"CondElitism"Conditional Elitismamount
"nothing" or "generational"Replace all the parents with their childrenNeeds the offspring size to be equal to the population size
"One-to-one" or "HillClimb"One to one (compare each parent with its child)Needs the offspring size to be equal to the population size
"Prob-one-to-one" or "ProbHillClimb"Probabilitisc One to one (with a chance to always choose the child)pNeeds the offspring size to be equal to the population size
"(m+n)" or "keepbest"(λ+μ), or choosing the λ best individuals taking parents and children
"(m,n)" or "keepoffspring"(λ,μ), or taking the best λ childrenλ must be smaller than μ
"CRO"A 2 step survivor selection method used in the CRO algorithm. Each individual attempts to enter the population K times and then a percentage of the worse individuals will be eliminated from the populationFd,Pd,attempts,maxPopSizeCan return a population with a variable number of individuals

Parent selection methods

These are methods of selecting the individuals that will be mutated/perturbed in each generation

The methods implemented are:

Method nameAlgorithmParamsOther info
"Torunament"Choose parents by tournamentamount, p
"Best"Select the n best individualsamount
"Random"Take n individuals at randomamount
"Roulette"Perform a selection with the roullette methodamount, method, F
"SUS"Stochastic universal samplingamount, method, F
"Nothing"Take all the individuals from the population

Operators

Class nameDomainOther info
OperatorRealReal valued vectors
OperatorIntInteger valued vectors
OperatorBinaryBinary vectors
OperatorPermPermutations
OperatorListVariable length lists
OperatorMetaOther operators
OperatorLambdaAnyLets you specify a function as an operator

The Operators functions available in the operator classes are:

Method nameAlgorithmParamsDomains
"1point"1 point crossoverReal, Int, Bin
"2point"2 point crossoverReal, Int, Bin
"Multipoint"multipoint crossoverReal, Int, Bin
"WeightedAvg"Weighted average crossoverFReal, Int
"BLXalpha"BLX-alpha crossoverCrReal
"Multicross"multi-individual multipoint crossoverNindivReal, Int, Bin
"XOR"Bytewise XOR with a random vectorNInt
"XORCross"Bytewise XOR between 2 vectors component by componentInt
"sbx"SBX crossoverCrReal
"Perm"Permutate vector componentsNReal, Int, Bin, Perm
"Gauss"Add Gaussian noiseFReal, Int
"Laplace"Add noise following a Laplace distributionFReal, Int
"Cauchy"Add noise following a Cauchy distributionFReal, Int
"Poisson"Add noise following a Cauchy distributionFInt
"Uniform"Add Uniform noiseLow, UpReal, Int
"MutRand" or "MutNoise"Add random noise to a number of vector componentsmethod, N, optionaly: Low, Up, FReal, Int
"MutSample"Take a sample from a probability distribution and put it on a number of vector componentsmethod, N, optionaly: Low, Up, FReal, Int
"RandNoise"Add random noisemethod, optionaly: Low, Up, FReal, Int
"RandSample"Sample from a probability distributionmethod, optionaly: Low, Up, FReal, Int
"DE/Rand/1"Sample from a probability distributionF, CrReal, Int
"DE/Best/1"Sample from a probability distributionF, CrReal, Int
"DE/Rand/2"Sample from a probability distributionF, CrReal, Int
"DE/Best/2"Sample from a probability distributionF, CrReal, Int
"DE/Current-to-rand/1"Sample from a probability distributionF, CrReal, Int
"DE/Current-to-best/1"Sample from a probability distributionF, CrReal, Int
"DE/Current-to-pbest/1"Sample from a probability distributionF, Cr, pReal, Int
"PSO"Sample from a probability distributionw, c1, c2Real, Int
"Firefly"Sample from a probability distributiona,b,c,gReal, Int
"Random"Sample from a probability distributionReal, Int, Bin, Perm
"RandomMask"Randomly sample a number of vector componentsNReal, Int
"Swap"Swap two componentsPerm
"Insert"Insert a component and shift to the leftPerm
"Scramble"Scramble permutation orderNPerm
"Invert"Reverse order of componentsPerm
"Roll"Roll components to the rightNPerm
"PMX"Partially mapped crossoverPerm
"OrderCross"Ordered crossoverPerm
"branch"Choose one of the provided operators randomlyOperators
"sequence"Apply all the provided operators in orderOperators
"split"Apply each operator to a subset of vector components following the mask providedOperators
"pick"Manually pick one of the operators provided (setting the chosen_idx attribute)Operators
"Dummy"Assing the vector to a predefined valueAll
"Custom"Provide a lambda function to apply as an operatorfunctionAll
"Nothing"Do nothingAll

Initializers

Initializers create the initial population that will be evolved in the optimization process.

Some of the implemente Initializers are:

Class nameDescriptionOther info
DirectInitializerInitialize the population to a preset list of individuals
SeedProbInitializerInitializes the population with another initializer and inserts user-specified individuals with a probability
SeedDetermInitializerInitializes the population with another initializer and inserts a number of user-specified individuals into the population
GaussianVectorInitializerInitialize individuals with normally distributed vectors
UniformVectorInitializerInitialize individuals with uniformly random distributed vectors
PermInitializerInitialize individuals with random permuations
LambdaInitializerInitialize individuals with a user-defined function

Encodings

Specifying the Encoding is optional but can be very helpful for some types of problems.

An encoding will represent each solution differently in the optimization process and the evaluation of the fintess, since most algorithm work only with vectors, but we might need other types of datatypes for our optimization.

Some of the implemented Encodings are:

Class nameEncodingDecodingOther info
DefaultEncodingMakes no changes to the inputMakes no changes to the input
TypeCastEncodingChanges the datatype of the vector from T1 to T2Changes the datatype of the vectorfrom T1 to T2
MatrixEncodingConverts a vector into a matrix of size NxMConverts a matrix to a vector with the .flatten() method
ImageEncodingConverts a vector into a matrix of size NxMx1 or NxMx3, each component is an unsigned 8bit numberConverts a matrix to a vector with the .flatten() method
LambdaEncodingApplies the user-defined encode functionApplies the user-defined decode function

Benchmark functions

The benchmark functions you can use to test the algorithms are:

Class nameDomainOther info
MaxOnesInteger
DiophantineEqInteger
MaxOnesRealReal
SphereReal
HighCondEllipticReal
BentCigarReal
DiscusReal
RosenbrockReal
AckleyReal
WeistrassReal
GriewankReal
RastriginReal
ModSchwefelReal
KatsuuraReal
HappyCatReal
HGBatReal
SumPowellReal
N4XinSheYangReal
ThreeSATReal
BinKnapsackBinary
MaxCliquePermutation
TSPPermutation
ImgApproxInteger
ImgStdInteger
ImgEntropyInteger

Keywords

FAQs


Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc