pylinkage.optimization package

Submodules

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: object

Collection 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: object

A 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.