PyEvopt quickstart

You will need to know a bit of Python. For a refresher, see Python tutorial

Learner profile

This is a quick overview about how to solve an optimization problem using PyEvopt.

Learning Objectives

After reading, you should be able to:
  • Understand how to define problems.

  • Understand how to use an optimizer.

  • Understand how to build an algorithm.

Defining the problem

To be able to solve an optimization problem, first, we need a problem. To represent it user should define the next three points:

  • objective: Mathematic funtion which represents the problem.

  • dimension: Number of variables the problem has.

  • domain: Domain of the objective funtion.

In the following example, it is defined using the rastrigin function with 9 dimensions and domain is -100 to 100.

>>> # Objective
>>> def rastrigin_function(X: npt.ArrayLike) -> float:
>>>    arr = np.array(X)
>>>    def aux(x):
>>>        return x * x - 10 * np.cos(2 * np.pi * x) + 10
>>>    res = np.apply_along_axis(lambda x: aux(x), 0, arr)
>>>    return res.sum()
>>> # Dimension
>>> dimension = 9
>>> # Domain
>>> domain = (-100, 100)

Building an algorithm

An important concept of PyEvopt are the algorithms. It is used by the optimizer to solve the problem. PyEvopt is specialized in evolutionary algorithm.

To build an algorithm, you have to choose it and then pick the operators that fit with your needs.

>>> from pyevopt.genetic import GeneticAlgorithm
>>> from pyevopt.operators.selection import SelectionTournament
>>> from pyevopt.operators.crossover import UniformCrossover
>>> from pyevopt.operators.mutation import NormalMutation
>>> from pyevopt.operators.survival import BasicSurvival
>>> selection = SelectionTournament(3)
>>> crossover = UniformCrossover(0.7)
>>> mutation = NormalMutation(0.01)
>>> survival = BasicSurvival()
>>> alg = GeneticAlgorithm(selection, crossover, mutation, survival)

Users can also build their owns algorithms by create a new class that inherits from the class pyevopt.base.Algorithm

The Optimizer

The is an object which acts like an easy-to-use interface for users. The optimizer take both concept defined before and use it to solve the problem. Optimizer also manage the stop criteria and population initialization with EarlyStopCriteria and Sampler classes respectivly.

The following optimizer, creates a real-valued population with size 60 and do 10 algorithm’s iterations.

First, as we want a real-valued population, we should use the RealSampler class.

>>> from pyevopt.sampler import RealSampler
>>> sampler = RealSampler()

Then, users should define the right EarlyStopriteria:

>>> from pyevopt.early_stop import MaxIterationCriteria
>>> early_stop = MaxIterationCriteria(max_iter=10)

Once it is defined, optimizer can be used.

>>> from pyevopt.optimizer import Optimizer
>>> opt = Optimizer(alg)
>>> y = opt.run(rastrigin_function, dimension, domain, sampler,
    early_stop, pop_size=60)