Problems, results and runs¶
All core classes are available from the top-level package, for example ypea.Problem.
Problem ¶
Problem(vars, objective, sense='min', *, n_obj=None, vectorized=False, constraints='feasibility', penalty=1000000.0, equality_atol=0.0001, equality_rtol=1e-06, equality_scale=1.0, constraint_scaling=True, name=None, optimum=None, info=None)
An optimization problem.
Parameters
vars(Variable or list of Variable): The decision variables. Names must be unique.objective(callable or None): Called with a decodedSolution. Returns the objective valuef, or(f, g)wheregis a constraint value or a list of them, each satisfied wheng <= 0, or(f, g, h)wherehis an equality constraint value or a list of them, each satisfied whenhis close to 0 (seeequality_atol).gmay be None when there are only equalities. With several objectives,fis a list or array ofn_objvalues, never a tuple. Pass None to evaluate the solutions yourself withAlgorithm.ask_tell.solvethen raises an error.sense: "min" or "max", or a list with one of them per objective A single string applies to every objective.n_obj(int, optional): Number of objectives (default 1, or the length ofsensewhen it is a list). With more than one, the problem needs a multi-objective algorithm, orypea.scalarizeto turn it into a single-objective problem.vectorized(bool): If True,objectiveis called once per population with aSolutionwhose attributes have a leading population axis, and returns arrays:fwith shape (n,) (or (n, n_obj) with several objectives), andgwith shape (n,) or (n, number of constraints).constraints("feasibility" or "penalty"): How constrained solutions are compared (see the guide Objectives and constraints).penalty(float): Penalty coefficient, used withconstraints="penalty".equality_atol,equality_rtol,equality_scale(float, float, float or list of float): An equalityh = 0counts as satisfied when|h| <= atol + rtol * scale, as innumpy.isclose. Otherwise its violation|h| - (atol + rtol * scale)adds to the total violation.equality_scaleis the typical size of each equality (one number for all, or one per equality). The defaults are 1e-4 (the CEC rule), 1e-6 and 1.constraint_scaling(bool or list of float): How the violations of the constraints are added up. With True (the default), each constraint is divided by its largest violation among the first solutions of a run (at least 20, see the user guide), so constraints of different sizes count alike, as Deb (2000) recommends. The scales then stay fixed for the run and are kept inResult.constraint_scale. False adds the raw violations. A list gives fixed scales, one per constraint (the inequalities, then the equalities).name(str, optional): Name for results and reports. Default: the name of the objective function.optimum(float, optional): Known optimal objective value. Results then report the error|f - optimum|.info(dict, optional): Free metadata, for example{"x_opt": ..., "source": ...}for benchmarks and test problems. Values should be plain Python or NumPy data, so the problem can be pickled.
sense
instance-attribute
¶
sense = parse_sense(senses[0]) if self.n_obj == 1 else [parse_sense(s) for s in senses]
_equality_tolerance
instance-attribute
¶
_equality_tolerance = (self.equality_atol, self.equality_rtol, scale)
decode ¶
decode(X)
Decode codes of shape (n, code_size). Returns a batch Solution if vectorized,
otherwise a list of Solution.
encode ¶
encode(solution)
Code vector of a solution given as a Solution or a dict of variable values.
evaluate ¶
evaluate(solution)
Objective value (an array with several objectives) and total violation of one decoded solution.
Solution ¶
A decoded solution. Each variable is an attribute (sol.x) and also a key (sol["x"]).
Writing your own algorithm by subclassing Algorithm is provisional in the 1.x releases: the methods below are stable, but the helpers that the built-in algorithms use may change.
Algorithm ¶
Algorithm(*, max_iter=None, pop_size=100, max_nfe=None, target=None, max_time=None, display=False, x0=None, local_search=None, local_search_prob=0.1, local_search_nfe=100)
Base class. Subclasses implement initialize() and iterate().
Common settings
max_iter(int or None): Maximum number of iterations. If None (the default), the run is limited only bymax_nfeandmax_time, and when neither is set,max_iteris 100.pop_size(int): Population size.max_nfe(int or None): Maximum number of objective function evaluations. Never exceeded.target(float or None): Stop when a feasible solution at least this good is found.max_time(float or None): Stop after this many seconds (checked between iterations).display(bool): Print one line per iteration.x0(starting solutions, or None): One solution or a list of them: code arrays in [0, 1] (shape (d,) or (k, d)), decoded solutions (aSolutionor a dict of variable values),Individualobjects, or aResult(its best solution, or its front with several objectives). They become the first members of the initial population, and the rest is random. Restarts stay random. None (default) starts at random.local_search(an algorithm, or None (default)): Makes the run memetic: each newly evaluated solution is improved, with probabilitylocal_search_prob(default 0.1), by a short run of this algorithm (for exampleHillClimbing()) of at mostlocal_search_nfeevaluations (default 100), started from it. A better solution replaces it (Lamarckian). The evaluations count toward the budget. Not for the single-solution methods and Sequence.
Inside initialize() and iterate() a subclass can use self.rng,
self.problem, self.pop, self.iter, self.nfe, self.best and the
helpers below. The best solution so far is tracked automatically.
objectives says which problems the algorithm solves: "single" (one objective),
"multi" (several) or "both". solve and ask_tell check it. An algorithm that
solves several objectives reads the archive of non-dominated solutions as
self.front (self.best is then None), and may take a max_archive setting
(stored under that name), which limits the archive by crowding distance.
solve ¶
solve(problem, *, seed=None, callbacks=(), executor=None, keep_evaluations=False)
Solve problem and return a Result.
seed: int, numpy Generator, ypea.StudioRng, or None The same integer seed gives the same result. (A NumPy Generator is consumed by the run.) AStudioRngdraws the same numbers as YPEA Studio, and each run starts its stream from the beginning, so the same object gives the same result.callbacks(list of callables): Each is called ascb(algorithm)after every iteration. A callback that returns True stops the run. Objects may also defineon_start(algorithm)andon_end(algorithm, result).executor(concurrent.futures.Executor, optional): Evaluate solutions in parallel (not used for vectorized problems).keep_evaluations(bool): Keep every evaluated solution inResult.evaluations(off by default, because it needs memory for all of them).
ask_tell ¶
ask_tell(problem, *, seed=None, callbacks=(), keep_evaluations=False)
Start a run whose solutions you evaluate yourself, and return its AskTell handle.
ask() gives the next batch of decoded solutions, tell(values) takes their
objective values, and result() gives the same Result that solve gives
when the values are the same. seed and callbacks are as in solve. The
run uses a copy of this algorithm, so the algorithm can start other runs meanwhile.
The problem may have objective=None. keep_evaluations is as in solve.
iterate ¶
iterate()
Run one iteration: create, evaluate and select new solutions. Every algorithm implements it.
request_stop ¶
request_stop(reason)
Stop the run after the current iteration, with reason as the stop reason.
progress ¶
progress()
Fraction of the run used before the current iteration, from 0 to 1: the largest of nfe / max_nfe, (iter - 1) / (iteration limit - 1) and elapsed / max_time. Use it for schedules that must end when the run ends, whichever limit stops it.
planned_iterations ¶
planned_iterations(evals_per_iter)
Expected number of iterations, for schedules that must end with the run (for example the SA temperature). Uses whichever limit binds first.
check_problem ¶
check_problem(problem)
Check settings that depend on the problem before a run (override it, for example to check that the operators fit the variables). Raise ValueError.
nondominated_sort ¶
nondominated_sort(pop)
Front of each solution, 0 for the non-dominated ones (Deb et al. 2002).
crowding_distance ¶
crowding_distance(pop, ranks=None)
Crowding distance of each solution within its front (Deb et al. 2002).
AskTell ¶
AskTell(algorithm, problem, seed=None, callbacks=(), keep_evaluations=False)
A run whose solutions you evaluate yourself. Create it with Algorithm.ask_tell.
::
run = ypea.PSO(max_nfe=500).ask_tell(problem, seed=0)
while not run.done:
solutions = run.ask()
run.tell([my_objective(s) for s in solutions])
result = run.result()
ask() returns the next batch of decoded solutions: a list of Solution objects,
or for a vectorized problem one Solution whose attributes have a leading batch
axis. Their codes are in codes. tell(values) takes what the objective would
return: one value f, (f, g) or (f, g, h) per solution, or for a vectorized
problem the arrays f, (f, g) or (f, g, h) for the whole batch. With several
objectives each f is a list or array of n_obj values (an array of shape
(n, n_obj) for a vectorized problem). The batch size changes from call to
call (some algorithms ask for one solution at a time), and the run never asks for more
than max_nfe evaluations.
Callbacks run in the worker thread, between tell() and the return of the next
batch. max_time counts the time you spend evaluating.
Attributes
done(bool): True when the run has ended.result()then gives itsResult.codes(numpy.ndarray or None): Codes of the batch thatask()returned last, with shape (n, code_size).algorithm(Algorithm): The copy of the algorithm that runs, for example to readiterorpopin between (only while the run waits for values).
tell ¶
tell(values)
Give the objective values of the batch that ask() returned, in the same order.
The run then continues until it asks for the next batch or ends. An exception of the algorithm or of a callback is raised here.
stop ¶
stop(reason='stopped')
End the run now and return its Result, with reason as the stop reason.
Result
dataclass
¶
Result(best, history, algorithm, params, problem, seed, nfe, iterations, run_time, stop_reason, optimum=None, extra=dict(), front=None, best_feasible=None, evaluations=None, constraint_scale=None)
What Algorithm.solve returns.
best is the best solution by the problem's comparison rules (with
constraints="penalty" it may be infeasible). best_feasible is the best feasible
solution by objective value alone, or None when no feasible solution was found. With
the default feasibility rules it equals best once a feasible solution exists.
With several objectives, best and best_feasible are None, and front holds
the non-dominated solutions (a Front). evaluations holds every evaluated
solution when the run was started with keep_evaluations=True.
constraint_scale holds the scale of each constraint (the inequalities, then the
equalities) when the problem scales its constraints, or None. Every violation in the
result is the sum of the violations divided by these scales.
error
property
¶
error
Distance of the best objective value from the known optimum, if there is one.
to_dict ¶
to_dict()
Plain Python data (JSON ready): settings, seed, best solution (or the front), history and trace, and the evaluations when they were kept.
summary ¶
summary()
A short text summary of the run: the best value (or the front), the budget used and the stop reason.
History
dataclass
¶
History(iteration, nfe, best_obj_value, best_violation, time, trace_nfe, trace_obj_value, trace_violation, trace_feasible_nfe=None, trace_feasible_obj_value=None, archive_size=None, trace_removed_nfe=None)
Per iteration records, plus the exact trace of improvements.
iteration, nfe, best_obj_value, best_violation and time have one
entry per iteration (iteration 0 is the initialization). trace_nfe,
trace_obj_value and trace_violation have one entry per improvement of the best.
trace_feasible_nfe and trace_feasible_obj_value have one entry per improvement
of the best feasible solution.
With several objectives, best_obj_value is NaN, best_violation is the smallest
violation in the front, and archive_size gives the size of the front, all per
iteration. The trace then logs the front exactly: one entry per solution that entered
it, with trace_obj_value of shape (entries, n_obj), and trace_removed_nfe the
NFE at which that solution left the front (-1 if it is still there). front_at(nfe)
rebuilds the front at any number of evaluations, for example to compute an indicator.
at_nfe ¶
at_nfe(points)
Best objective value found within each number of evaluations in points.
A number for a single point, an array for several. NaN before the first evaluation. One objective only.
front_at ¶
front_at(nfe)
Several objectives: the objective values of the front after nfe evaluations,
shape (k, n_obj).
front_mask ¶
front_mask(nfe)
Several objectives: a boolean mask of the trace entries that formed the front after
nfe evaluations, for example trace_violation[mask].
Front
dataclass
¶
Front(positions, obj_values, violations, solutions)
The non-dominated solutions of a multi-objective run (Result.front).
positions has shape (k, code_size), obj_values (k, n_obj) and violations
(k,). solutions holds the k decoded solutions. The rows are sorted by the first
objective (then the second, and so on), best first. front[i] gives an
Individual whose obj_value is an array.
feasible
property
¶
feasible
True for each feasible solution (all of them, once any feasible solution was found).
Evaluations
dataclass
¶
Evaluations(nfe, positions, obj_values, violations)
Every evaluated solution of a run (Result.evaluations), in evaluation order.
nfe is the evaluation number of each row (1, 2, ...), positions the codes,
obj_values the objective values (shape (n,), or (n, n_obj) with several
objectives) and violations the total constraint violations. Non-finite objective
values are stored as the worst value, as the run saw them. Index it like an array to
filter or sort: ev[ev.feasible], ev[np.argsort(ev.obj_values)]. Decode rows
with problem.decode(ev.positions).
scalarize ¶
scalarize(problem, weights, method='weighted_sum', ideal=None)
A single-objective problem from a multi-objective one, to minimize.
Parameters
problem(Problem): A problem with several objectives.weights(list of float): One nonnegative weight per objective, not all zero.method: "weighted_sum" or "tchebycheff""weighted_sum"minimizessum(w_i * s_i * f_i), withs_i = 1for an objective to minimize and -1 for one to maximize. It finds only points on the convex parts of the front."tchebycheff"minimizesmax(w_i * |f_i - z_i|)(Zhang and Li 2007), which can reach every point of the front.ideal(list of float): The ideal pointzfor Tchebycheff, in the units of the objectives: a value at least as good as the best possible value of each objective. Required for"tchebycheff".
The new problem has the same variables, constraints and settings. Its objective calls the original one and combines the values, so constraint values pass through.
Individual
dataclass
¶
Individual(position, solution, obj_value, violation=0.0)
One solution: its code, decoded solution, objective value and constraint violation.
Population ¶
Population(X, F, V)
A set of solutions stored as arrays.
X holds the codes in [0, 1] with shape (n, d), F the objective values with
shape (n, m) (m = 1 with one objective), and V the total constraint violation with shape (n,).
Best ¶
Best(X, F, V)
The best solution so far (alg.best): a population of one whose obj_value
and violation are numbers, as in result.best.
Comparator ¶
Comparator(sense='min', constraint_handling='feasibility', penalty=1000000.0)
Compares solutions by the senses of the objectives and the constraint handling.
sense is "min" or "max" for one objective, or a list with one of them per
objective. With one objective, sense is a string and sign is 1.0 or -1.0.
With several, sense is a list and sign an array with one entry per objective.
dominates ¶
dominates(F1, V1, F2, V2, rule=None)
Element-wise: does solution 1 dominate solution 2? Broadcasts.
F has shape (..., m) and V shape (...). rule is the constraint handling,
"feasibility" or "penalty", by default the comparator's own.
"feasibility"(constrained domination, Deb et al. 2002): a feasible solution dominates an infeasible one, an infeasible one dominates another with a larger violation, and two feasible ones are compared by Pareto dominance. Two infeasible solutions with exactly the same violation are also compared by Pareto dominance (the paper leaves both non-dominated)."penalty": Pareto dominance of the penalized objectivesf + penalty * v(each objective turned into minimization first). Equal penalized objectives are decided by the lower violation.
With one objective both rules give the same answer as better.
nondominated_sort ¶
nondominated_sort(F, V, rule=None)
Fast non-dominated sorting (Deb et al. 2002) by dominates with rule.
Returns the front of each solution: 0 for the solutions that no other one dominates, 1 for those dominated only by solutions of front 0, and so on. Uses memory for an n by n matrix.
crowding_distance ¶
crowding_distance(F, ranks=None)
Crowding distance of Deb et al. (2002), computed within each front (all
solutions form one front when ranks is None). Larger means less crowded.
For each objective, the front is sorted by that objective, the two boundary solutions get an infinite distance, and every other solution adds the gap between its two neighbors divided by the range of that objective in the front. A front of one or two solutions gets infinite distances, and an objective with no range adds nothing. The sort is stable, so of two equal values the first one comes first.
random ¶
The Studio generator: an opt-in random generator shared with YPEA Studio.
Pass it as the seed of a run, algorithm.solve(problem, seed=ypea.StudioRng(123)), and
the run draws exactly the same numbers as YPEA Studio with the same seed. Without it,
ypea uses NumPy's default generator, as before.
The core is Philox2x32-10 (Salmon, Moraes, Dror and Shaw, 2011), a counter based generator, so whole batches are computed at once. ln, cos and sin are built from basic arithmetic in a fixed order, so the draws match the Studio engine bit for bit. The full specification is spec/rng.md in the YPEA Studio project.
StudioRng offers the eight numpy.random.Generator methods that ypea's algorithms
call, with the same signatures: random, uniform, integers, standard_normal,
standard_cauchy, geometric, choice (with or without p, always with
replacement) and permutation. New algorithm code must use only these. Batch draws are
fast, single draws are slower than NumPy's. derive_seed(base, i) gives the seed of run
i of an experiment with base seed base, as in Studio.
Do not change the arithmetic here without changing the Studio engine and the shared test cases (tests/data/studio) together.