platypus.core module
- class AdaptiveGridArchive(capacity, nobjs, divisions, dominance=<platypus.core.ParetoDominance object>)
Bases:
ArchiveA bounded archive using density to truncate solutions.
The objective space is partitioned into a grid containing
math.pow(divisions, nobjs)cells. Please note that this can quickly result in a large internal array or an integer overflow as eitherdivisionsornobjsgrows.The density of each cell is measured by counting the number of solutions within the cell. When the archive exceeds the desired capacity, a solution is removed from the densest cell(s).
Parameters
- capacityint
The maximum capacity of this archive.
- nobjsint
The number of objectives.
- divisionsint
The number of divisions in objective space
- dominanceDominance
The dominance criteria (default is Pareto dominance).
- adapt_grid()
Adapts the grid by updating the bounds and density.
- add(solution)
Try adding a solution to this archive.
Three outcomes can occur when adding a solution: 1. The solution is non-dominated. The new solution is added to the
archive.
The solution dominiates one or more members of the archive. The dominated solutions are removed and the new solution added.
The solution is dominated by one or more members of the archive. The new solution is rejected and the archive is unchanged.
Parameters
- solutionSolution
The solution to add.
Returns
Trueif the solution is non-dominated and added to the archive,Falseotherwise.
- find_densest()
Finds the grid cell index with the highest density.
- find_index(solution)
Returns the grid cell index of the given solution.
- pick_from_densest()
Picks a solution from the densest grid cell(s).
- class Algorithm(problem, evaluator=None, log_frequency=None, **kwargs)
Bases:
objectBase class for all optimization algorithms.
For most use cases, use the
run()method to execute an algorithm until the termination conditions are satisfied. Internally, this invokes thestep()method to perform each iteration of the algorithm. An termination conditions and callbacks are evaluated after each step.Parameters
- problemProblem
The problem being optimized.
- evaluatorEvaluator
The evalutor used to evaluate solutions. If None, the default evaluator defined in
PlatypusConfigis selected.- log_frequencyint
The frequency to log evaluation progress. If None, the default log frequency defined in
PlatypusConfigis selected.
Attributes
- nfeint
The current number of function evaluations (NFE)
- result: list or Archive
The current result, which is updated after each iteration.
- add_extension(extension)
Adds an extension.
Extensions add functionality to an algorithm at specific points during a run. If multiple extensions are added, they are run in reverse order. That is, the last extension added is the first to run.
Parameters
- extensionExtension
The extension to add.
- evaluate_all(solutions)
Evaluates all of the given solutions.
Subclasses should prefer using this method to evaluate solutions, ideally providing an entire population to leverage parallelization, as it tracks NFE.
Parameters
- solutionslist of Solution
The solutions to evaluate.
- remove_extension(extension)
Removes an extension.
Parameters
- extensionExtension or Type
The extension or type of extension to remove.
- run(condition, callback=None)
Runs this algorithm until the termination condition is reached.
Parameters
- conditionint or TerminationCondition
The termination condition. Providing an integer value is converted into the
MaxEvaluationscondition.- callbackCallable, optional
Callback function that is invoked after every iteration. The callback is passed this algorithm instance.
- abstract step()
Performs one logical step of the algorithm.
- class Archive(dominance=<platypus.core.ParetoDominance object>)
Bases:
objectAn archive containing only non-dominated solutions.
Since an archive stores non-dominated solutions, its size can potentially grow unbounded. Consider using one of the subclasses that provide truncation.
Parameters
- dominanceDominance
The dominance criteria (default is Pareto dominance).
- add(solution)
Try adding a solution to this archive.
Three outcomes can occur when adding a solution: 1. The solution is non-dominated. The new solution is added to the
archive.
The solution dominiates one or more members of the archive. The dominated solutions are removed and the new solution added.
The solution is dominated by one or more members of the archive. The new solution is rejected and the archive is unchanged.
Parameters
- solutionSolution
The solution to add.
Returns
Trueif the solution is non-dominated and added to the archive,Falseotherwise.
- append(solution)
Append a solution to this archive.
This is similar to
add()except no result is returned.Parameters
- solutionSolution
The solution to append.
- class AttributeDominance(getter, larger_preferred=True)
Bases:
DominanceDominance based on the value of an attribute.
The referenced attribute must be numeric, typically either an int or float.
Parameters
- getterCallable
Function that reads the value of the attribute from each solution.
- larger_preferredbool
Determines if larger or smaller values are preferred.
- compare(solution1, solution2)
Compare two solutions for dominance.
Parameters
- solution1Solution
The first solution.
- solution2Solution
The second solution.
Returns
-1 if the first solution dominates the second, 1 if the second solution dominates the first, or 0 if the two solutions are mutually non-dominated.
- class Constraint(op, value=None)
Bases:
objectDefines an constraint on an optimization problem.
A constraint can be defined in several ways. First, with a given operator and value:
Constraint("<=", 10)
Second, by providing a string with the operator and value together:
Constraint("<= 10")
Third, by providing a function to compute the constraint value, where any non-zero value is considered a constraint violation:
Constraint(lambda x : 0 if x <= 10 else math.abs(10 - x))
Parameters
- opstr or Callable
The operator, such as
"<=", the full constraint including the value, such as"<=0", or a function to compute the constraint value.- valuefloat, optional
The value of the constraint. This is only required when passing an operator without a value to
op.
- class Direction(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
EnumDefines the optimization direction for an objective.
- class Dominance
Bases:
objectCompares two solutions for dominance.
- abstract compare(solution1, solution2)
Compare two solutions for dominance.
Parameters
- solution1Solution
The first solution.
- solution2Solution
The second solution.
Returns
-1 if the first solution dominates the second, 1 if the second solution dominates the first, or 0 if the two solutions are mutually non-dominated.
- class EpsilonBoxArchive(epsilons)
Bases:
ArchiveArchive based on epsilon-box dominance.
Uses
EpsilonDominanceto limit the size of the archive. This avoids adding many non-dominated solutions that are similar to one another, as controlled by the providedepsilons.Parameters
- epsilonslist of float
The epsilons that control the size of the epsilon boxes.
Attributes
- improvementsint
Tracks the number of epsilon-box improvements, which by definition counts the number of new solutions accepted into this archive.
- add(solution)
Try adding a solution to this archive.
Three outcomes can occur when adding a solution: 1. The solution is non-dominated. The new solution is added to the
archive.
The solution dominiates one or more members of the archive. The dominated solutions are removed and the new solution added.
The solution is dominated by one or more members of the archive. The new solution is rejected and the archive is unchanged.
Parameters
- solutionSolution
The solution to add.
Returns
Trueif the solution is non-dominated and added to the archive,Falseotherwise.
- class EpsilonDominance(epsilons)
Bases:
DominanceEpsilon dominance.
Similar to Pareto dominance except if the two solutions are contained within the same epsilon-box, the solution closer to the optimal corner of the box is preferred.
Parameters
- epsilonslist of float
The epsilons that define the sizes of the epsilon-box.
- compare(solution1, solution2)
Compare two solutions for dominance.
Parameters
- solution1Solution
The first solution.
- solution2Solution
The second solution.
Returns
-1 if the first solution dominates the second, 1 if the second solution dominates the first, or 0 if the two solutions are mutually non-dominated.
- class FitnessArchive(fitness, dominance=<platypus.core.ParetoDominance object>, larger_preferred=True, getter=<function fitness_key>)
Bases:
ArchiveA bounded archive that uses fitness to truncate solutions.
Fitness is a generic term, simply referring to numeric attributes assigned to a solution. For instance, below we use
crowding_distance()to assign thecrowding_distanceattribute, andcrowding_distance_key()to read those values:FitnessArchive(crowding_distance, getter=crowding_distance_key)
Refer to
truncate_fitness()for more details.Parameters
- fitnessCallable
Function for calculating and assigning a fitness attribute to all members of the archive.
- dominanceDominance
The dominance criteria (default is Pareto dominance).
- larger_preferredbool
Determines if larger or smaller fitness values are preferred during truncation.
- getterCallable
Function that reads the fitness attribute from a solution. This should match the attribute assigned by the
fitnessfunction.
- class Generator
Bases:
objectAbstract class for generating initial populations.
- class Indicator
Bases:
objectAbstract class for performance indicators.
- class MaxEvaluations(nfe)
Bases:
TerminationConditionTermination condition based on the maximum number of function evaluations.
Parameters
- nfeint
The maximum number of function evaluations to run the algorithm.
- initialize(algorithm)
Initializes this termination condition.
This method is called once at the start of a run, and should be used to record any initial state. Also consider that users can call
runmultiple times, where each invocation continues the execution of the run from where it left off.Parameters
- algorithmAlgorithm
The algorithm instance.
- shouldTerminate(algorithm)
Checks if the algorithm should terminate.
This method is called after each iteration. The defintion of one “iteration” in specific to each algorithm. For example, a generational algorithm typically produces and evaluates multiple offspring each iteration. Consequently, a run might not stop exactly where the termination condition indicates.
Parameters
- algorithmAlgorithm
The algorithm instance.
Returns
Trueif the termination condition is satisfied and the run should stop;Falseotherwise.
- class MaxTime(max_time)
Bases:
TerminationConditionTermination condition based on the maximum elapsed time.
Parameters
- max_timefloat
The duration, in seconds, to run the algorithm.
- initialize(algorithm)
Initializes this termination condition.
This method is called once at the start of a run, and should be used to record any initial state. Also consider that users can call
runmultiple times, where each invocation continues the execution of the run from where it left off.Parameters
- algorithmAlgorithm
The algorithm instance.
- shouldTerminate(algorithm)
Checks if the algorithm should terminate.
This method is called after each iteration. The defintion of one “iteration” in specific to each algorithm. For example, a generational algorithm typically produces and evaluates multiple offspring each iteration. Consequently, a run might not stop exactly where the termination condition indicates.
Parameters
- algorithmAlgorithm
The algorithm instance.
Returns
Trueif the termination condition is satisfied and the run should stop;Falseotherwise.
- class Mutation
Bases:
VariatorAbstract class for mutation operators.
Mutation is just a special
Variatorwith an arity of 1. While not required, mutation operators typically also produce a single offspring.
- class ParetoDominance
Bases:
DominancePareto dominance with constraints.
If either solution violates constraints, then the solution with a smaller constraint violation is preferred. If both solutions are feasible, then Pareto dominance is used to select the preferred solution.
- compare(solution1, solution2)
Compare two solutions for dominance.
Parameters
- solution1Solution
The first solution.
- solution2Solution
The second solution.
Returns
-1 if the first solution dominates the second, 1 if the second solution dominates the first, or 0 if the two solutions are mutually non-dominated.
- class Problem(nvars, nobjs, nconstrs=0, function=None)
Bases:
WarnOnOverwriteMixinClass representing a problem.
Attributes
- nvars: int
The number of decision variables
- nobjs: int
The number of objectives.
- nconstrs: int
The number of constraints.
- function: callable
The function used to evaluate the problem. If no function is given, it is expected that the evaluate method is overridden.
- types: FixedLengthArray of Type
The type of each decision variable. The type describes the bounds and encoding/decoding required for each decision variable.
- directions: FixedLengthArray of Direction
The optimization direction of each objective, either MINIMIZE (-1) or MAXIMIZE (1)
- constraints: FixedLengthArray of Constraint
Describes the types of constraints as an equality or inequality. The default requires each constraint value to be 0.
- evaluate(solution)
Evaluates the problem.
By default, this method calls the function passed to the constructor. Alternatively, a problem can subclass and override this method. When overriding, this method is responsible for updating the objectives and constraints stored in the solution.
Parameters
- solution: Solution
The solution to evaluate.
- class Selector
Bases:
objectAbstract class for selection operators.
- select(n, population)
Selects N members from the population.
This default implementation operates “with replacement”, meaning solutions can be selected multiple times. Subclasses are allowed to modify this behavior.
Parameters
- nint
The number of solutions to select from the population.
- population: list of Solution
The population of solutions.
- class Solution(problem)
Bases:
WarnOnOverwriteMixinClass representing a solution to a problem.
Parameters
- problem: Problem
The problem.
Attributes
- variables: FixedLengthArray of objects
The values of the variables.
- objectives: FixedLengthArray of float
The values of the objectives. These values will only be assigned after the solution is evaluated.
- constraints: FixedLengthArray of float
The values of the constraints. These values will only be assigned after the solution is evaluated.
- constraint_violation: float
The magnitude of the constraint violation.
- feasible: bool
True if the solution does not violate any constraints; False otherwise.
- evaluated: bool
True if the solution is evaluated; False otherwise.
- evaluate()
Evaluates this solution.
- class TerminationCondition
Bases:
objectAbstract class for defining termination conditions.
- initialize(algorithm)
Initializes this termination condition.
This method is called once at the start of a run, and should be used to record any initial state. Also consider that users can call
runmultiple times, where each invocation continues the execution of the run from where it left off.Parameters
- algorithmAlgorithm
The algorithm instance.
- abstract shouldTerminate(algorithm)
Checks if the algorithm should terminate.
This method is called after each iteration. The defintion of one “iteration” in specific to each algorithm. For example, a generational algorithm typically produces and evaluates multiple offspring each iteration. Consequently, a run might not stop exactly where the termination condition indicates.
Parameters
- algorithmAlgorithm
The algorithm instance.
Returns
Trueif the termination condition is satisfied and the run should stop;Falseotherwise.
- class Variator(arity)
Bases:
objectAbstract class for variation operators (crossover and mutation).
Variation operators must not modify the parents! Instead, create a copy of the parents, set
evaluatedtoFalse, and make any modifications on the copy:child = copy.deepcopy(parent) child.evaluated = False
Parameters
- arityint
The operator arity, or number of required parents.
- class WarnOnOverwriteMixin
Bases:
objectMixin for classes using FixedLengthArray to warn on direct assignment.
- crowding_distance(solutions)
Calculates crowding distance for a non-dominated front.
Computes the crowding distance for a single non-dominated front. It is assumed all solutions are non-dominated. This method assigns the attribute
crowding_distanceto all solutions.Parameters
- solutionsiterable of Solution
The collection of solutions
- nondominated(solutions)
Filters the solutions to only include non-dominated.
Parameters
- solutionsiterable of Solution
The solutions to filter.
Returns
The non-dominated solutions.
- nondominated_prune(solutions, size)
Prunes a population using non-dominated sorting.
Similar to
nondominated_truncate, except the crowding distance is recomputed after each solution is removed.Parameters
- solutionsiterable
The collection of solutions that have been non-domination sorted
- size: int
The size of the truncated result
- nondominated_sort(solutions)
Fast non-dominated sorting.
Performs fast non-dominated sorting on a collection of solutions. The solutions will be assigned the following attributes:
rank- The index of the non-dominated front containing the solution. Rank 0 stores all non-dominated solutions.crowding_distance- The crowding distance of the given solution. Larger values indicate less crowding near the solution.
Parameters
- solutionsiterable of Solution
The collection of solutions
- nondominated_sort_cmp(x, y)
Compares two solutions using nondominated sorting results.
After processing a population with
nondominated_sort(), this comparison function can be used to order solutions by their rank and crowding distance.Parameters
- xSolution
The first solution.
- ySolution
The second solution.
Returns
-1,0, or1to indicate ifxis better, equal, or worse thanybased on rank and crowding distance.
- nondominated_split(solutions, size)
Identify the front that must be truncated.
When truncating a population to a fixed size using non-dominated sorting, identify the front N that can not completely fit within the truncated result. Returns a tuple
(first, last), wherefirstcontains all solutions in the first N fronts (those solutions that will definitely remain after truncation), and thelastis the front that must be truncated.lastcan be empty.Parameters
- solutionsiterable of Solution
The collection of solutions that have been non-dominated sorted
- sizeint
The size of the truncated result
- nondominated_truncate(solutions, size)
Truncates a population using non-dominated sorting.
Truncates a population to the given size. The resulting population is filled with the first N-1 fronts. The Nth front is too large and must be split using crowding distance.
Parameters
- solutionsiterable
The collection of solutions that have been non-domination sorted
- size: int
The size of the truncated result
- normalize(solutions, minimum=None, maximum=None)
Normalizes the solution objectives.
Normalizes the objectives of each solution within the minimum and maximum bounds. If the minimum and maximum bounds are not provided, then the bounds are computed based on the bounds of the solutions.
Returns the minimum and maximum bounds used for normalization along with setting the ‘normalized_objectives’ attribute on each solution.
Parameters
- solutionsiterable
The solutions to be normalized.
- minimumfloat list
The minimum values used to normalize the objectives.
- maximumfloat list
The maximum values used to normalize the objectives.
- truncate_fitness(solutions, size, larger_preferred=True, getter=<function fitness_key>)
Truncates a population based on a fitness value.
Truncates a population to the given size based on fitness values. By default, the attribute
fitnessis used, but can be customized by specifying a customattrgetter.Parameters
- solutionsiterable
The collection of solutions that have already been assigned fitness values
- sizeint
The size of the truncated result
- larger_preferredbool (default True)
If larger fitness values are preferred
- gettercallable (default
attrgetter("fitness")) Retrieves the fitness value from a solution