niapy

niapy.runner

Implementation of Runner utility class.

class niapy.runner.Runner(dimension=10, max_evals=1000000, runs=1, algorithms='ArtificialBeeColonyAlgorithm', problems='Ackley')[source]

Bases: object

Runner utility feature.

Feature which enables running multiple algorithms with multiple problems. It also support exporting results in various formats (e.g. Pandas DataFrame, JSON, Excel)

Variables:
  • dimension (int) – Dimension of problem

  • max_evals (int) – Number of function evaluations

  • runs (int) – Number of repetitions

  • algorithms (Union[List[str], List[Algorithm]]) – List of algorithms to run

  • problems (List[Union[str, Problem]]) – List of problems to run

Initialize Runner.

Parameters:
  • dimension (int) – Dimension of problem

  • max_evals (int) – Number of function evaluations

  • runs (int) – Number of repetitions

  • algorithms (List[Algorithm]) – List of algorithms to run

  • problems (List[Union[str, Problem]]) – List of problems to run

__init__(dimension=10, max_evals=1000000, runs=1, algorithms='ArtificialBeeColonyAlgorithm', problems='Ackley')[source]

Initialize Runner.

Parameters:
  • dimension (int) – Dimension of problem

  • max_evals (int) – Number of function evaluations

  • runs (int) – Number of repetitions

  • algorithms (List[Algorithm]) – List of algorithms to run

  • problems (List[Union[str, Problem]]) – List of problems to run

run(export='dataframe', verbose=False)[source]

Execute runner.

Parameters:
  • export (str) – Takes export type (e.g. dataframe, json, excel) (default: “dataframe”)

  • verbose (bool) – Switch for verbose logging (default: {False})

Returns:

Returns dictionary of results

Return type:

dict

Raises:

TypeError – Raises TypeError if export type is not supported

task_factory(name)[source]

Create optimization task.

Parameters:

name (str) – Problem name.

Returns:

Optimization task to use.

Return type:

Task

niapy.task

The implementation of tasks.

class niapy.task.OptimizationType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Enum representing type of optimization.

Variables:
  • MINIMIZATION (int) – Represents minimization problems and is default optimization type of all algorithms.

  • MAXIMIZATION (int) – Represents maximization problems.

MAXIMIZATION = -1.0
MINIMIZATION = 1.0
class niapy.task.Task(problem=None, dimension=None, lower=None, upper=None, optimization_type=OptimizationType.MINIMIZATION, repair_function=<function limit>, max_evals=inf, max_iters=inf, cutoff_value=None, enable_logging=False)[source]

Bases: object

Class representing an optimization task.

Date:

2019

Author:

Klemen Berkovič and others

Variables:
  • problem (Problem) – Optimization problem.

  • dimension (int) – Dimension of the problem.

  • lower (numpy.ndarray) – Lower bounds of the problem.

  • upper (numpy.ndarray) – Upper bounds of the problem.

  • range (numpy.ndarray) – Search range between upper and lower limits.

  • optimization_type (OptimizationType) – Optimization type to use.

  • iters (int) – Number of algorithm iterations/generations.

  • evals (int) – Number of function evaluations.

  • max_iters (int) – Maximum number of algorithm iterations/generations.

  • max_evals (int) – Maximum number of function evaluations.

  • cutoff_value (float) – Reference function/fitness values to reach in optimization.

  • x_f (float) – Best found individual function/fitness value.

Initialize task class for optimization.

Parameters:
  • problem (Union[str, Problem]) – Optimization problem.

  • dimension (Optional[int]) – Dimension of the problem. Will be ignored if problem is instance of the Problem class.

  • lower (Optional[Union[float, Iterable[float]]]) – Lower bounds of the problem. Will be ignored if problem is instance of the Problem class.

  • upper (Optional[Union[float, Iterable[float]]]) – Upper bounds of the problem. Will be ignored if problem is instance of the Problem class.

  • optimization_type (Optional[OptimizationType]) – Set the type of optimization. Default is minimization.

  • repair_function (Optional[Callable[[numpy.ndarray, numpy.ndarray, numpy.ndarray, Dict[str, Any]], numpy.ndarray]]) – Function for repairing individuals components to desired limits.

  • max_evals (Optional[int]) – Number of function evaluations.

  • max_iters (Optional[int]) – Number of generations or iterations.

  • cutoff_value (Optional[float]) – Reference value of function/fitness function.

  • enable_logging (Optional[bool]) – Enable/disable logging of improvements.

__init__(problem=None, dimension=None, lower=None, upper=None, optimization_type=OptimizationType.MINIMIZATION, repair_function=<function limit>, max_evals=inf, max_iters=inf, cutoff_value=None, enable_logging=False)[source]

Initialize task class for optimization.

Parameters:
  • problem (Union[str, Problem]) – Optimization problem.

  • dimension (Optional[int]) – Dimension of the problem. Will be ignored if problem is instance of the Problem class.

  • lower (Optional[Union[float, Iterable[float]]]) – Lower bounds of the problem. Will be ignored if problem is instance of the Problem class.

  • upper (Optional[Union[float, Iterable[float]]]) – Upper bounds of the problem. Will be ignored if problem is instance of the Problem class.

  • optimization_type (Optional[OptimizationType]) – Set the type of optimization. Default is minimization.

  • repair_function (Optional[Callable[[numpy.ndarray, numpy.ndarray, numpy.ndarray, Dict[str, Any]], numpy.ndarray]]) – Function for repairing individuals components to desired limits.

  • max_evals (Optional[int]) – Number of function evaluations.

  • max_iters (Optional[int]) – Number of generations or iterations.

  • cutoff_value (Optional[float]) – Reference value of function/fitness function.

  • enable_logging (Optional[bool]) – Enable/disable logging of improvements.

convergence_data(x_axis='iters')[source]

Get values of x and y-axis for plotting covariance graph.

Parameters:

x_axis (Literal['iters', 'evals']) – Quantity to be displayed on the x-axis. Either ‘iters’ or ‘evals’.

Returns:

  1. array of function evaluations.

  2. array of fitness values.

Return type:

Tuple[np.ndarray, np.ndarray]

eval(x)[source]

Evaluate the solution A.

Parameters:

x (numpy.ndarray) – Solution to evaluate.

Returns:

Fitness/function values of solution.

Return type:

float

is_feasible(x)[source]

Check if the solution is feasible.

Parameters:

x (Union[numpy.ndarray, Individual]) – Solution to check for feasibility.

Returns:

True if solution is in feasible space else False.

Return type:

bool

next_iter()[source]

Increments the number of algorithm iterations.

plot_convergence(x_axis='iters', title='Convergence Graph')[source]

Plot a simple convergence graph.

Parameters:
  • x_axis (Literal['iters', 'evals']) – Quantity to be displayed on the x-axis. Either ‘iters’ or ‘evals’.

  • title (str) – Title of the graph.

repair(x, rng=None)[source]

Repair solution and put the solution in the random position inside of the bounds of problem.

Parameters:
  • x (numpy.ndarray) – Solution to check and repair if needed.

  • rng (Optional[numpy.random.Generator]) – Random number generator.

Returns:

Fixed solution.

Return type:

numpy.ndarray

stopping_condition()[source]

Check if optimization task should stop.

Returns:

True if number of function evaluations or number of algorithm iterations/generations or reference values is reach else False.

Return type:

bool

stopping_condition_iter()[source]

Check if stopping condition reached and increase number of iterations.

Returns:

True if number of function evaluations or number of algorithm iterations/generations or reference values is reach else False.

Return type:

bool

niapy.callbacks

class niapy.callbacks.Callback[source]

Bases: object

Base class for callbacks.

Callbacks allow you to execute code before and after each iteration of an algorithm.

after_iteration(population, fitness, best_x, best_fitness, **params)[source]

Callback method to be executed after each iteration of the algorithm.

Parameters:
  • population (numpy.ndarray) – The current population of individuals.

  • fitness (numpy.ndarray) – The fitness values corresponding to the individuals.

  • best_x (numpy.ndarray) – The best solution found so far.

  • best_fitness (float) – The fitness value of the best solution found.

  • **params – Additional algorithm parameters.

after_run()[source]

Callback method to be executed after running the algorithm.

before_iteration(population, fitness, best_x, best_fitness, **params)[source]

Callback method to be executed before each iteration of the algorithm.

Parameters:
  • population (numpy.ndarray) – The current population of individuals.

  • fitness (numpy.ndarray) – The fitness values corresponding to the individuals.

  • best_x (numpy.ndarray) – The best solution found so far.

  • best_fitness (float) – The fitness value of the best solution found.

  • **params – Additional algorithm parameters.

before_run()[source]

Callback method to be executed before running the algorithm.

set_algorithm(algorithm)[source]

Set the algorithm property for this callback.

Parameters:

algorithm (Algorithm) – The algorithm object to associate with this callback.

class niapy.callbacks.CallbackList(callbacks=None)[source]

Bases: Callback

Container for Callback objects.

Initialize CallbackList.

Parameters:

callbacks (list, optional) – Existing list of callback objects. Defaults to None.

__init__(callbacks=None)[source]

Initialize CallbackList.

Parameters:

callbacks (list, optional) – Existing list of callback objects. Defaults to None.

after_iteration(population, fitness, best_x, best_fitness, **params)[source]

Execute after_iteration method for all callbacks.

Parameters:
  • population (numpy.ndarray) – The current population of individuals.

  • fitness (numpy.ndarray) – The fitness values corresponding to the individuals.

  • best_x (numpy.ndarray) – The best solution found so far.

  • best_fitness (float) – The fitness value of the best solution found.

  • **params – Additional algorithm parameters.

after_run()[source]

Execute after_run method for each callback in the list.

append(callback)[source]

Append callback to list.

Parameters:

callback (Callback) – Callback to append.

Raises:

ValueError – If callback is not an instance of Callback.

before_iteration(population, fitness, best_x, best_fitness, **params)[source]

Execute before_iteration method for all callbacks.

Parameters:
  • population (numpy.ndarray) – The current population of individuals.

  • fitness (numpy.ndarray) – The fitness values corresponding to the individuals.

  • best_x (numpy.ndarray) – The best solution found so far.

  • best_fitness (float) – The fitness value of the best solution found.

  • **params – Additional algorithm parameters.

before_run()[source]

Execute before_run method for each callback in the list.

set_algorithm(algorithm)[source]

Set the algorithm property for all the callbacks in this list.

Parameters:

algorithm (Algorithm) – The algorithm object to associate with this callback list.