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.
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, **kwargs: ~typing.Any) list[Agent]
Particle Swarm Optimization wrapper for pyswarms.
This function is a simple wrapper to optimize a linkage using PSO. It will mainly call the LocalBestPSO function from pyswarms.single.
- 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, w in pyswarms. The default is .3.
leader – Learning coefficient of each particle, c1 in pyswarms. The default is .2.
follower – Social coefficient, c2 in pyswarms. The default is .5.
neighbors – Number of neighbors to consider. The default is 17.
iters – Number of iterations to describe. 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).
kwargs – keyword arguments to pass to pyswarm.local.single.LocalBestPSO.
- 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.OptimizationProgress(current_iteration: int, total_iterations: int, best_score: float | None = None, is_complete: bool = False)
Bases:
objectProgress information for async optimization.
- Attributes:
current_iteration: Current iteration number. total_iterations: Total number of iterations. best_score: Best score found so far (may be None if not yet available). is_complete: Whether the optimization has completed.
- best_score: float | None = None
- current_iteration: int
- is_complete: bool = False
- property progress_fraction: float
Return progress as a fraction between 0.0 and 1.0.
- total_iterations: int
- 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.
- pylinkage.optimization.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, **kwargs: ~typing.Any) list[Agent]
Particle Swarm Optimization wrapper for pyswarms.
This function is a simple wrapper to optimize a linkage using PSO. It will mainly call the LocalBestPSO function from pyswarms.single.
- 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, w in pyswarms. The default is .3.
leader – Learning coefficient of each particle, c1 in pyswarms. The default is .2.
follower – Social coefficient, c2 in pyswarms. The default is .5.
neighbors – Number of neighbors to consider. The default is 17.
iters – Number of iterations to describe. 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).
kwargs – keyword arguments to pass to pyswarm.local.single.LocalBestPSO.
- Returns:
List of Agents: best score, best dimensions and initial positions.
- Raises:
OptimizationError – If parameters are invalid or optimization fails.
- async pylinkage.optimization.particle_swarm_optimization_async(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>, on_progress: ~collections.abc.Callable[[~pylinkage.optimization.async_optimization.OptimizationProgress], None] | None = None, executor: ~concurrent.futures.thread.ThreadPoolExecutor | None = None, **kwargs: ~typing.Any) list[Agent]
Async version of particle_swarm_optimization.
This function runs the PSO optimization in a thread pool executor to avoid blocking the event loop, while providing progress callbacks and cancellation support.
- 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.
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. If None, it takes len(tuple(linkage.get_num_constraints())).
n_particles – Number of particles in the swarm. The default is 100.
inertia – Inertia of each particle. The default is 0.6.
leader – Learning coefficient of each particle. The default is 3.0.
follower – Social coefficient. The default is 0.1.
neighbors – Number of neighbors to consider. The default is 17.
iters – Number of iterations. The default is 200.
bounds – Bounds to the space, in format (lower_bound, upper_bound).
order_relation – How to compare scores (max or min). Default is max.
on_progress – Optional callback function called with progress updates. The callback receives an OptimizationProgress object.
executor – Optional ThreadPoolExecutor to use. If None, a default executor will be created.
kwargs – Additional keyword arguments passed to LocalBestPSO.
- Returns:
List of Agents: best score, best dimensions and initial positions.
- Raises:
asyncio.CancelledError – If the optimization is cancelled.
OptimizationError – If parameters are invalid or optimization fails.
Example:
async def my_optimization(): def progress_handler(progress): print(f"Progress: {progress.progress_fraction:.1%}") results = await particle_swarm_optimization_async( eval_func=my_fitness, linkage=my_linkage, iters=100, on_progress=progress_handler, ) return results
- pylinkage.optimization.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.
- async pylinkage.optimization.trials_and_errors_optimization_async(eval_func: Callable[[Linkage, Sequence[float], JointPositions], float], linkage: Linkage, parameters: Sequence[float] | None = None, n_results: int = 10, divisions: int = 5, on_progress: Callable[[OptimizationProgress], None] | None = None, executor: ThreadPoolExecutor | None = None, **kwargs: Any) list[MutableAgent]
Async version of trials_and_errors_optimization.
This function runs the grid search optimization in a thread pool executor to avoid blocking the event loop, while providing progress callbacks and cancellation support.
- Parameters:
eval_func – Evaluation function. Input: (linkage, num_constraints, initial_coordinates). Output: score (float).
linkage – Linkage to evaluate.
parameters – Parameters that will be modified. If None, uses tuple(linkage.get_num_constraints()).
n_results – Number of best candidates to return. The default is 10.
divisions – Number of subdivisions between bounds. The default is 5.
on_progress – Optional callback function called with progress updates.
executor – Optional ThreadPoolExecutor to use. If None, a default executor will be created.
kwargs – Additional arguments for the optimization: - bounds: A 2-tuple containing minimal and maximal bounds. - order_relation: Function to compare scores (max, min, abs). - sequential: If True, consecutive linkages have small variation.
- Returns:
List of (score, dimensions, initial_position) tuples.
- Raises:
asyncio.CancelledError – If the optimization is cancelled.
OptimizationError – If parameters are invalid or no valid solution found.
Example:
async def my_optimization(): def progress_handler(progress): print(f"Progress: {progress.progress_fraction:.1%}") results = await trials_and_errors_optimization_async( eval_func=my_fitness, linkage=my_linkage, divisions=10, on_progress=progress_handler, ) return results