pylinkage.optimization package
Submodules
pylinkage.optimization.grid_search module
Implementation of a grid search optimization.
It should be used for reference only as the search space will almost certainly be too big.
- pylinkage.optimization.grid_search.fast_variator(divisions: int, bounds: tuple[Sequence[float], Sequence[float]]) Generator[list[float], None, None]
Return an iterable of elements’ all possibles variations.
Number of variations: ((max_dim - 1 / min_dim) / delta_dim) ** len(ite).
Here the order in the variations is not important.
- Parameters:
divisions – Number of subdivisions between bounds.
bounds – 2-uple of minimal then maximal bounds.
- Returns:
An iterable of all the dimension combinations.
- pylinkage.optimization.grid_search.sequential_variator(center: Sequence[float] | ndarray[tuple[Any, ...], dtype[floating]], divisions: int, bounds: tuple[Sequence[float], Sequence[float]]) Generator[ndarray[tuple[Any, ...], dtype[floating]], None, None]
Return an iterable of each possible variation for the elements.
Number of variations: ((max_dim - 1 / min_dim) / delta_dim) ** len(ite).
Because linkage is not tolerant to violent changes, the order of output for the coefficients is very important.
The coefficient is in order: middle → min (step 2), min → middle (step 2), middle → max (step 1), so that there is no huge variation.
- Parameters:
center – Elements that should vary.
divisions – Number of subdivisions between bounds.
bounds – 2-uple of minimal then maximal bounds.
- Returns:
An iterable of all the dimension combinations.
- pylinkage.optimization.grid_search.tqdm_verbosity(iterable: Iterable[Any], verbose: bool = True, *args: Any, **kwargs: Any) Generator[Any, None, None]
Wrapper for tqdm, that let you specify if you want verbosity.
Deprecated since version 0.6.0: tqdm_verbosity will be removed in pylinkage 0.7.0, as tqdm can be disabled with the argument disable=True.
- Parameters:
iterable – Iterable to wrap.
verbose – Whether to show progress bar. (Default value = True).
args – Ordered args to pass to tqdm.
kwargs – Keyword args for tqdm.
- pylinkage.optimization.grid_search.trials_and_errors_optimization(eval_func: Callable[[Linkage, Sequence[float], JointPositions], float], linkage: Linkage, parameters: Sequence[float] | None = None, n_results: int = 10, divisions: int = 5, **kwargs: Any) list[MutableAgent]
Return the list of dimensions optimizing eval_func.
Each dimension set has a score, which is added in an array of n_results results, contains the linkages with the best scores in a maximization problem by default.
- Parameters:
eval_func – Evaluation function. Input: (linkage, num_constraints, initial_coordinates). Output: score (float).
linkage – Linkage to evaluate.
parameters – Parameters that will be modified. Geometric constraints. If not, it will be assigned tuple(linkage.get_num_constraints()). The default is None.
n_results – Number of the best candidates to return. The default is 10.
divisions – Number of subdivisions between bounds. The default is 5.
kwargs –
Extra arguments for the optimization.
- boundsA 2-uple (tuple of two elements), containing the minimal and maximal bounds.
If None, we will use parameters as a center. (Default value = None).
- order_relationA function of two arguments, should return the best score of two
scores. Common examples are min, max, abs. (Default value =
max()).
- verboseThe number of combinations will be printed in console if True.
(Default value = True).
sequential : If True, two consecutive linkages will have a small variation.
- Returns:
3-uplet of score, dimensions and initial position for each Linkage to return. Its size is {n_results}.
- Raises:
OptimizationError – If parameters are invalid or no valid solution is found.
pylinkage.optimization.particle_swarm module
Implementation of a particle swarm optimization.
Pure NumPy local-best PSO — no external dependencies beyond numpy.
Created on Fri Mar 8, 13:51:45 2019.
@author: HugoFara
- pylinkage.optimization.particle_swarm.particle_swarm_optimization(eval_func: Callable[[Linkage, Sequence[float], JointPositions], float], linkage: Linkage, center: ~collections.abc.Sequence[float] | float | None = None, dimensions: int | None = None, n_particles: int = 100, leader: float = 3.0, follower: float = 0.1, inertia: float = 0.6, neighbors: int = 17, iters: int = 200, bounds: tuple[~collections.abc.Sequence[float], ~collections.abc.Sequence[float]] | None = None, order_relation: ~collections.abc.Callable[[float, float], float] = <built-in function max>, verbose: bool = True) list[Agent]
Particle Swarm Optimization for linkage parameters.
Uses a local-best ring-topology PSO implemented in pure NumPy.
- Parameters:
eval_func – The evaluation function. Input: (linkage, num_constraints, initial_coordinates). Output: score (float). The swarm will look for the HIGHEST score.
linkage – Linkage to be optimized. Make sure to give an optimized linkage for better results.
center – A list of initial dimensions. If None, dimensions will be generated randomly between bounds. The default is None.
dimensions – Number of dimensions of the swarm space, number of parameters. If None, it takes the value len(tuple(linkage.get_num_constraints())). The default is None.
n_particles – Number of particles in the swarm. The default is 100.
inertia – Inertia of each particle. The default is 0.6.
leader – Cognitive acceleration coefficient (c1). The default is 3.0.
follower – Social acceleration coefficient (c2). The default is 0.1.
neighbors – Number of neighbors in ring topology. The default is 17.
iters – Number of iterations. The default is 200.
bounds – Bounds to the space, in format (lower_bound, upper_bound). (Default value = None).
order_relation – How to compare scores. There should not be anything else than the built-in max and min functions. The default is max.
verbose – The optimization state will be printed in the console if True. (Default value = True).
- Returns:
List of Agents: best score, best dimensions and initial positions.
- Raises:
OptimizationError – If parameters are invalid or optimization fails.
pylinkage.optimization.utils module
This utility module provides various useful functions for optimization.
Created on Mon Jul 12 00:00:01 2021.
@author: HugoFara
- pylinkage.optimization.utils.generate_bounds(center: Iterable[float], min_ratio: float = 5, max_factor: float = 5) tuple[ndarray[tuple[Any, ...], dtype[floating]], ndarray[tuple[Any, ...], dtype[floating]]]
Simple function to generate bounds from a linkage.
- Parameters:
center – 1-D sequence, often in the form of
linkage.get_num_constraints().min_ratio – Minimal compression ratio for the bounds. Minimal bounds will be of the shape center[x] / min_ratio. (Default value = 5).
max_factor – Dilation factor for the upper bounds. Maximal bounds will be of the shape center[x] * max_factor. (Default value = 5).
- Raises:
OptimizationError – If min_ratio or max_factor are not positive.
- pylinkage.optimization.utils.kinematic_maximization(func: Callable[[...], float]) Callable[[Linkage, Iterable[float], JointPositions | None], float]
Standard run for any linkage before a complete fitness evaluation.
This decorator makes a kinematic simulation, before passing the loci to the decorated function. In case of error, the penalty value is -float(‘inf’).
- Parameters:
func – Fitness function to be decorated.
- pylinkage.optimization.utils.kinematic_minimization(func: Callable[[...], float]) Callable[[Linkage, Iterable[float], JointPositions | None], float]
Standard run for any linkage before a complete fitness evaluation.
This decorator makes a kinematic simulation, before passing the loci to the decorated function. In case of error, the penalty value is float(‘inf’).
- Parameters:
func – Fitness function to be decorated.
Module contents
Optimization package.
- class pylinkage.optimization.ParetoFront(solutions: list[~pylinkage.optimization.collections.pareto.ParetoSolution], objective_names: tuple[str, ...] = <factory>)
Bases:
objectCollection of non-dominated solutions from multi-objective optimization.
- Attributes:
solutions: List of Pareto-optimal solutions. objective_names: Names for each objective (for plotting).
- best_compromise(weights: Sequence[float] | None = None) ParetoSolution
Select the best compromise solution.
Uses weighted sum of normalized objectives to find a balanced solution.
- Args:
weights: Weight for each objective. If None, uses equal weights.
- Returns:
The solution with the lowest weighted sum.
- Raises:
ValueError: If the front is empty.
- filter(max_solutions: int) ParetoFront
Filter to a subset of well-distributed solutions.
Uses crowding distance to select diverse solutions.
- Args:
max_solutions: Maximum number of solutions to keep.
- Returns:
New ParetoFront with at most max_solutions solutions.
- hypervolume(reference_point: Sequence[float]) float
Compute the hypervolume indicator.
The hypervolume is the volume of the objective space dominated by the Pareto front and bounded by a reference point. Higher is better.
- Args:
- reference_point: Upper bound for each objective. Should be
worse than any solution in the front.
- Returns:
The hypervolume indicator value.
- Raises:
ImportError: If pymoo is not installed.
- property n_objectives: int
Return the number of objectives.
- objective_names: tuple[str, ...]
- plot(ax: Axes | None = None, objective_indices: tuple[int, int] | tuple[int, int, int] = (0, 1), **kwargs: Any) Figure
Plot the Pareto front.
For 2 objectives: Creates a 2D scatter plot. For 3 objectives: Creates a 3D scatter plot.
- Args:
ax: Matplotlib axes to plot on. If None, creates new figure. objective_indices: Which objectives to plot (indices). **kwargs: Additional arguments passed to scatter().
- Returns:
The matplotlib Figure containing the plot.
- Raises:
ValueError: If the front is empty or indices are invalid.
- scores_array() ndarray[tuple[Any, ...], dtype[floating[Any]]]
Return all scores as a 2D numpy array.
- Returns:
Array of shape (n_solutions, n_objectives).
- solutions: list[ParetoSolution]
- class pylinkage.optimization.ParetoSolution(scores: tuple[float, ...], dimensions: NDArray[np.floating[Any]], initial_positions: JointPositions = (), *, init_positions: JointPositions | None = None)
Bases:
objectA single solution on the Pareto front.
- Attributes:
scores: Objective values, one per objective (all minimized). dimensions: Constraint values that produced this solution. initial_positions: Initial joint positions used during optimization.
- dimensions: NDArray[np.floating[Any]]
- dominates(other: ParetoSolution) bool
Check if this solution dominates another.
A solution dominates another if it is at least as good in all objectives and strictly better in at least one.
- Args:
other: Another Pareto solution to compare against.
- Returns:
True if this solution dominates the other.
- property init_positions: JointPositions
Backwards-compatible alias for
initial_positions.
- initial_positions: JointPositions = ()
- scores: tuple[float, ...]
- pylinkage.optimization.generate_bounds(center: Iterable[float], min_ratio: float = 5, max_factor: float = 5) tuple[ndarray[tuple[Any, ...], dtype[floating]], ndarray[tuple[Any, ...], dtype[floating]]]
Simple function to generate bounds from a linkage.
- Parameters:
center – 1-D sequence, often in the form of
linkage.get_num_constraints().min_ratio – Minimal compression ratio for the bounds. Minimal bounds will be of the shape center[x] / min_ratio. (Default value = 5).
max_factor – Dilation factor for the upper bounds. Maximal bounds will be of the shape center[x] * max_factor. (Default value = 5).
- Raises:
OptimizationError – If min_ratio or max_factor are not positive.
- pylinkage.optimization.kinematic_maximization(func: Callable[[...], float]) Callable[[Linkage, Iterable[float], JointPositions | None], float]
Standard run for any linkage before a complete fitness evaluation.
This decorator makes a kinematic simulation, before passing the loci to the decorated function. In case of error, the penalty value is -float(‘inf’).
- Parameters:
func – Fitness function to be decorated.
- pylinkage.optimization.kinematic_minimization(func: Callable[[...], float]) Callable[[Linkage, Iterable[float], JointPositions | None], float]
Standard run for any linkage before a complete fitness evaluation.
This decorator makes a kinematic simulation, before passing the loci to the decorated function. In case of error, the penalty value is float(‘inf’).
- Parameters:
func – Fitness function to be decorated.