genetic_optimizer
Optimization using Genetic Algorithms (GA)
The genetic_optimizer module provides optimizers and wrappers for GA.
As for now, I didn’t try a convincing Genetic Algorithm library. This is why it is built-in here. Feel free to propose a copyleft library on GitHub!
Created on Thu Jun 10 21:20:47 2021.
@author: HugoFara
- class leggedsnake.genetic_optimizer.GeneticOptimization(dna: list[Any], fitness: Callable[[...], tuple[float, list[tuple[float, float]]]], prob: float = 0.07, **kwargs: Any)
Bases:
object- __init__(dna: list[Any], fitness: Callable[[...], tuple[float, list[tuple[float, float]]]], prob: float = 0.07, **kwargs: Any) None
- Parameters:
dna (list)
fitness (callable)
prob (float or tuple[float])
kwargs (dict) –
Other useful parameters for the optimization.
- max_popint, default=11
Maximum number of individuals. The default is 11.
- max_genetic_distfloat, default=.7
Maximum genetic distance, before individuals cannot reproduce (separated species). The default is .7.
- startnstopbool, default=False
Ability to close program without loosing population. If True, we verify at initialization the existence of a data file. Population is saved every int(250 / max_pop) iterations. The default is False.
- fitness_argstuple
Keyword arguments to send to the fitness function. The default is None (no argument sent).
- verboseint
Level of verbosity. 0: no verbose, do not print anything. 1: show a progress bar. 2: complete report for each turn. The default is 1.
- birth(par1: list[Any], par2: list[Any]) list[Any]
Return a new individual with par1 and par2 as parents (two sequences).
Child are generated by a uniform crossover followed by a random “resetting” mutation of each gene. The resetting is a normal law.
Initial positions come from one of the two parents randomly.
- Parameters:
par1 (list[float, tuple of float, tuple of tuple of float]) – Dna of first parent.
par2 (list[float, tuple of float, tuple of tuple of float]) – Dna of second parent.
- Returns:
child – Dna of the child.
- Return type:
list[float, tuple of float, tuple of tuple of float]
- dna: list[Any]
- evaluate_individual(dna: list[Any], fitness_args: tuple[Any, ...] | None) tuple[float, list[tuple[float, float]]]
Simple evaluation for a single individual.
- Parameters:
dna (list[float, tuple of float, tuple of tuple of float]) – List of the individuals’ DNAs
fitness_args (tuple) – Additional arguments to pass to the fitness function. Usually the initial positions of the joints.
- Returns:
Score then initial coordinates.
- Return type:
tuple
See also
evaluate_populationcounterpart for an entire population.
- evaluate_population(fitness_args: tuple[Any, ...] | None, verbose: bool = True, processes: int = 1) None
Evaluate the whole population, attribute scores.
- Parameters:
fitness_args (tuple) – Additional arguments to pass to the fitness function. Usually the initial positions of the joints.
verbose (bool, default=True) – To display information about population evaluation.
processes (int, default=1) – Number of processes involved for a multiprocessor evaluation.
See also
evaluate_individualsame function but on a single DNA.
- fitness: Callable[[...], tuple[float, list[tuple[float, float]]]]
- iters: int
- kwargs: dict[str, Any]
- make_children(parents: list[list[Any]], max_genetic_dist: float = inf) list[list[Any]]
- max_pop: int
- pop: list[list[Any]]
- prob: float
- reduce_population() list[list[Any]]
Reduce the population down to max_pop.
- Returns:
new_population – At most self.max_pop individuals, sorted by score.
- Return type:
list of dna
- run(iters: int, processes: int = 1) list[Agent]
Optimization by genetic algorithm (GA).
- Parameters:
iters (int) – Number of iterations.
processes (int, default=1) – Number of processes that will evaluate the linkages.
- Returns:
List of Agent(score, dimensions, init_positions) sorted by score in descending order. Compatible with pylinkage’s chain_optimizers pipeline.
- Return type:
list[Agent]
- select_parents(verbose: bool = True) list[list[Any]]
Selection 1/4 of the population as parents.
- startnstop: str | bool
- verbosity: int
- leggedsnake.genetic_optimizer.agents_to_ensemble(agents: Sequence[Agent], linkage: Any) Ensemble
Wrap a list of Agents in a pylinkage Ensemble.
Provides
.rank(),.top(),.filter(),.filter_by_score()and numpy-style indexing over optimization results. The template linkage is only used for topology metadata; batch simulation viaEnsemble.simulate()is not supported for Walker-based mechanisms.- Parameters:
agents (sequence of Agent) – Optimization results (e.g. from
genetic_algorithm_optimization).linkage (Walker, Mechanism, or Linkage) – Template. A
Walkeris converted to its underlying Mechanism.
- Returns:
One member per agent, with
scores={"score": agent.score}.- Return type:
Ensemble
- leggedsnake.genetic_optimizer.genetic_algorithm_optimization(eval_func: ~typing.Callable[[...], float], linkage: ~typing.Any, center: ~collections.abc.Sequence[float] | None = None, bounds: tuple[~collections.abc.Sequence[float], ~collections.abc.Sequence[float]] | None = None, order_relation: ~typing.Callable[[float, float], float] = <built-in function max>, max_pop: int = 30, iters: int = 100, prob: float = 0.07, max_genetic_dist: float = 10.0, processes: int = 1, startnstop: str | bool = False, verbose: bool = True, **kwargs: ~typing.Any) Ensemble
Genetic algorithm optimization with the standard pylinkage interface.
This wrapper bridges leggedsnake’s
GeneticOptimizationto pylinkage’s optimizer contract, making it usable withchain_optimizersand interchangeable with PSO, DE, etc.The evaluation function receives
(linkage, dimensions, init_positions)and returns a scalar score — exactly like pylinkage optimizers.- Parameters:
eval_func (callable) – Evaluation function with signature
(linkage, dimensions, init_positions) -> float.linkage (Walker or Linkage) – The mechanism to optimize. Must provide
get_constraints(),set_constraints(),get_coords(),set_coords().center (sequence of float, optional) – Initial dimensions. If None, read from
linkage.chain_optimizersinjects the previous stage’s best here.bounds (tuple of (lower, upper), optional) – Not directly used by the GA, but accepted for API compatibility. When provided, initial random children are clamped to these bounds.
order_relation (callable, optional) –
max(default) for maximization,minfor minimization.max_pop (int) – Maximum population size. Default 30.
iters (int) – Number of generations. Default 100.
prob (float) – Mutation standard deviation. Default 0.07.
max_genetic_dist (float) – Speciation threshold. Default 10.0.
processes (int) – Number of parallel processes for evaluation. Default 1.
startnstop (str or bool) – Path to checkpoint file, or False to disable. Default False.
verbose (bool) – Show progress bar. Default True.
- Returns:
Population wrapped in a pylinkage
Ensemble(one member per candidate, columnar scores). Ranking is already applied: the member at index 0 is the best underorder_relation. Iterate, slice, or call.top()/.rank()/.filter_by_score()to drill down. Useensemble[i].score/.dimensions/.initial_positionsto access fields — or callensemble[i].to_agent()for the legacy tuple shape.- Return type:
Ensemble
- leggedsnake.genetic_optimizer.kwargs_switcher(arg_name: str, kwargs: dict[str, Any], default: Any = None) Any
Simple function to return the good element from a kwargs dict.
- leggedsnake.genetic_optimizer.load_population(file_path: str) list[list[Any]]
Return a population from a given file.
- leggedsnake.genetic_optimizer.save_population(file_path: str, population: list[list[Any]], verbose: bool = False, data_descriptors: dict[str, Any] | None = None) None
Save the population to a json file.
- Parameters:
file_path (str) – Path of the file to write to.
population (list) – Sequence of dna
verbose (bool) – Enable or not verbosity (outputs success).
data_descriptors (dict) – Any additional value you want to save for the current generation.